Web3.js ERC20 Token Transfer – How to Send ERC20 Tokens through Web3 on Node.js

blockchainerc-20nodejstransferweb3js

My transactions go through without errors, while they're pending the data field shows the amount of tokens I'm sending, but when the transaction goes through the data field is empty. Here is my code:

const abi = My_Contract.abi
const web3 = new Web3('https://rinkeby.infura.io/v3/INFURA_PROJECT_ID')
const gasprice= await web3.eth.getGasPrice()
var count = await web3.eth.getTransactionCount(myAccount)
const token = new web3.eth.Contract(abi, My_Contract.networks[4].address)

var amountInDecimal = 166
const txObject = {
  from: myAccount,
  nonce: "0x" + count.toString(16),
  to: '0x153ed6D60AcaE6E915907233F10663462FF67622',
  gas: 100000,
  value:"0x0",
  data:token.methods.transfer('0x153ed6D60AcaE6E915907233F10663462FF67622', 
  web3.utils.toHex(web3.utils.toWei(amountInDecimal.toString(), "ether"))).encodeABI(),
  gasPrice:gasprice
}
console.log(txObject)
web3.eth.accounts.signTransaction(txObject, privateKey, (err, res) => {
  if (err) {
    console.log('err',err)
  }
  else {
    console.log('res', res)
  }
  const raw = res.rawTransaction
  web3.eth.sendSignedTransaction(raw, (err, txHash) => {
    if (err) {
      console.log(err)
    }
    else {
      console.log("txHash:", txHash)
    }
  })
})

When I call the transfer function through truffle console it works perfectly. Please help, I am dying

Best Answer

The problem is that you are sending the transfer message to the token recipient address. To execute a function from a contract the transaction has to target the contract address.

const token = new web3.eth.Contract(abi, My_Contract.networks[4].address)

const txObject = {
  ..
  to: '0x153ed6D60AcaE6E915907233F10663462FF67622',        // <--- Recipient
  ..
}

It should have been to the token contract instead

const token = new web3.eth.Contract(abi, My_Contract.networks[4].address)

const txObject = {
  ..
  to: My_Contract.networks[4].address,                     // <--- Token
  ..
}
Related Topic