Created
December 4, 2019 09:59
-
-
Save dmdeklerk/edd9e8f83b6a82f2b6848399c04532a5 to your computer and use it in GitHub Desktop.
Transfer ERC20 Ethereum token
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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