1

I've been trying to follow the documentation, but then that mentions things that are not native to Javascript like "Buffer" so I find a thing called ethereumjs-tx to let me use that.

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

  • I am using Infura as my web3 provider

  • My function looks like this (I have removed the actual addresses and keys 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;
    
            //(COUNT is used for the 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; //also arbitrary, but 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 the transferTokens function with console logs, they never get logged (so presumably the function is never executed for some reason. It is

    tokenContract.methods.balanceOf(sender).call(function(err, bal){ //line93
                        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);
                        }
                    });
    

placed just before the "creating Raw Transaction" line in the original function.

Basically I have no clue. I have been struggling with this for 3 days and I am starting to feel the pressure. I really appreciate any help.

I realise I might be totally wrong and have to start over with a new approach but I cannot for the life of me figure out how to send a token with web3js.

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

  • 2
    If you're connected to an actual public network, I think your gas price is way too low to get a transaction mined. You're passing 30 wei when it should be something like 1 or 2 gwei (2000000000 wei). And yes, you should have receipt = await .... – smarx Jul 26 '18 at 23:07
  • @smarx Thank you. I fixed that and actually got it to work based on a previous answer from here using their EthJS to allow me to use a buffer and a TX. I know from your site and on here that you are very knowledgeable and helpful so I wonder if you think of any better way I should be able to get Buffer and Tx to work in my browser script. I tell all my colleagues I am learning off stackexchange and programtheblockchain.com. :) – John Murphy Jul 27 '18 at 8:06
0

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, ...])

  • There is some functionality that our application will need that is only available in v 1.0 (such as creating wallets), so I think I need to be using v1.0 going forward. And for the sake of being up to date, is it not a good idea to be going for 1.0 asap? Thanks so much for responding. – John Murphy Jul 26 '18 at 10:11
  • That depends I guess on whether you need something working now or not, and whether you're happy to be at the mercy of web3 1.0's timeline. Can you shoot for an MVP using Web3 0.x, and develop along side it the 1.0.0 functionality to be ready for its release? – gskapka Jul 26 '18 at 13:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.