All files parser-jupiter.ts

89.28% Statements 75/84
67.5% Branches 27/40
100% Functions 18/18
90.36% Lines 75/83

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 2651x 1x 1x 1x 1x 1x                                                           3x 3x 3x 3x 3x     1x                                 3x                                 1x       2x 2x   2x 2x       2x   11x 2x 2x   11x         2x 2x 2x 2x               2x 2x   2x 5x 2x 16x 3x 3x               16x   13x     3x 3x               3x 3x 3x   3x           3x   3x                         2x       2x             2x   3x 3x     3x       3x           3x 3x       2x 3x 3x 1x 1x       2x       2x           2x               2x 2x   2x       2x 2x 2x 2x   2x 2x 2x 2x                                           2x 20x      
import { ParsedTransactionWithMeta, PartiallyDecodedInstruction, PublicKey } from '@solana/web3.js';
import bs58 from 'bs58';
import { DEX_PROGRAMS, DISCRIMINATORS, TOKENS } from './constants';
import { deserializeUnchecked } from 'borsh';
import { convertToUiAmount, DexInfo, TradeInfo } from './types';
import { TokenInfoExtractor } from './token-extractor';
 
export interface JupiterSwapEvent {
    amm: PublicKey;
    inputMint: PublicKey;
    inputAmount: bigint;
    outputMint: PublicKey;
    outputAmount: bigint;
}
 
export interface JupiterSwapEventData extends JupiterSwapEvent {
    inputMintDecimals: number;
    outputMintDecimals: number;
}
 
// Borsh class definition for Jupiter 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
        };
    }
}
 
export interface JupiterSwapInfo {
    amms: string[];
    tokenIn: Map<string, bigint>;
    tokenOut: Map<string, bigint>;
    decimals: Map<string, number>;
}
 
export class JupiterParser {
    private readonly splDecimalsMap: Map<string, number>;
 
    constructor(
        private readonly txWithMeta: ParsedTransactionWithMeta,
        private readonly dexInfo: DexInfo
    ) {
        const tokenExtractor = new TokenInfoExtractor(txWithMeta);
        this.splDecimalsMap = tokenExtractor.extractDecimals();
    }
 
    public processTrades(): TradeInfo[] {
        return this.txWithMeta.transaction.message.instructions
            .reduce((trades: TradeInfo[], instruction: any, index: number) => {
                if ([DEX_PROGRAMS.JUPITER.id,DEX_PROGRAMS.JUPITER_DCA.id].includes(instruction.programId.toBase58())) {
                    const instructionTrades = this.processInstructionTrades(index);
                    trades.push(...instructionTrades);
                }
                return trades;
            }, []);
    }
 
    public processInstructionTrades(instructionIndex: number): TradeInfo[] {
        try {
            const events = this.processJupiterSwaps(instructionIndex);
            const data = this.processSwapData(events);
            return data ? [data] : [];
        } catch (error) {
            console.log('Error processing Jupiter trades:', error, this.txWithMeta.transaction.signatures[0]);
            return [];
        }
    }
 
    private processJupiterSwaps(instructionIndex: number): JupiterSwapEventData[] {
        const innerInstructions = this.txWithMeta.meta?.innerInstructions;
        Iif (!innerInstructions) return [];
 
        return innerInstructions
            .filter(set => set.index === instructionIndex)
            .flatMap(set => set.instructions
                .filter((instruction) => this.isJupiterRouteEventInstruction(instruction as PartiallyDecodedInstruction))
                .map(instruction => this.parseJupiterRouteEventInstruction(instruction as PartiallyDecodedInstruction))
                .filter((transfer): transfer is JupiterSwapEventData => transfer !== null)
            );
    }
 
    private isJupiterRouteEventInstruction(
        instruction: PartiallyDecodedInstruction
    ): boolean {
       
        if (instruction.programId.toBase58() != (DEX_PROGRAMS.JUPITER.id) ||
            instruction.data?.length < 16) {
            return false;
        }
 
        const decodedData = bs58.decode(instruction.data.toString());
        return Buffer.from(decodedData.slice(0, 16)).equals(
            Buffer.from(DISCRIMINATORS.JUPITER.ROUTE_EVENT)
        );
    }
 
