Skip to content

Instantly share code, notes, and snippets.

@dmdeklerk
Created December 4, 2019 09:59
Show Gist options
  • Save dmdeklerk/edd9e8f83b6a82f2b6848399c04532a5 to your computer and use it in GitHub Desktop.
Save dmdeklerk/edd9e8f83b6a82f2b6848399c04532a5 to your computer and use it in GitHub Desktop.
Transfer ERC20 Ethereum token
const Web3 = require('web3')
const web3 = new Web3();
const erc20TransferAbi = [{
"constant": false,
"inputs": [{
"name": "_to",
"type": "address"
},{
"name": "_value",
"type": "uint256"
}],
"name": "transfer",
"outputs": [{
"name": "",
"type": "bool"
}],
"type": "function"
}];
function getAddress(privateKey, type) {
var data = web3.eth.accounts.privateKeyToAccount(privateKey);
return data ? data.address : null;
}
function transferEth(privateKey, to, value, nonce, gasPrice, gasLimit, chainId) {
var tx = {
to,
nonce,
value,
gasPrice,
gasLimit,
chainId
}
return web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
return signed.rawTransaction;
});
}
function transferErc20(privateKey, contractAddress, to, value, nonce, gasPrice, gasLimit, chainId) {
const from = getAddress(privateKey)
const contract = new web3.eth.Contract(erc20TransferAbi, contractAddress, { from });
const data = contract.methods.transfer(to, value).encodeABI()
const tx = {
from,
to: contractAddress,
nonce,
value: '0x0',
gasPrice,
gasLimit,
chainId,
data,
}
return web3.eth.accounts.signTransaction(tx, privateKey).then(signed => {
return signed.rawTransaction;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment