solana

How do I get the amount of custom token transfered in a transaction with @solana/web3.js?


I want to get the number of custom token that's transfered using trasnsaction signature with @solana/web3.js. How may I do that?

Thank you in advance.


Solution

  • Here the Javascript code to get the amount of transfered tokens using solana web3.js

    var tes;
    var triesGetTrans = 0;
    while (!tes && triesGetTrans < 30) {
        try {
            if (triesGetTrans != 0) await sleep(10000)
            triesGetTrans++
            tes = await connection.getTransaction(updatedAccountInfo.signature, { maxSupportedTransactionVersion: 2 });
        } catch (e) {
            //console.log('Err getTransaction', updatedAccountInfo.signature);
        }
    }
    var consumed = 0;
    if (tes && tes.meta && tes.meta.preTokenBalances && tes.meta.preTokenBalances.length > 0 ) {
        consumed = tes.meta.preTokenBalances[0].uiTokenAmount.uiAmount - tes.meta.postTokenBalances[0].uiTokenAmount.uiAmount;
    }