    private parseJupiterRouteEventInstruction(
        instruction: PartiallyDecodedInstruction
    ): JupiterSwapEventData | null {
        try {
            const decodedData = bs58.decode(instruction.data.toString());
            const eventData = decodedData.slice(16); // Skip discriminator
 
            const layout = deserializeUnchecked(
                JupiterLayout.schema,
                JupiterLayout,
                Buffer.from(eventData)
            );
 
            const swapEvent = layout.toSwapEvent();
 
            return {
                ...swapEvent,
                inputMintDecimals: this.splDecimalsMap.get(swapEvent.inputMint.toBase58()) || 0,
                outputMintDecimals: this.splDecimalsMap.get(swapEvent.outputMint.toBase58()) || 0,
            };
        } catch (error) {
            throw (
                `Failed to parse Jupiter route event: ${error instanceof Error ? error.message : 'Unknown error'}`
            );
        }
    }
 
    private processSwapData(events: JupiterSwapEventData[]): TradeInfo | null {
        Iif (events.length === 0) {
            throw ('No events provided');
        }
 
        const intermediateInfo: JupiterSwapInfo = {
            amms: [],
            tokenIn: new Map(),
            tokenOut: new Map(),
            decimals: new Map(),
        };
 
        for (const jupiterEvent of events) {
 
            const inputMint = jupiterEvent.inputMint.toBase58();
            const outputMint = jupiterEvent.outputMint.toBase58();
 
            // Update token amounts
            intermediateInfo.tokenIn.set(
                inputMint,
                (intermediateInfo.tokenIn.get(inputMint) || BigInt(0)) + jupiterEvent.inputAmount
            );
            intermediateInfo.tokenOut.set(
                outputMint,
                (intermediateInfo.tokenOut.get(outputMint) || BigInt(0)) + jupiterEvent.outputAmount
            );
 
            // Store decimals
            intermediateInfo.decimals.set(inputMint, jupiterEvent.inputMintDecimals);
            intermediateInfo.decimals.set(outputMint, jupiterEvent.outputMintDecimals);
        }
 
        // Remove intermediate tokens
        for (const [mint, inAmount] of intermediateInfo.tokenIn.entries()) {
            const outAmount = intermediateInfo.tokenOut.get(mint);
            if (outAmount && inAmount === outAmount) {
                intermediateInfo.tokenIn.delete(mint);
                intermediateInfo.tokenOut.delete(mint);
            }
        }
 
        Iif (intermediateInfo.tokenIn.size === 0 || intermediateInfo.tokenOut.size === 0) {
            throw ('Invalid swap: all tokens were removed as intermediates');
        }
 
        return this.convertToSwapInfo(intermediateInfo);
    }
 
    private convertToSwapInfo(
        intermediateInfo: JupiterSwapInfo,
    ): TradeInfo | null {
        Iif (intermediateInfo.tokenIn.size !== 1 || intermediateInfo.tokenOut.size !== 1) {
 
            console.error(
                `Invalid swap: expected 1 input and 1 output token, got ${intermediateInfo.tokenIn.size} input(s) and ${intermediateInfo.tokenOut.size} output(s)`
            );
            return null;
        }
 
        const [inMintEntry] = Array.from(intermediateInfo.tokenIn.entries());
        const [outMintEntry] = Array.from(intermediateInfo.tokenOut.entries());
 
        Iif (!inMintEntry || !outMintEntry) {
            throw ('Missing input or output token information');
        }
 
        const [inMint, inAmount] = inMintEntry;
        const [outMint, outAmount] = outMintEntry;
        const inMintDecimals = intermediateInfo.decimals.get(inMint) || 0;
        const outMintDecimals = intermediateInfo.decimals.get(inMint) || 0;
        // Determine signer based on DCA program presence
        const signerIndex = this.containsDCAProgram() ? 2 : 0;
        const signer = this.txWithMeta.transaction.message.accountKeys[signerIndex].pubkey.toBase58();
        const tradeType = Object.values(TOKENS).includes(inMint) ? "SELL" : "BUY";
        return {
            type: tradeType,
            inputToken: {
                mint: inMint,
                amount: convertToUiAmount(inAmount, inMintDecimals),
                decimals: inMintDecimals
            },
            outputToken: {
                mint: outMint,
                amount: convertToUiAmount(outAmount, outMintDecimals),
                decimals: outMintDecimals
            },
            user: signer,
            programId: this.dexInfo.programId,
            amm: this.dexInfo.amm,
            slot: this.txWithMeta.slot,
            timestamp: this.txWithMeta.blockTime || 0,
            signature: this.txWithMeta.transaction.signatures[0],
        };
    }
 
    private containsDCAProgram(): boolean {
        return this.txWithMeta.transaction.message.accountKeys.some(key =>
            key.pubkey.toBase58() == (DEX_PROGRAMS.JUPITER_DCA.id)
        );
    }
}