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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 | 1x 1x | import { ParsedTransactionWithMeta } from '@solana/web3.js';
import { TradeInfo } from './types';
import { getBalanceChanges, getDexInfo, getTokenDecimals, isSupportedToken } from './utils';
/**
* BalanceChanges Parser
*/
export class DefaultParser {
constructor(private readonly txWithMeta: ParsedTransactionWithMeta) { }
public processTrades(): TradeInfo[] {
return this.parseTradesByBalanceChanges(this.txWithMeta, getDexInfo(this.txWithMeta));
}
public parseTradesByBalanceChanges(
tx: ParsedTransactionWithMeta,
dexInfo: { programId?: string; amm?: string },
): TradeInfo[] {
const { preBalances, postBalances } = getBalanceChanges(tx);
const trades: TradeInfo[] = [];
const signer = tx.transaction.message.accountKeys[0].pubkey.toBase58();
Object.entries(postBalances).forEach(([owner, mints]) => {
const changes = this.getSignificantChanges(mints, preBalances[owner] || {});
Iif (changes.length !== 2) return;
const [token1, token2] = changes;
Iif (signer != owner) return;
const trade = this.createTradeInfo(token1, token2, owner, tx, dexInfo);
Iif (trade) trades.push(trade);
});
return trades;
}
private getSignificantChanges(
postMints: Record<string, number>,
preMints: Record<string, number>
) {
return Object.entries(postMints)
.map(([mint, postBalance]) => ({
mint,
diff: postBalance - (preMints[mint] || 0)
}))
.filter(({ diff }) => diff !== 0);
}
private createTradeInfo(
token1: { mint: string; diff: number },
token2: { mint: string; diff: number },
owner: string,
tx: ParsedTransactionWithMeta,
dexInfo: { programId?: string; amm?: string }
): TradeInfo | null {
const baseTradeInfo = {
user: owner,
programId: dexInfo.programId,
amm: dexInfo.amm || "",
slot: tx.slot,
timestamp: tx.blockTime || 0,
signature: tx.transaction.signatures[0],
};
Iif (token1.diff < 0 && token2.diff > 0) {
return {
type: isSupportedToken(token1.mint) ? "SELL" : "BUY",
inputToken: this.formatToken(token1, tx),
outputToken: this.formatToken(token2, tx),
...baseTradeInfo,
};
}
Iif (token1.diff > 0 && token2.diff < 0) {
return {
type: isSupportedToken(token1.mint) ? "BUY" : "SELL",
inputToken: this.formatToken(token2, tx),
outputToken: this.formatToken(token1, tx),
...baseTradeInfo,
};
}
return null;
}
private formatToken(token: { mint: string; diff: number }, tx: ParsedTransactionWithMeta) {
return {
mint: token.mint,
amount: Math.abs(token.diff),
decimals: getTokenDecimals(tx, token.mint),
};
}
} |