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.
web3js, nodejs, erc-20
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)
Web3js.eth.getTransactionCount(fromAddress)
.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)
transaction.sign(privateKey)
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
```
edited
Still looking for solution though
I can see you creating a transaction after getting the transaction count, but try to do something simpler first.
contract_data.transfer(receiver,amount{from:web3.eth.accounts[0]});
web3js, tokens, erc-20
contract.methods.transfer
Try to get a basic transfer working, then you can try to add in the sendSignedTransaction.
11125
July 14, 2021, 10:19am
7
Update new Tx with
let transaction = new Tx(rawTransaction, {chain: chainId})
You can find the chain id here https://chainlist.org/