0

I have a piece of typescript code finding out the number of tokens swapped in a transaction. This goes well, but in (estimated) 3% of the cases I get a strange result. In the provided code, I get as a result:

movedSol -0.010017014
tokenBalanceBefore 24696796.2733421
tokenBalanceAfter 84.022468663
tokenBalanceChanged -24696712.250873435

Where I would expect:

movedSol -0.010017014
tokenBalanceBefore 24696796.2733421
tokenBalanceAfter 24696712.250873435
tokenBalanceChanged -84.022468663

What am I doing wrong?

Solscan transaction from the example

import { Connection, clusterApiUrl, GetVersionedTransactionConfig, LAMPORTS_PER_SOL } from '@solana/web3.js';

main();

async function main() {
  const transactionId = '5Wqke2sa3WRzN7GMpGybs8tCETc3mW3zdai7Qq3zpb8xLSbtKSWzs6qqw4kZKjcBaxN18Pnv1tVB6iDV3ShP1M89';
  const tokenAddress = '3ag1Mj9AKz9FAkCQ6gAEhpLSX8B2pUbPdkb9iBsDLZNB';
  const connection = new Connection(clusterApiUrl('mainnet-beta'), 'confirmed');
  const options: GetVersionedTransactionConfig = {commitment: 'confirmed', maxSupportedTransactionVersion: 0};
  const transactionResponse: any = await connection.getTransaction(transactionId, options);

  const preSolBalance = transactionResponse.meta?.preBalances[0] || 0;
  const postSolBalance = transactionResponse.meta?.postBalances[0] || 0;
  const movedSol = (postSolBalance - preSolBalance) / LAMPORTS_PER_SOL
  const tokenBalanceBefore = transactionResponse.meta?.preTokenBalances?.find(token => token.mint === tokenAddress)?.uiTokenAmount.uiAmount || 0;
  const tokenBalanceAfter = transactionResponse.meta?.postTokenBalances?.find(token => token.mint === tokenAddress)?.uiTokenAmount.uiAmount || 0;
  const tokenBalanceChanged =  tokenBalanceAfter - tokenBalanceBefore;
  console.log('movedSol', movedSol);
  console.log('tokenBalanceBefore', tokenBalanceBefore);
  console.log('tokenBalanceAfter', tokenBalanceAfter);
  console.log('tokenBalanceChanged', tokenBalanceChanged);
}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.