All files / src/parsers transfer-parser.ts

12.5% Statements 2/16
0% Branches 0/17
0% Functions 0/1
13.33% Lines 2/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44    1x   1x                                                                              
import { ParsedTransactionWithMeta } from '@solana/web3.js';
import { TransferInfo } from '../types';
import { getBalanceChanges, getTokenDecimals } from '../utils';
 
export class TransferParser {
  public parseTransfers(tx: ParsedTransactionWithMeta): TransferInfo[] {
    const transfers: TransferInfo[] = [];
    const { preBalances, postBalances } = getBalanceChanges(tx);
 
    // Compare pre and post balances to detect transfers
    for (const [owner, mints] of Object.entries(postBalances)) {
      for (const [mint, postBalance] of Object.entries(mints)) {
        const preBalance = preBalances[owner]?.[mint] || 0;
        const difference = postBalance - preBalance;
 
        Iif (difference !== 0) {
          // Find the counterparty by looking for opposite balance change
          for (const [otherOwner, otherMints] of Object.entries(postBalances)) {
            Iif (otherOwner === owner) continue;
            const otherDiff = (otherMints[mint] || 0) - (preBalances[otherOwner]?.[mint] || 0);
 
            Iif (otherDiff === -difference) {
              transfers.push({
                type: difference > 0 ? 'TRANSFER_IN' : 'TRANSFER_OUT',
                token: {
                  mint,
                  amount: Math.abs(difference),
                  decimals: getTokenDecimals(tx, mint),
                },
                from: difference > 0 ? otherOwner : owner,
                to: difference > 0 ? owner : otherOwner,
                timestamp: tx.blockTime || 0,
                signature: tx.transaction.signatures[0],
              });
            }
          }
        }
      }
    }
 
    return transfers;
  }
}