Skip to content

Instantly share code, notes, and snippets.

@Strernd
Created June 7, 2021 11:09
Show Gist options
  • Save Strernd/4458ee077e96b97443aecfb08b0c4a0a to your computer and use it in GitHub Desktop.
Save Strernd/4458ee077e96b97443aecfb08b0c4a0a to your computer and use it in GitHub Desktop.
Parses an ERC20 Transfer from the Ethereum API.
const converter = require("hex2dec");
const Eth = require("ethjs");
const eth = new Eth(new Eth.HttpProvider(process.env.INFURA));
async function getERC20TransferByHash(hash) {
const ethTxData = await eth.getTransactionByHash(hash);
if (ethTxData === null) throw "TX NOT FOUND";
if (
ethTxData.input.length !== 138 ||
ethTxData.input.slice(2, 10) !== "a9059cbb"
) {
throw "NO ERC20 TRANSFER";
}
const receiver = `0x${ethTxData.input.slice(34, 74)}`;
const amount = converter.hexToDec(ethTxData.input.slice(74));
const symbol = ethTxData.to;
const sender = ethTxData.from;
return { receiver, amount, symbol, hash, sender };
}
getERC20TransferByHash(
"0xd1a2033b3a81d130241e097468554d7d626947c146c8ecd9a4c1b36fc6e45e54"
).then(console.log);
/*
{
receiver: '0x7dcda8fd073a1dab84976d7876634efbc61f5f15',
amount: '500000000000000000000',
symbol: '0x8eef5a82e6aa222a60f009ac18c24ee12dbf4b41',
hash: '0xd1a2033b3a81d130241e097468554d7d626947c146c8ecd9a4c1b36fc6e45e54',
sender: '0x3aba231a90befc61224bac50529f9e5f5058606e'
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment