Web3js

不支持未簽名交易 - web3、infura、@ethereumjs/tx

  • March 20, 2022

我正在使用 web3、@ethereumjs/tx 和 infura 發送簽名交易。但是,我收到一個錯誤“不支持未簽名的交易”。

這是我的程式碼,信用

const Web3 = require('web3')
const Tx = require('@ethereumjs/tx').Transaction

const web3 = new Web3(new Web3.providers.HttpProvider('https://rinkeby.infura.io/v3/PROJECT_ID'))

const addressFrom = '0x210490505e07cB9762017288e4729d0f15xxxxxx';
const Key = 'PRIVATE_KEY';
privateKey = Buffer.from(Key, 'hex');
const addressTo = '0x8035f72510907Fe3EE05b4dF439E5D0d977xxxxx';

const txData = {
 gasLimit: web3.utils.toHex(2500000000),
 gasPrice: web3.utils.toHex(10e9), // 10 Gwei
 from: addressFrom,
 to: addressTo,
 //chainId: 4,
 value: web3.utils.toHex(web3.utils.toWei('123', 'wei'))
}

const sendRawTransaction = txData =>
 web3.eth.getTransactionCount(addressFrom).then(txCount => {
   const newNonce = web3.utils.toHex(txCount)
   const transaction = new Tx({ ...txData, nonce: newNonce }, { chain: 'rinkeby' })
   transaction.sign(privateKey)
   const serializedTx = transaction.serialize().toString('hex')
   return web3.eth.sendSignedTransaction('0x' + serializedTx, function(err, hash) {
     if (!err) {
       console.log('Tx Hash:' + hash);
     }else {
       console.log(err);
     }
   });
 })

sendRawTransaction(txData)

錯誤:

Error: Returned error: transaction could not be decoded: unsigned transactions not supported
at Object.ErrorResponse (/PATH/node_modules/web3-core-helpers/lib/errors.js:28:19)
at /PATH/node_modules/web3-core-requestmanager/lib/index.js:303:36
at XMLHttpRequest.request.onreadystatechange (/PATH/node_modules/web3-providers-http/lib/index.js:98:13)
at XMLHttpRequestEventTarget.dispatchEvent (/PATH/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
at XMLHttpRequest._setReadyState (/PATH/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
at XMLHttpRequest._onHttpResponseEnd (/PATH/node_modules/xhr2-cookies/dist/xml-http-request.js:318:14)
at IncomingMessage.<anonymous> (/PATH/node_modules/xhr2-cookies/dist/xml-http-request.js:289:61)
at IncomingMessage.emit (node:events:381:22)
at endReadableNT (node:internal/streams/readable:1307:12)
at processTicksAndRejections (node:internal/process/task_queues:81:21) {
 data: null
}

我嘗試過的事情:

  • 使數據不為空
  • 在交易中添加’chainId:4'
  • 仔細檢查我的私鑰是否正確。

謝謝。

您的程式碼有兩個問題:

  1. 替換const Tx = require('@ethereumjs/tx').Transactionconst Tx = require('ethereumjs-tx').Transaction(如您提供的連結中所示)。

您目前使用的2.x版本ethereumjs-tx不應與3.x(重命名為@ethereumjs/tx)混淆,因為存在重大更改。

  1. 你的gas限制太高了( 2500000000)

區塊氣體限制僅限10000000於 Rinkeby 網路,gasLimit因此您的交易不得超過此數量。對於兩個 EOA 之間的簡單傳輸(沒有其他數據),您可以將其設置21000為 gas 限制。

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