Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Blockchain by (4.1k points)

I created a contract token using the sample solidity code tutorial. It has a function called transfer to send tokens between accounts:

function transfer(address _to, uint256 _value)

I need to now connect to this contract using web3, and then send a certain number of tokens generated to another account. I've been struggling with how to do this for quite some time and hoping this community could help. Here is what I have thus far, using web3 version 0.20.0:

const Web3 = require("web3");
const web3 = new Web3();
web3.setProvider(new
web3.providers.HttpProvider("https://ropsten.infura.io/XXXXXX"));
var abi = [ {} ] // redacted on purpose
var count = web3.eth.getTransactionCount("0x9...");
var abiArray = abi;
var contractAddress = "0x2...";
var contract =  web3.eth.contract(abiArray).at(contractAddress);

var data = contract.transfer.getData("0x2...", 10000, {from: "0x9..."});
var gasPrice = web3.eth.gasPrice;
var gasLimit = 90000;

var rawTransaction = {
  "from": "0x9...",
  "nonce": web3.toHex(count),
  "gasPrice": web3.toHex(gasPrice),
  "gasLimit": web3.toHex(gasLimit),
  "to": "0x2...",
  "value": "0x1",
  "data": data,
  "chainId": 0x03
};

var privKey = new Buffer('XXXXXXXXXXXXXX', '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);
});

This transaction works but it's sending ether as opposed to the actual ERC20 token. I'm really at a loss for why this is the case and would appreciate any help

1 Answer

0 votes
by (14.4k points)

The reason you are sending ethers in place of the token is that in the raw transaction field of value you are inputting "0x1". To send the ERC20 token you should leave it at "0x0".

This way your issue will be resolved. 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...