Web3js send Token instead of ETH

Basically i have this piece of code that works for sending ETH through web3js. Now my questions is, if i wanted to sent not ETH, but an ERC20 token, what changes to the code do i need to make? Could someone point me in the right direction/fix my code? What changes need to be made in order to send ERC20 instead of ETH itself? Thanks in advance!

var trxData = {
from: addressFrom, // My address
to: addressTo,
value: web3.utils.toHex(“1000000000000000000”),
gasLimit: web3.utils.toHex(21000),
gasPrice: web3.utils.toHex(1 * 1e9), // 41 Gwei

Hello, you need to use the transfer function for the ERC20 contract.

Something like:

contractInstance.method.transfer(addressToSendTo, amountToTransfer).send(from:address)

i checked but it’s not working… I am getting “UnhandledPromiseRejectionWarning: Error: Returned error: invalid sender” for some reason

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

const Web3js = new Web3(new Web3.providers.HttpProvider('https://polygon-mainnet.infura.io/v3/key%27))

let tokenAddress = '0x' // HST contract address
let toAddress = '0x' // where to send it
let fromAddress = '0x' // your wallet
let privateKey = Buffer.from('key', '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 Web3js.eth.Contract(contractABI, tokenAddress, {from: fromAddress})

// 1e18 === 1 HST
let amount = Web3js.utils.toHex(1e18)

  .then((count) => {
    let rawTransaction = {
      'from': fromAddress,
      'gasPrice': Web3js.utils.toHex(20 * 1e9),
      'gasLimit': Web3js.utils.toHex(210000),
      'to': tokenAddress,
      'value': 0x0,
      'data': contract.methods.transfer(toAddress, amount).encodeABI(),
      'nonce': Web3js.utils.toHex(count)
    let transaction = new Tx(rawTransaction)
    Web3js.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex'))
      .on('transactionHash', console.log)

Please use triple backticks to surround your code in order to get proper formatting.

code here


Still looking for solution though

I can see you creating a transaction after getting the transaction count, but try to do something simpler first.



Try to get a basic transfer working, then you can try to add in the sendSignedTransaction.

Update new Tx with
let transaction = new Tx(rawTransaction, {chain: chainId})
You can find the chain id here https://chainlist.org/