All files / src/parsers/moonshot parser-moonshot.ts

7.93% Statements 5/63
0% Branches 0/51
0% Functions 0/12
8.62% Lines 5/58

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  1x 1x 1x 1x   1x                                                                                                                                                                                                                                                                          
import { TokenAmount } from '@solana/web3.js';
import { DEX_PROGRAMS, DISCRIMINATORS, TOKENS } from '../../constants';
import { convertToUiAmount, TradeInfo, TradeType } from '../../types';
import { absBigInt, getInstructionData } from '../../utils';
import { BaseParser } from '../base-parser';
 
export class MoonshotParser extends BaseParser {
  public processTrades(): TradeInfo[] {
    const trades: TradeInfo[] = [];
 
    this.classifiedInstructions.forEach(({ instruction, programId, outerIndex, innerIndex }) => {
      Iif (this.isTradeInstruction(instruction, programId)) {
        const trade = this.parseTradeInstruction(instruction, `${outerIndex}-${innerIndex ?? 0}`);
        Iif (trade) {
          trades.push(trade);
        }
      }
    });
 
    return trades;
  }
 
  private isTradeInstruction(instruction: any, programId: string): boolean {
    const accounts = this.adapter.getInstructionAccounts(instruction);
    return programId === DEX_PROGRAMS.MOONSHOT.id && accounts && accounts.length === 11;
  }
 
  private parseTradeInstruction(instruction: any, idx: string): TradeInfo | null {
    try {
      Iif (!('data' in instruction)) return null;
 
      const data = getInstructionData(instruction);
      const discriminator = data.slice(0, 8);
      let tradeType: TradeType;
 
      if (discriminator.equals(DISCRIMINATORS.MOONSHOT.BUY)) {
        tradeType = 'BUY';
      } else if (discriminator.equals(DISCRIMINATORS.MOONSHOT.SELL)) {
        tradeType = 'SELL';
      } else {
        return null;
      }
 
      const moonshotTokenMint = this.adapter.getInstructionAccounts(instruction)[6];
      const accountKeys = this.adapter.accountKeys;
      const collateralMint = this.detectCollateralMint(accountKeys);
      const { tokenAmount, collateralAmount } = this.calculateAmounts(moonshotTokenMint, collateralMint);
 
      const trade: TradeInfo = {
        type: tradeType,
        inputToken: {
          mint: tradeType === 'BUY' ? collateralMint : moonshotTokenMint,
          amount: tradeType === 'BUY' ? (collateralAmount.uiAmount ?? 0) : (tokenAmount.uiAmount ?? 0),
          amountRaw: tradeType === 'BUY' ? collateralAmount.amount : tokenAmount.amount,
          decimals: tradeType === 'BUY' ? collateralAmount.decimals : tokenAmount.decimals,
        },
        outputToken: {
          mint: tradeType === 'BUY' ? moonshotTokenMint : collateralMint,
          amount: tradeType === 'BUY' ? (tokenAmount.uiAmount ?? 0) : (collateralAmount.uiAmount ?? 0),
          amountRaw: tradeType === 'BUY' ? tokenAmount.amount : collateralAmount.amount,
          decimals: tradeType === 'BUY' ? tokenAmount.decimals : collateralAmount.decimals,
        },
        user: this.adapter.signer,
        programId: DEX_PROGRAMS.MOONSHOT.id,
        amm: DEX_PROGRAMS.MOONSHOT.name,
        route: this.dexInfo.route || '',
        slot: this.adapter.slot,
        timestamp: this.adapter.blockTime,
        signature: this.adapter.signature,
        idx,
      };
 
      return this.utils.attachTokenTransferInfo(trade, this.transferActions);
    } catch (error) {
      console.error('Failed to parse Moonshot trade:', error);
      return null;
    }
  }
 
  private detectCollateralMint(accountKeys: string[]): string {
    Iif (accountKeys.some((key) => key === TOKENS.USDC)) return TOKENS.USDC;
    Iif (accountKeys.some((key) => key === TOKENS.USDT)) return TOKENS.USDT;
    return TOKENS.SOL;
  }
 
  private calculateAmounts(tokenMint: string, collateralMint: string) {
    const tokenBalanceChanges = this.getTokenBalanceChanges(tokenMint);
    const collateralBalanceChanges = this.getTokenBalanceChanges(collateralMint);
 
    return {
      tokenAmount: this.createTokenAmount(absBigInt(tokenBalanceChanges), tokenMint),
      collateralAmount: this.createTokenAmount(absBigInt(collateralBalanceChanges), collateralMint),
    };
  }
 
  private getTokenBalanceChanges(mint: string): bigint {
    const signer = this.adapter.signer;
 
    Iif (mint === TOKENS.SOL) {
      Iif (!this.adapter.postBalances?.[0] || !this.adapter.preBalances?.[0]) {
        throw new Error('Insufficient balance information for SOL');
      }
      return BigInt(this.adapter.postBalances[0] - this.adapter.preBalances[0]);
    }
 
    let preAmount = BigInt(0);
    let postAmount = BigInt(0);
    let balanceFound = false;
 
    this.adapter.preTokenBalances?.forEach((preBalance) => {
      Iif (preBalance.mint === mint && preBalance.owner === signer) {
        preAmount = BigInt(preBalance.uiTokenAmount.amount);
        balanceFound = true;
      }
    });
 
    this.adapter.postTokenBalances?.forEach((postBalance) => {
      Iif (postBalance.mint === mint && postBalance.owner === signer) {
        postAmount = BigInt(postBalance.uiTokenAmount.amount);
        balanceFound = true;
      }
    });
 
    Iif (!balanceFound) {
      throw new Error('Could not find balance for specified mint and signer');
    }
 
    return postAmount - preAmount;
  }
 
  private createTokenAmount(amount: bigint, mint: string): TokenAmount {
    const decimals = this.adapter.getTokenDecimals(mint);
    return {
      amount: amount.toString(),
      uiAmount: convertToUiAmount(amount, decimals),
      decimals,
    };
  }
}