Created
March 27, 2019 11:18
-
-
Save rajeshsubhankar/7e8472320ce347b67991b2ccb85d0bf1 to your computer and use it in GitHub Desktop.
Create and sends a raw ERC-20 token transaction with web3 v1.0 and Infura
This file contains hidden or 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 Tx = require('ethereumjs-tx'); | |
const BigNumber = require('bignumber.js'); | |
const abi = require('ethereumjs-abi'); | |
// connect to Infura node | |
const web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/v2/INFURA_PROJECT_ID')); | |
// the address that will send the test transaction | |
const addressFrom = 'SENDER_ADDRESS'; | |
const privKey = 'SENDER_PRIVATE_KEY'; | |
// the destination address | |
const addressTo = 'RECEIVER_ADDRESS'; | |
// token details | |
const tokenAddress = 'TOKEN_CONTRACT_ADDRESS'; | |
const amount = 0.5; | |
const tokenDecimal = 18; // default value | |
/** Create token transfer value as (10 ** token_decimal) * user_supplied_value | |
* @dev BigNumber instead of BN to handle decimal user_supplied_value | |
* @note web3.utils.toBigNumber is no more supported in [email protected] | |
*/ | |
const base = new BigNumber(10); | |
const valueToTransfer = base.pow(tokenDecimal) | |
.times(amount); | |
/* Create token transfer ABI encoded data | |
* `transfer()` method signature at https://eips.ethereum.org/EIPS/eip-20 | |
* ABI encoding ruleset at https://solidity.readthedocs.io/en/develop/abi-spec.html | |
* Convert BigNumber to BN instance as ethereumjs-abi doesn't support BigNumber | |
*/ | |
const rawData = abi.methodID('transfer', ['address', 'uint256']).toString('hex') + | |
abi.rawEncode(['address', 'uint256'], [addressTo, web3.utils.toBN(valueToTransfer)]).toString('hex'); | |
// get the number of transactions sent so far so we can create a fresh nonce | |
web3.eth.getTransactionCount(addressFrom) | |
.then((txCount, err) => { | |
// construct the transaction data | |
const txData = { | |
nonce: web3.utils.toHex(txCount), | |
gasLimit: web3.utils.toHex(250000), | |
gasPrice: web3.utils.toHex(10e9), // 10 Gwei | |
to: tokenAddress, | |
from: addressFrom, | |
value: '0x00', | |
data: `0x${rawData}`, | |
}; | |
const privateKey = Buffer.from(privKey, 'hex'); | |
const transaction = new Tx(txData); | |
transaction.sign(privateKey); | |
const serializedTx = transaction.serialize().toString('hex'); | |
web3.eth.sendSignedTransaction('0x' + serializedTx).on('receipt', console.log); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment