Created
March 28, 2019 17:03
-
-
Save rajeshsubhankar/d9b1ca007be3d7db0ba5f6fe19d99e8b to your computer and use it in GitHub Desktop.
Create and sends a raw ERC-20 token transaction with ether.js 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 ethers = require('ethers'); | |
const BigNumber = require('bignumber.js'); | |
const provider = new ethers.providers.JsonRpcProvider('https://ropsten.infura.io/v2/INFURA_PROJECT_ID'); | |
const addressFrom = 'SENDER_ADDRESS'; | |
const privateKey = 'SENDER_PRIVATE_KEY'; | |
const wallet = new ethers.Wallet(privateKey, provider); | |
const addressTo = 'RECEIVER_ADDRESS'; | |
// token details | |
const tokenAddress = 'TOKEN_ADDRESS'; | |
const amount = 0.5; | |
const tokenDecimal = 18; // token decimal | |
/** Create token transfer value as (10 ** token_decimal) * user_supplied_value | |
* @dev BigNumber instead of BN to handle decimal user_supplied_value | |
*/ | |
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 | |
*/ | |
var abi = [{ | |
"constant": false, | |
"inputs": [{ | |
"name": "_to", | |
"type": "address" | |
}, { | |
"name": "_value", | |
"type": "uint256" | |
}], | |
"name": "transfer", | |
"outputs": [{ | |
"name": "", | |
"type": "bool" | |
}], | |
"payable": false, | |
"stateMutability": "nonpayable", | |
"type": "function" | |
}]; | |
const iface = new ethers.utils.Interface(abi); | |
const rawData = iface.functions.transfer.encode([addressTo, valueToTransfer.toString()]); | |
provider.getTransactionCount(addressFrom) | |
.then((txCount) => { | |
// construct the transaction data | |
const txData = { | |
nonce: txCount, | |
gasLimit: 250000, | |
gasPrice: 10e9, // 10 Gwei | |
to: tokenAddress, // token contract address | |
value: ethers.constants.HexZero, // no ether value | |
data: rawData, | |
} | |
const serializedTx = ethers.utils.serializeTransaction(txData); | |
//console.log('serialized Tx: ', serializedTx); | |
//console.log('parsed serialized tx: ', ethers.utils.parseTransaction(serializedTx)); | |
// parse unsigned serialized transaction and sign it | |
wallet.sign(ethers.utils.parseTransaction(serializedTx)) | |
.then((signedSerializedTx) => { | |
//console.log('signed serialized tx: ', signedSerializedTx); | |
// broadcast signed serialized tx | |
provider.sendTransaction(signedSerializedTx) | |
.then((response) => { | |
console.log('tx response: ', response); | |
}); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment