Skip to content

Instantly share code, notes, and snippets.

@x3388638
Created March 28, 2018 16:32
Show Gist options
  • Save x3388638/f7c4de25a2c438d3b52afd2ce3be4959 to your computer and use it in GitHub Desktop.
Save x3388638/f7c4de25a2c438d3b52afd2ce3be4959 to your computer and use it in GitHub Desktop.
Send ethereum ERC20 token via web3.js (ether, ETH, contract)
const Tx = require('ethereumjs-tx');
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io/'));
const contractAddr = 'CONTRACT_ADDRESS';
const contractAbi = [/* CONTRACT_ABI_ARRAY */];
const contractOwner = {
addr: 'CONTRACT_OWNER_ADDRESS',
key: 'CONTRACT_OWNER_PRIVATE_KEY'
};
sendToken('RECEIVER_ADDRESS', 'AMOUNT_OF_TOKEN');
function sendToken(receiver, amount) {
console.log(`Start to send ${amount} tokens to ${receiver}`);
const contract = web3.eth.contract(contractAbi).at(contractAddr);
const data = contract.transfer.getData(receiver, amount * 1e18);
const gasPrice = web3.eth.gasPrice;
const gasLimit = 90000;
const rawTransaction = {
'from': contractOwner.addr,
'nonce': web3.toHex(web3.eth.getTransactionCount(contractOwner.addr)),
'gasPrice': web3.toHex(gasPrice),
'gasLimit': web3.toHex(gasLimit),
'to': contractAddr,
'value': 0,
'data': data,
'chainId': 1
};
const privKey = new Buffer(contractOwner.key, 'hex');
const tx = new Tx(rawTransaction);
tx.sign(privKey);
const serializedTx = tx.serialize();
web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function (err, hash) {
if (err) {
console.log(err);
}
console.log(hash);
});
}
@iegestesi
Copy link

Can you write this code for send function in erc 777 tokens? Unfortunately, there is no data transmission in Erc 20 tokens or I could not, but I could not, but data is sent in erc 777 tokens. It would be nice if you couldn't find sample code in this topic.

@x3388638
Copy link
Author

@iegestesi
Sorry that it's so long time ago I wrote this code, and I haven't developed blockchain related for more than 2 years.
Maybe you can find the solution in latest ethereumjs-tx and web3.js docs

@vilgacx
Copy link

vilgacx commented Aug 26, 2021

can you let me know what was Web3.js version?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment