【问题标题】:Web3 - Sending a transaction results in "invalid sender"Web3 - 发送交易导致“无效发件人”
【发布时间】:2019-10-25 12:08:26
【问题描述】:

我正在尝试通过 Infura 节点使用 web3 调用我的智能合约 (Ropsten) 上的函数。我在 Metmask 中创建了一个测试账户,并导出了账户地址和私钥。细节看起来正确,但是我收到错误{"code":-32000,"message":"invalid sender"}。我猜这是交易签名的问题?

这是我的代码

const Web3 = require('web3');
const Tx = require('ethereumjs-tx').Transaction;
const fs = require('fs');

const pk = Buffer.from('PRIVATE KEY FROM METAMASK', 'hex')
const sourceAccount = 'ACCOUNT ADDRESS FROM METAMASK'
const web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/API_KEY"));
const consumerAddress = '0xc36577aa0171f649be6bd7205148ed83c07198ee';
web3.eth.defaultAccount = sourceAccount;


//Get Consumer contract instance
const consumerAbi = JSON.parse(fs.readFileSync('rental-contract-abi.json', 'utf8'));
let consumerContract = new web3.eth.Contract(consumerAbi, consumerAddress);
const myData = consumerContract.methods.checkDate("e716efba3b404da98e28faaa2939c0fd","2019-06-04","AU-NSW").encodeABI();
web3.eth.getTransactionCount(sourceAccount, (err, txCount) => {
    // Build the transaction
    const txObject = {
        nonce:    web3.utils.toHex(txCount),
        to:       consumerAddress,
        from: sourceAccount,
        chainId: 3,
        value:    web3.utils.toHex(web3.utils.toWei('0', 'ether')),
        gasLimit: web3.utils.toHex(2100000),
        gasPrice: web3.utils.toHex(web3.utils.toWei('6', 'gwei')),
        data: myData  
    }

    // Sign the transaction
    const tx = new Tx(txObject);
    tx.sign(pk);

    const feeCost = tx.getUpfrontCost()
    console.log('Total Amount of ETH needed:' + web3.utils.fromWei(feeCost.toString(), 'ether'))

    console.log('---Serialized TX----')
    console.log(tx.serialize().toString('hex'))
    console.log('--------------------')

    const serializedTx = tx.serialize();
    const raw = '0x' + serializedTx.toString('hex');
    
    // Broadcast the transaction
    const transaction = web3.eth.sendSignedTransaction(raw, (err, tx) => {
        console.log(tx);
        console.log(err);
    });
});

【问题讨论】:

    标签: node.js ethereum web3 metamask


    【解决方案1】:

    您需要在签署交易时添加网络信息。请参阅最新的 web3 文档。将签名交易代码更改为:

    const tx = new Tx(txObject,{'chain':'ropsten'});
    

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 2023-01-13
      • 2019-12-05
      • 2022-01-04
      • 2021-11-21
      • 2016-06-06
      • 2018-11-04
      • 2023-02-12
      • 2013-08-27
      相关资源
      最近更新 更多