Web3js
如何為私鑰生成緩衝區
我是乙太坊開發的初學者。我正在使用
Web3 js 1.0
建構一個簡單的節點 js 應用程序,將乙太幣從一個錢包發送到主網上的另一個錢包。我在從私鑰創建緩衝區時遇到問題,不斷收到此錯誤-
錯誤:預期的私鑰是長度為 32 的 Uint8Array。
這是我的程式碼:
//Private keys const key1 = "0xb7bxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; //Generate Byte Buffer for key const buffer1 = Buffer.from(key1, "hex"); const rawTx = { nonce: web3.utils.toHex(count), to: addTo, value: web3.utils.toHex(bal - 10000000000 * 21000), gasLimit: web3.utils.toHex(21000), gasPrice: web3.utils.toHex(10000000000), }; const txn = new Tx(rawTx); txn.sign(buffer1); const serialTx = txn.serialize(); const raw = "0x" + serialTx.toString("hex"); web3.eth.sendSignedTransaction(raw).on("transactionHash", (txHash) => { console.log("transactionHash:", txHash); });
我在某處讀到,您必須在將
0x
私鑰傳遞給 Buffer 方法之前將其從私鑰中刪除?這是真的嗎?
如果您將程式碼更改為此,它應該可以解決問題。
const buffer1 = Buffer.from(key1.substring(2,66), "hex");
嘗試使用以下程式碼:
public function transfer( privateKey: string, fromAccount: string, toAccount: string, amount: string ) { const privateKeyBUF = Buffer.from(privateKey, 'hex'); const contract = new this.web3.eth.Contract( [FunctionsAbi], [ContractAddress], { from: fromAccount } ); amount = this.web3.utils.toHex(this.web3.utils.toWei(amount)); return from(this.web3.eth.getTransactionCount(fromAccount)).pipe( switchMap((count) => { const rawTransaction = { from: fromAccount, gasPrice: this.web3.utils.toHex(20 * 1e9), gasLimit: this.web3.utils.toHex(210000), to: [ContractAddress], value: 0x0, data: contract.methods.transfer(toAccount, amount).encodeABI(), nonce: this.web3.utils.toHex(count), }; const transaction = new Tx(rawTransaction, { chain: 'chain' }); transaction.sign(privateKeyBUF); return from( this.web3.eth.sendSignedTransaction( '0x' + transaction.serialize().toString('hex') ) ); }), map((transaction) => { return transaction; }) ); }