0

您好,我想使用 ankr api 和 web3 提供程序将 bep20 令牌一个地址转移到另一个地址,但出现类似错误

发件人无效

这是我用于传输代币的代码,我已经将chaind id用于binanace,例如bnb,bsc binance smart chain mainnet

let tokenAddress = '0x41XXXXXXXXXXXXXXXXXXXXXXXXXXXXXbce' //  contract address
 
  let toAddress = req.params.toaddress // where to send it
  let fromAddress = req.params.fromaddress // your wallet
  let pKey = req.params.privatekey.split('0x');
  let privateKey = Buffer.from(pKey[1],'hex');
  
  let contractABI = [
    // transfer
    {
      'constant': false,
      'inputs': [
        {
          'name': '_to',
          'type': 'address'
        },
        {
          'name': '_value',
          'type': 'uint256'
        }
      ],
      'name': 'transfer',
      'outputs': [
        {
          'name': '',
          'type': 'bool'
        }
      ],
      'type': 'function'
    }
  ]

  let contract = new web32.eth.Contract(contractABI, tokenAddress, {from: fromAddress})

  // 1e18 === 1 HST
  let amount1 = req.params.amount;

  let amount = web32.utils.toBN(amount1*1000000000000000000)
  // console.log(amount);
  web32.eth.getTransactionCount(fromAddress)
    .then((count) => {
      let rawTransaction = {
        'from': fromAddress,
        'gasPrice': web32.utils.toHex(20 * 1e9),
        'gasLimit': web32.utils.toHex(210000),
        'to': tokenAddress,
        'value': 0x0,
        'data': contract.methods.transfer(toAddress, amount).encodeABI(),
        'nonce': web32.utils.toHex(count),
        "chainId": 56
      }
      let transaction = new EthereumTx(rawTransaction,{chain:'bsc'})
      transaction.sign(privateKey)
      web32.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'),(err,hash) => {
        console.log(err)
        var url = "https://etherscan.io/tx/"+hash
        res.json({hash: hash, status_url: url,success:'true',message : 'Transaction has been pushed.'});
      })
        
    })
4

1 回答 1

1
transaction.sign(privateKey)
web32.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'),(err,hash) => {

您正在传递未签名的交易,需要传递已签名的交易。

const signedTx = transaction.sign(privateKey)
web32.eth.sendSignedTransaction('0x' + signedTx.serialize().toString('hex'),(err,hash) => {

请参阅自述文件 中的示例(查找const signedTx代码段)

于 2021-10-02T09:47:01.897 回答