Search code examples
javascriptweb3jsbep20

How to get tokens transferred in transaction details using web3 js?


I am using web3js to get transaction details

my code:

const transactionHash = this._req.query.transactionHash;

const transaction = await this._web3.eth.getTransactionReceipt(transactionHash);

const logs = await transaction.logs;

const log = await logs.find(i => i.transactionHash === transactionHash);

const topics = await log.topics;

const test = await this._web3.eth.abi.decodeParameter('bytes32', topics[0]);

const from = await this._web3.eth.abi.decodeParameter('address', topics[1]);

const to = await this._web3.eth.abi.decodeParameter('address', topics[2]);

const value = await this._web3.eth.abi.decodeParameter('uint256', log.data);

const amount = await this._web3.utils.fromWei(value);

But I still haven't got the token name of the transaction

enter image description here

Give me some suggestions, thanks


Solution

  • To get the token symbol, you need to call the token contract's function symbol().

    Since the Transfer event was emitted by the token contract, you have its address in the log.address property. Then you just need to call the symbol() function:

    const abiJson = [
        {"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"}
    ];
    
    const contract = new web3.eth.Contract(abiJson, log.address);
    const symbol = await contract.methods.symbol().call();