Skip to content

Instantly share code, notes, and snippets.

@rajeshsubhankar
Created March 28, 2019 17:03
Show Gist options
  • Save rajeshsubhankar/d9b1ca007be3d7db0ba5f6fe19d99e8b to your computer and use it in GitHub Desktop.
Save rajeshsubhankar/d9b1ca007be3d7db0ba5f6fe19d99e8b to your computer and use it in GitHub Desktop.

Revisions

  1. rajeshsubhankar created this gist Mar 28, 2019.
    71 changes: 71 additions & 0 deletions sendRawTokenTransaction.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    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);
    });
    });
    });