0

Here is my code,

web3.eth.getTransaction(txns.transactionHash,function (err,res){
  console.log(res.to); // consoles contract address
  var input = res.input,erc20=input.slice(0,10);
  if(erc20 == '0xa9059cbb'){
    var amount= web3.utils.hexToNumberString(input.slice(74,138));
    amount = web3.utils.fromWei(amount);
    var to_address = web3.utils.hexToString(input.slice(10,74)); // Cannot get/decode to_address
    console.log(amount,to_address);
  }
})

Also, res.to consoles contract address instead of exact to_address. So that I'm trying to get it from input hash.

1

The field to reffers to the recipient of the transaction (the contract). Token transfer is an "internal transaction" to get the values you need to look into the data (or input) fields.

For instance, using hash = 0x080f0be5e0808320ac80a60646cb43ea1573731f818477710bfbbd377ff81be7 web3.eth.getTransaction(txns.transactionHash,function (err,res){console.log(res.input)})

will give you: "0xa9059cbb0000000000000000000000004f2161c7eb1dc40d6f0eb24db81bf4a6eb0c3f300000000000000000000000000000000000000000000000056bc75e2d63100000"



Here:

a9059cbb (first 4 bytes) gives you the signature of the method transfer

The next 32 bytes are for the address (to) - remove the first 12 bytes (24 zeros) 0000000000000000000000004f2161c7eb1dc40d6f0eb24db81bf4a6eb0c3f30

The remaining 32 bytes are the value of the transaction (in Hex) 0000000000000000000000000000000000000000000000056bc75e2d63100000

This is because the transfer method is transfer(address to, uint256 value)



In general,for ERC20 transfers you can do:

method = input.slice(2,10) = "a9059cbb"

to = input.slice(34,72) = "4f2161c7eb1dc40d6f0eb24db81bf4a6eb0c3f"

value = input.slice(73,138) = "00000000000000000000000000000000000000000000000056bc75e2d63100000"

Hope this helps

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.