All files / src/parsers parser-moonshot.ts

6.32% Statements 5/79
0% Branches 0/39
0% Functions 0/22
6.57% Lines 5/76

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 1861x 1x 1x   1x   1x                                                                                                                                                                                                                                                                                                                                                                      
import { DEX_PROGRAMS, DISCRIMINATORS, TOKENS } from '../constants';
import { convertToUiAmount, DexInfo, TokenAmount, TradeInfo, TradeType, TransferData } from '../types';
import { absBigInt, getInstructionData } from '../utils';
import { TransactionAdapter } from '../transaction-adapter';
import { TransactionUtils } from '../transaction-utils';
 
export class MoonshotParser {
  private readonly utils: TransactionUtils;
 
  constructor(
    private readonly adapter: TransactionAdapter,
    private readonly dexInfo: DexInfo,
    private readonly transferActions: Record<string, TransferData[]>
  ) {
    this.utils = new TransactionUtils(adapter);
  }
 
  public processTrades(): TradeInfo[] {
    const trades: TradeInfo[] = [];
    const instructions = this.adapter.instructions;
 
    instructions.forEach((instruction: any, index: number) => {
      Iif (this.isTradeInstruction(instruction)) {
        trades.push(...this.processInstructionTrades(instruction, index));
      }
    });
 
    return trades;
  }
 
  public processInstructionTrades(instruction: any, outerIndex: number): TradeInfo[] {
    const trades: TradeInfo[] = [];
 
    // outer instruction
    const instructions = this.adapter.instructions;
    trades.push(
      ...instructions
        .filter((instruction: any, index: number) => outerIndex == index && this.isTradeInstruction(instruction))
        .map((instruction: any, index: any) => this.parseTradeInstruction(instruction, `${outerIndex}-${index}`))
        .filter((transfer: any): transfer is TradeInfo => transfer !== null)
    );
 
    // inner instruction
    const innerInstructions = this.adapter.innerInstructions;
    Iif (innerInstructions) {
      trades.push(
        ...innerInstructions
          .filter((set) => set.index === outerIndex)
          .flatMap((set) =>
            set.instructions
              .map((instruction, index) => this.parseTradeInstruction(instruction, `${outerIndex}-${index}`))
              .filter((transfer): transfer is TradeInfo => transfer !== null)
          )
      );
    }
 
    return trades;
  }
 
  public isTradeInstruction(instruction: any): boolean {
    const programId = this.adapter.getInstructionProgramId(instruction);
    const accounts = this.adapter.getInstructionAccounts(instruction);
    return programId == DEX_PROGRAMS.MOONSHOT.id && accounts && accounts.length === 11;
  }
 
  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 parseTradeInstruction(instruction: any, idx: string): TradeInfo | null {
    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]; // meme
    const accountKeys = this.adapter.accountKeys;
    const collateralMint = this.detectCollateralMint(accountKeys);
    const { tokenAmount, collateralAmount } = this.calculateAmounts(moonshotTokenMint, collateralMint);
 
    return this.createTradeInfo(tradeType, tokenAmount, collateralAmount, moonshotTokenMint, collateralMint, idx);
  }
 
  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 createTradeInfo(
    tradeType: TradeType,
    tokenAmount: TokenAmount,
    collateralAmount: TokenAmount,
    moonshotTokenMint: string,
    collateralMint: string,
    idx: string
  ): TradeInfo {
    const trade: TradeInfo = {
      type: tradeType,
      inputToken: {
        mint: tradeType == 'BUY' ? collateralMint : moonshotTokenMint,
        amount: tradeType == 'BUY' ? collateralAmount.uiAmount : tokenAmount.uiAmount,
        decimals: tradeType == 'BUY' ? collateralAmount.decimals : tokenAmount.decimals,
      },
      outputToken: {
        mint: tradeType == 'BUY' ? moonshotTokenMint : collateralMint,
        amount: tradeType == 'BUY' ? tokenAmount.uiAmount : collateralAmount.uiAmount,
        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);
  }
 
  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,
      uiAmount: convertToUiAmount(amount, decimals),
      decimals,
    };
  }
}