TransWikia.com

Transferring an ERC-20 using web3js 1.0.0

Ethereum Asked by John Murphy on February 21, 2021

I have been trying to follow the web3js documentation, but it mentions things that are not native to Javascript like “Buffer” so I found a library called ethereumjs-tx to let me use that.

  • My HTML page to test it on has scripts to import web3js-1.0.0 and browser-ethereumjs-tx.js

  • I am using Infura as my web3 provider

Here is my function, with addresses and private keys stripped for safety:

async function transferTokens(){
    // example: https://ethereum.stackexchange.com/questions/24828/how-to-send-erc20-token-using-web3-api

    // the ABI of the erc20
    var abi;

    // the token address for the specific token 
    var tokenAddr;

    // instantiate the token contract using the ABI and the Contract Address.
    var tokenContract = new web3.eth.Contract(abi, tokenAddr);

    // who has the tokens to be sent? 
    var sender;

    // where are the tokens being sent?
    var tokenRecipient = document.getElementById('tokenRecipient').value;

    // how many tokens are being sent?
    var tokenAmount;

    // nonce
    var count = web3.eth.getTransactionCount(sender);

    //set a gas price for the transfer in GWei (I picked 30 arbitrarily).
    var gasPriceGwei = 30;

    var gasLimit = 400000; // arbitrary, I know it's higher than needed

    //Creating a raw Tx...
    var rawTransaction = {
        "from": sender,
        "nonce": "0x" + count.toString(16), 
        "gasPrice": gasPriceGwei,
        "gasLimit": gasLimit,
        "to": tokenRecipient,
        "value": "0x0",
        "data": tokenContract.methods.transfer(tokenRecipient, tokenAmount).encodeABI(), // not sure wtf
        "chainId": 0x04 //rinkeby network
    };

    // EthJS allows us a buffer function.
    var privKey = new EthJS.Buffer.Buffer('[my_privKey]', 'hex');

    var tx = new EthJS.Tx(rawTransaction); 
    tx.sign(privKey);
    var serializedTx = tx.serialize();

    // Comment out these three lines if you don't really want to send the TX right now
    console.log(`Attempting to send signed tx:  ${serializedTx.toString('hex')}`);
    var receipt =  web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'));
    console.log(`Receipt info:  ${JSON.stringify(receipt, null, 't')}`);

}

Nothing happens. The console logs:

    TEST.html:134 Attempting to send signed tx:  [a Tx that is 334 characters long] 
    TEST.html:136 Receipt info:  {}

When I try to include another function (that I know works) inside transferTokens with console logs, they never get logged. So presumably the function is never executed for some reason. My working function is:

tokenContract.methods.balanceOf(sender).call(function(err, bal){
    console.log("LOG X");
    if(!err){
        bal = web3.utils.fromWei(bal, 'ether');
        console.log("sender bal: "+bal);
        document.getElementById('balBeforeSending').innerHTML 
        = "The balance of "+ document.getElementById('tokenTransfer').options[document.getElementById('tokenTransfer').selectedIndex].innerHTML
            + " before sending " + sender + " was: " 
            + bal;  
    }
    else{
        console.log("line 106");
        console.error(err);
    }
});

I have placed it just before the “creating Raw Transaction” line in the original function.

I had await on both the count and the receipt previously but they never got logged so I thought I would remove them. The program was stuck waiting for them but never got anything back so I believe nothing after the await was executed.

One Answer

Web3 1.0 isn't actually released yet, which might be why you're having some issues. See the disclaimer here. Instead, use the API docs here to craft your transactions.

And since you added a question on the line where you were generating data for the transaction, in web3 0.x.x you'd need to do something like this to correctly encode the data:

const data = contractInstance.methodName.getData(param1 [, param2, ...])

Answered by gskapka on February 21, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP