0

I'm currently writing a function using Web3 to send our tokens, it's currently sending ETH instead. Since we're doing this straight on the main network (We like taking risks), the transaction fees are adding up.

If anyone can help us see how to send our token rather than ETH it would be really appreciated.

    const web3 = new Web3();
web3.setProvider(new 
web3.providers.HttpProvider("https://mainnet.infura.io/XXXXXX"));
var count = web3.eth.getTransactionCount(from_addr);
var contract =  web3.eth.contract(abi).at(contract_addr);

var data = contract.transfer.getData(to_addr, 10, {from: from_addr});
var gasPrice = web3.eth.gasPrice;
var gasLimit = 90000;

var rawTransaction = {
  "from": from_addr,
  "nonce": web3.toHex(count),
  "gasPrice": web3.toHex(gasPrice),
  "gasLimit": web3.toHex(gasLimit),
  "to": to_addr,
  "value": 0,
  "data": data,
  "chainId": 0x01
};

var privKey = new Buffer(priv_key, 'hex');
var tx = new Tx(rawTransaction);

tx.sign(privKey);
var serializedTx = tx.serialize();

web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
  if (!err)
      console.log(hash);
  else
      console.log(err);
});

I've pretty much copied and pasted this question: How to send ERC20 token using Web3 API?. They seemed to have found the way to send tokens whereas I'm still sending ETH.

Any advice would be much appreciated.

Thanks

1

This line is wrong:

"to": to_addr,

It should be:

"to": contract_addr,

You're calling a function in a smart contract, so the smart contract is the recipient of that transaction. (It will then update its internal ledger to account for the transfer of the token.)

  • Ah of course! Thank you! I couldn't see the issue! Additionally, in the getData(to, value, from). If the token has 18 decimals, would 10 be 10 (and then 18 0's) or it's just 10? – SwimmingG Jan 16 '18 at 23:14
  • Yes, with 18 decimals, 10 "tokens" is a 10 followed by 18 zeros. – user19510 Jan 16 '18 at 23:18
  • @smarx I am getting an error when i run this code to transfer tokens on main network , I am not running testrpc because its used for test network what am i doing wrong PLEASE HELP below is the error i am getting ======> (node:1044) UnhandledPromiseRejectionWarning: Error: Invalid JSON RPC response: "" at Object.InvalidResponse ..... – veeresh kumbar Apr 14 '18 at 5:41
  • Comments are not for asking new questions. – user19510 Apr 14 '18 at 16:36

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.