All files / src/parsers parser-jupiter.ts

7.52% Statements 7/93
0% Branches 0/43
0% Functions 0/20
8.33% Lines 7/84

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 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 3031x 1x 1x   1x   1x                                                                                           1x                                                                                 1x                                                                                                                                                                                                                                                                                                                                                                                                                                  
import { PublicKey } from '@solana/web3.js';
import { deserializeUnchecked } from 'borsh';
import { DEX_PROGRAMS, DISCRIMINATORS } from '../constants';
import { DexInfo, TradeInfo, TransferData } from '../types';
import { getAMMs, getInstructionData, getTradeType } from '../utils';
import { TransactionAdapter } from '../transaction-adapter';
import { TransactionUtils } from '../transaction-utils';
 
/**
 * Interface for Jupiter swap event data
 */
export interface JupiterSwapEvent {
  amm: PublicKey;
  inputMint: PublicKey;
  inputAmount: bigint;
  outputMint: PublicKey;
  outputAmount: bigint;
}
 
/**
 * Extended Jupiter swap event data with decimals and index
 */
export interface JupiterSwapEventData extends JupiterSwapEvent {
  inputMintDecimals: number;
  outputMintDecimals: number;
  idx: string;
}
 
/**
 * Borsh layout for Jupiter swap events
 */
class JupiterLayout {
  amm: Uint8Array;
  inputMint: Uint8Array;
  inputAmount: bigint;
  outputMint: Uint8Array;
  outputAmount: bigint;
 
  constructor(fields: {
    amm: Uint8Array;
    inputMint: Uint8Array;
    inputAmount: bigint;
    outputMint: Uint8Array;
    outputAmount: bigint;
  }) {
    this.amm = fields.amm;
    this.inputMint = fields.inputMint;
    this.inputAmount = fields.inputAmount;
    this.outputMint = fields.outputMint;
    this.outputAmount = fields.outputAmount;
  }
 
  static schema = new Map([
    [
      JupiterLayout,
      {
        kind: 'struct',
        fields: [
          ['amm', [32]],
          ['inputMint', [32]],
          ['inputAmount', 'u64'],
          ['outputMint', [32]],
          ['outputAmount', 'u64'],
        ],
      },
    ],
  ]);
 
  toSwapEvent(): JupiterSwapEvent {
    return {
      amm: new PublicKey(this.amm),
      inputMint: new PublicKey(this.inputMint),
      inputAmount: this.inputAmount,
      outputMint: new PublicKey(this.outputMint),
      outputAmount: this.outputAmount,
    };
  }
}
 
/**
 * Intermediate swap info for processing Jupiter events
 */
export interface JupiterSwapInfo {
  amms: string[];
  tokenIn: Map<string, bigint>;
  tokenOut: Map<string, bigint>;
  decimals: Map<string, number>;
  idx: string;
}
 
/**
 * Parser for Jupiter DEX transactions
 */
export class JupiterParser {
  private readonly utils: TransactionUtils;
 
  constructor(
    private readonly adapter: TransactionAdapter,
    private readonly dexInfo: DexInfo,
    private readonly transferActions: Record<string, TransferData[]>
  ) {
    this.utils = new TransactionUtils(adapter);
  }
 
  /**
   * Process trades from transaction
   */
  public processTrades(): TradeInfo[] {
    const trades: TradeInfo[] = [];
 
    this.adapter.instructions.forEach((ix: any, idx: number) => {
      Iif (this.isTradeInstruction(ix)) {
        const trade = this.processInstruction(ix, idx);
        trades.push(...trade);
      }
    });
 
    return trades;
  }
 
  /**
   * Process instruction
   */
  private processInstruction(instruction: any, idx: number): TradeInfo[] {
    try {
      const events = this.processJupiterSwaps(idx);
      const data = this.processSwapData(events);
      return data ? [data] : [];
    } catch (error) {
      console.error('Process instruction error:', error);
      return [];
    }
  }
 
  /**
   * Check if instruction is a trade instruction
   */
  private isTradeInstruction(instruction: any): boolean {
    const programId = this.adapter.getInstructionProgramId(instruction);
    return [DEX_PROGRAMS.JUPITER.id, DEX_PROGRAMS.JUPITER_DCA.id].includes(programId);
  }
 
  /**
   * Process Jupiter swap events
   */
  private processJupiterSwaps(instructionIndex: number): JupiterSwapEventData[] {
    const innerInstructions = this.adapter.innerInstructions;
    Iif (!innerInstructions) return [];
 
    return innerInstructions
      .filter((set) => set.index === instructionIndex)
      .flatMap((set) =>
        set.instructions
          .filter((ix) => this.isJupiterRouteEventInstruction(ix))
          .map((ix, idx) => this.parseJupiterRouteEventInstruction(ix, `${instructionIndex}-${idx}`))
          .filter((event): event is JupiterSwapEventData => event !== null)
      );
  }
 
