【问题标题】:i am trying to send a transaction but it throws an error我正在尝试发送交易,但它会引发错误
【发布时间】:2022-08-02 22:30:37
【问题描述】:

终端错误

 if (!cond) throw new Error(msg)
             ^

Error: Expected private key to be an Uint8Array with length 32

我的代码

它关于签名错误。 我完全不知道为什么这不起作用,因为我直接从指南中复制了每段代码,现在它不起作用。

const Web3 = require(\'web3\')
const Tx = require(\'ethereumjs-tx\').Transaction
const web3 = new Web3(\'http://127.0.0.1:8545\')

const account1 = \'0x97F70e1a18B6237603e9382920C93853992ab174\'
const account2 = \'0xA838152E5C21f8d3Df51f696431AEb1D3C2Ff2F7\'

const privateKey1 = Buffer.from(process.env.PRIVATE_KEY_1,\'hex\')
const privateKey2 = Buffer.from(process.env.PRIVATE_KEY_2,\'hex\')

const contractAddress = \'0xd9145CCE52D386f254917e481eB44e9943F39138\'
const contractABI = //had to remove to be a shorten code
var contract = new web3.eth.Contract(contractABI, contractAddress);
const data = contract.methods.transfer(account2,20000).encodeABI();


web3.eth.getTransactionCount(account1, (err, txCount) => {

//create the transaction object
const txObject = {
    nonce: web3.utils.toHex(txCount), 
    gasLimit:web3.utils.toHex(210000) ,
    gasPrice: web3.utils.toHex(web3.utils.toWei(\'10\', \'gwei\')),
    to: contractAddress,  
    data: data
}
 
//sign the transaction
const tx = new Tx(txObject)
tx.sign(privateKey1)

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

//broadcast the transaction
web3.eth.sendSignedTransaction(raw, (err , txHash) =>{
    console.log(\'err:\', err , \'txHash:\', txHash);
    //use this txHash to find contract on Etherscan!
})
})

而已

    标签: node.js ethereum web3js etherscan


    【解决方案1】:

    您是否确保设置了示例代码中引用的 PRIVATE_KEY_1 和 PRIVATE_KEY_2 变量?在我看来,这似乎是最明显的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2021-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多