All files parser-pumpfun.ts

93.33% Statements 56/60
50% Branches 10/20
100% Functions 22/22
94.73% Lines 54/57

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 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 1631x 1x 1x 1x 1x                                               1x   1x     2x 2x 2x 2x       1x 1x 1x 1x       4x 4x 4x 4x       1x 1x 1x 1x       8x           1x 1x     1x   6x 2x   6x         2x 2x       2x 2x   2x 6x 2x 19x 1x 1x         2x   1x       1x 1x   1x                                           19x 19x 3x   16x         1x 1x 1x               1x   1x                      
import { PublicKey, ParsedTransactionWithMeta, PartiallyDecodedInstruction } from '@solana/web3.js';
import { Buffer } from 'buffer';
import base58 from 'bs58';
import { DEX_PROGRAMS, DISCRIMINATORS, TOKENS } from './constants';
import { convertToUiAmount, TradeInfo, TradeType } from './types';
 
interface PumpfunTradeEvent {
  mint: PublicKey;
  solAmount: bigint;
  tokenAmount: bigint;
  isBuy: boolean;
  user: PublicKey;
  timestamp: bigint;
  virtualSolReserves: bigint;
  virtualTokenReserves: bigint;
}
 
interface PumpfunCreateEvent {
  name: string;
  symbol: string;
  uri: string;
  mint: PublicKey;
  bondingCurve: PublicKey;
  user: PublicKey;
}
 
// Binary reader implementation with better error handling
class BinaryReader {
  private offset = 0;
 
  constructor(private buffer: Buffer) { }
 
  readFixedArray(length: number): Buffer {
    this.checkBounds(length);
    const array = this.buffer.slice(this.offset, this.offset + length);
    this.offset += length;
    return array;
  }
 
  readU8(): number {
    this.checkBounds(1);
    const value = this.buffer.readUInt8(this.offset);
    this.offset += 1;
    return value;
  }
 
  readU64(): bigint {
    this.checkBounds(8);
    const value = this.buffer.readBigUInt64LE(this.offset);
    this.offset += 8;
    return value;
  }
 
  readI64(): bigint {
    this.checkBounds(8);
    const value = this.buffer.readBigInt64LE(this.offset);
    this.offset += 8;
    return value;
  }
 
  private checkBounds(length: number) {
    Iif (this.offset + length > this.buffer.length) {
      throw new Error(`Buffer overflow: trying to read ${length} bytes at offset ${this.offset} in buffer of length ${this.buffer.length}`);
    }
  }
}
 
export class PumpfunParser {
  constructor(private readonly txWithMeta: ParsedTransactionWithMeta) { }
 
  public processTrades(): TradeInfo[] {
    return this.txWithMeta.transaction.message.instructions
      .reduce((trades: TradeInfo[], instruction: any, index: number) => {
        if (instruction.programId.toBase58() === DEX_PROGRAMS.PUMP_FUN.id) {
          trades.push(...this.processInstructionTrades(index));
        }
        return trades;
      }, []);
  }
 
  public processInstructionTrades(instructionIndex: number): TradeInfo[] {
    const events = this.parseInnerInstructions(instructionIndex);
    return this.processSwapData(events);
  }
 
  private parseInnerInstructions(instructionIndex: number): PumpfunTradeEvent[] {
    const innerInstructions = this.txWithMeta.meta?.innerInstructions;
    Iif (!innerInstructions) return [];
 
    return innerInstructions
      .filter(set => set.index === instructionIndex)
      .flatMap(set => set.instructions
        .filter(ix => this.isPumpFunTradeEvent(ix as PartiallyDecodedInstruction))
        .map(ix => this.parseTradeEvent(ix as PartiallyDecodedInstruction))
        .filter((event): event is PumpfunTradeEvent => event !== null)
      );
  }
 
  private processSwapData(events: PumpfunTradeEvent[]): TradeInfo[] {
    if (!events.length) return [];
 
    return events.map(event => this.createTradeInfo(event));
  }
 
  private createTradeInfo(event: PumpfunTradeEvent): TradeInfo {
    const tradeType: TradeType = event.isBuy ? "BUY" : "SELL";
    const isBuy = tradeType === 'BUY';
 
    return {
      type: tradeType,
      inputToken: {
        mint: isBuy ? event.mint.toBase58() : TOKENS.SOL,
        amount: isBuy ? convertToUiAmount(event.tokenAmount, 6) : convertToUiAmount(event.solAmount, 9),
        decimals: isBuy ? 6 : 9,
      },
      outputToken: {
        mint: isBuy ? TOKENS.SOL : event.mint.toBase58(),
        amount: isBuy ? convertToUiAmount(event.solAmount, 9) : convertToUiAmount(event.tokenAmount, 6),
        decimals: isBuy ? 9 : 6,
      },
      user: event.user.toBase58(),
      programId: DEX_PROGRAMS.PUMP_FUN.id,
      amm: DEX_PROGRAMS.PUMP_FUN.name,
      slot: this.txWithMeta.slot,
      timestamp: this.txWithMeta.blockTime || 0,
      signature: this.txWithMeta.transaction.signatures[0],
    };
  }
 
  private isPumpFunTradeEvent(instruction: PartiallyDecodedInstruction): boolean {
    try {
      const data = base58.decode(instruction.data as string);
      return Buffer.from(data.slice(0, 16)).equals(DISCRIMINATORS.PUMPFUN.TRADE_EVENT);
    } catch {
      return false;
    }
  }
 
  private parseTradeEvent(instruction: PartiallyDecodedInstruction): PumpfunTradeEvent | null {
    try {
      const data = base58.decode(instruction.data as string);
      return this.decodeTradeEvent(data.slice(16));
    } catch (error) {
      console.error('Failed to parse PumpFun trade event:', error);
      return null;
    }
  }
 
  private decodeTradeEvent(data: Buffer): PumpfunTradeEvent {
    const reader = new BinaryReader(data);
 
    return {
      mint: new PublicKey(reader.readFixedArray(32)),
      solAmount: reader.readU64(),
      tokenAmount: reader.readU64(),
      isBuy: reader.readU8() === 1,
      user: new PublicKey(reader.readFixedArray(32)),
      timestamp: reader.readI64(),
      virtualSolReserves: reader.readU64(),
      virtualTokenReserves: reader.readU64()
    };
  }
}