  /**
   * Check if instruction is a Jupiter route event
   */
  private isJupiterRouteEventInstruction(instruction: any): boolean {
    const programId = this.adapter.getInstructionProgramId(instruction);
    Iif (programId !== DEX_PROGRAMS.JUPITER.id) return false;
 
    const data = getInstructionData(instruction);
    Iif (!data || data.length < 16) return false;
 
    return Buffer.from(data.slice(0, 16)).equals(Buffer.from(DISCRIMINATORS.JUPITER.ROUTE_EVENT));
  }
 
  /**
   * Parse Jupiter route event instruction
   */
  private parseJupiterRouteEventInstruction(instruction: any, idx: string): JupiterSwapEventData | null {
    try {
      const data = getInstructionData(instruction);
      Iif (!data) return null;
 
      Iif (data.length < 16) return null;
 
      const eventData = data.slice(16);
      const layout = deserializeUnchecked(JupiterLayout.schema, JupiterLayout, Buffer.from(eventData));
      const swapEvent = layout.toSwapEvent();
 
      return {
        ...swapEvent,
        inputMintDecimals: this.adapter.getTokenDecimals(swapEvent.inputMint.toBase58()) || 0,
        outputMintDecimals: this.adapter.getTokenDecimals(swapEvent.outputMint.toBase58()) || 0,
        idx,
      };
    } catch (error) {
      console.error('Parse Jupiter route event error:', error);
      return null;
    }
  }
 
  /**
   * Process swap data from events
   */
  private processSwapData(events: JupiterSwapEventData[]): TradeInfo | null {
    Iif (events.length === 0) return null;
 
    const intermediateInfo: JupiterSwapInfo = {
      amms: [],
      tokenIn: new Map(),
      tokenOut: new Map(),
      decimals: new Map(),
      idx: '',
    };
 
    // Process events
    for (const event of events) {
      const inputMint = event.inputMint.toBase58();
      const outputMint = event.outputMint.toBase58();
 
      intermediateInfo.tokenIn.set(
        inputMint,
        (intermediateInfo.tokenIn.get(inputMint) || BigInt(0)) + event.inputAmount
      );
      intermediateInfo.tokenOut.set(
        outputMint,
        (intermediateInfo.tokenOut.get(outputMint) || BigInt(0)) + event.outputAmount
      );
 
      intermediateInfo.decimals.set(inputMint, event.inputMintDecimals);
      intermediateInfo.decimals.set(outputMint, event.outputMintDecimals);
      intermediateInfo.idx = event.idx;
    }
 
    // Remove intermediate tokens
    for (const [mint, inAmount] of intermediateInfo.tokenIn.entries()) {
      const outAmount = intermediateInfo.tokenOut.get(mint);
      Iif (outAmount && inAmount === outAmount) {
        intermediateInfo.tokenIn.delete(mint);
        intermediateInfo.tokenOut.delete(mint);
      }
    }
 
    return intermediateInfo.tokenIn.size > 0 && intermediateInfo.tokenOut.size > 0
      ? this.convertToTradeInfo(intermediateInfo)
      : null;
  }
 
  /**
   * Convert swap info to trade info
   */
  private convertToTradeInfo(info: JupiterSwapInfo): TradeInfo | null {
    Iif (info.tokenIn.size !== 1 || info.tokenOut.size !== 1) return null;
 
    const [[inMint, inAmount]] = Array.from(info.tokenIn.entries());
    const [[outMint, outAmount]] = Array.from(info.tokenOut.entries());
    const inDecimals = info.decimals.get(inMint) || 0;
    const outDecimals = info.decimals.get(outMint) || 0;
 
    const signerIndex = this.containsDCAProgram() ? 2 : 0;
    const signer = this.adapter.getAccountKey(signerIndex);
 
    const trade = {
      type: getTradeType(inMint, outMint),
      inputToken: {
        mint: inMint,
        amount: Number(inAmount) / 10 ** inDecimals,
        decimals: inDecimals,
      },
      outputToken: {
        mint: outMint,
        amount: Number(outAmount) / 10 ** outDecimals,
        decimals: outDecimals,
      },
      user: signer,
      programId: this.dexInfo.programId,
      amm: this.dexInfo.amm || getAMMs(Object.keys(this.transferActions))?.[0] || '',
      route: this.dexInfo.route || '',
      slot: this.adapter.slot,
      timestamp: this.adapter.blockTime,
      signature: this.adapter.signature,
      idx: info.idx,
    };
 
    return this.utils.attachTokenTransferInfo(trade, this.transferActions);
  }
 
  /**
   * Check if transaction contains DCA program
   */
  private containsDCAProgram(): boolean {
    return this.adapter.accountKeys.some((key) => key === DEX_PROGRAMS.JUPITER_DCA.id);
  }
 
  /**
   * Parse transfer actions
   */
  public parseTransferAction(transfer: [string, TransferData[]]): TradeInfo[] {
    const [, transfers] = transfer;
    Iif (transfers.length < 2) return [];
 
    const trade = this.utils.processSwapData(transfers, this.dexInfo);
    return trade ? [trade] : [];
  }
}