Transactions

預期的私鑰是長度為 32 的 Uint8Array

  • August 16, 2021

我正在嘗試發送交易,但它會引發錯誤。我仍然沒有發送任何交易只是簽署它……

13) 在 XMLHttpRequestEventTarget.dispatchEvent (C:\web3\node_modules\xhr2-cookies\dist\xml-http-request-event-target.js:34:22) 在 XMLHttpRequest._setReadyState (C:\web3\node_modules\xhr2- cookies\dist\xml-http-request.js:208:14) 在 IncomingMessage 的 XMLHttpRequest._onHttpResponseEnd (C:\web3\node_modules\xhr2-cookies\dist\xml-http-request.js:318:14)。(C:\web3\node_modules\xhr2-cookies\dist\xml-http-request.js:289:61) 在 IncomingMessage.emit (events.js:327:22) 在 endReadableNT (internal/streams/readable.js: 1327:12)

var Tx = require('ethereumjs-tx')

const Web3 = require('web3')
const web3 = new Web3('http://127.0.0.1:7545')

const account1 = '0x67d30ef950015Ab1a03e30ED5d5F2A26de196C4d'
const account2 = '0x04bCD71C67656cFda695F14a9E9Bf8B6064b8AD1'

const privateKey1 = 'c429601ee7a6167356f15baa70fd8fe17b0325dab7047a658a31039e5384bffd'
const privateKey2 = '60495127495614d5aadb1f4561a3989d6636cbe55ada58c685ef28cff01bde21'

const privateKey1Buffer = Buffer.from(privateKey1, 'hex')
const privateKey2Buffer = Buffer.from(privateKey2, 'hex')

console.log('Buffer 1: ', privateKey1Buffer)
console.log('Buffer 2: ', privateKey2Buffer)

web3.eth.getTransactionCount(account1, (err, txCount) => {
   const txObject = {
     nonce:    web3.utils.toHex(txCount),
     to:       account2,
     value:    web3.utils.toHex(web3.utils.toWei('0.1', 'ether')),
     gasLimit: web3.utils.toHex(21000),
     gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
   }

   const tx = new Tx.Transaction(txObject)
   tx.sign(privateKey1)

   const serializedTx = tx.serialize().toString('hex')
   // const raw = '0x' + serializedTx.toString('hex')

   console.log('tx :', tx)
   console.log('serializedTx :', serializedTx)
   console.log('raw :', raw)
 })

這部分是錯誤的。

tx.sign(privateKey1)

像這樣修復它:

tx.sign(privateKey1Buffer)

我有這個錯誤是因為我沒有0x從私鑰的前綴中刪除。

引用自:https://ethereum.stackexchange.com/questions/93909