【问题标题】:Web3js signTransationWeb3js 签名交易
【发布时间】:2021-12-25 18:29:00
【问题描述】:

我正在关注文档以便能够在 Kovan 测试网上签署和发送交易。当我控制 txHash 时,我目前得到一个未定义的值。

web3.eth.getTransactionCount(account1, (err, txCount) => {
    // 1)Build Transaction
    const txObject = {
        nonce: web3.utils.toHex(txCount),
        to: account2,
        value: web3.utils.toHex(web3.utils.toWei('0.05', 'ether')),
        gasLimit: web3.utils.toHex(2100),
        gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
    }
    
     // 2)Sign Transaction
    const tx = new Tx(txObject,{'chain':42})
    tx.sign(privateKey1)
    
    const serializedTransaction = tx.serialize()
    const raw = '0x' + serializedTransaction.toString('hex')

    console.log("raw:", raw)
    console.log("tx:", serializedTransaction)

    // 3)Broadcast Transaction
    web3.eth.sendSignedTransaction(raw, (err, txHash) =>{
        console.log('txHash:', txHash)
    })
    // COMMENTED-OUT web3.eth.sendSignedTransaction('0x' + serializedTransaction .toString('hex'))
    // .on('receipt', console.log);
})

【问题讨论】:

    标签: javascript ethereum web3 web3js


    【解决方案1】:

    signTransaction() 只执行签名。它不会将(签名的)交易广播到网络。

    为此,您可以使用sendSignedTransaction() (docs),它将(签名和序列化的)tx 数据提交给提供者,提供者将其广播到网络。

    web3.eth.sendSignedTransaction(signedTx.rawTransaction)
    .on('receipt', console.log);
    

    【讨论】:

    • 我更新了我的代码,但现在有未定义的任何想法?
    • @PythonCoder1981 你在哪一部分得到undefinedsendSignedTransaction 回调中的 err 是否返回任何非空值?
    • 在 console.log 的 sendSignTransaction 的输出中显示 txHash: undefined
    • @PythonCoder1981 然后它可能在err 变量中返回一个值,它没有设置txHash。 (在 JS 中,undefined 值用于尚未设置值的变量。)您可以检查err 值吗?
    • 谢谢,我在 console.log 后发现了“err”,gas 限制设置不正确,我将它设置为 2100 并将其更改为 21000 并且它起作用了。
    猜你喜欢
    • 2018-09-12
    • 2021-11-23
    • 2022-08-13
    • 1970-01-01
    • 2023-04-10
    • 2022-06-18
    • 2022-01-04
    • 2018-07-28
    • 1970-01-01
    相关资源
    最近更新 更多