All files / src transaction-adapter.ts

50.77% Statements 98/193
36.95% Branches 51/138
62.71% Functions 37/59
58.02% Lines 94/162

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 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 4681x 1x 1x 1x         1x 1x 1x 1x     1x 1x   1x 1x       9x       1x 1x                 2x                     5x             5x             4x             3x                                         2x             1x                     1x 17x 1x 1x 1x                             23x 23x                           23x 98x 98x 98x             23x 23x             37x                                                                 3x 7x     3x 3x                                                                     3x 6x   17x           3x 6x   17x         1x                                   20x 20x       2x 3x                         1x                             1x     1x     1x 1x     1x                 1x 1x 4x   4x 4x 4x           4x     4x 2x                 1x 6x 6x             1x 2x 8x 8x                 6x 3x 2x 1x 1x                 6x 3x 3x                     6x                                           14x 14x 14x 14x       8x 8x 6x           3x 3x         3x 3x                                                       6x      
import { MessageV0, PublicKey, TokenAmount } from '@solana/web3.js';
import { SPL_TOKEN_INSTRUCTION_TYPES, TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID, TOKENS } from './constants';
import { convertToUiAmount, ParseConfig, PoolEventType, SolanaTransaction, TokenInfo } from './types';
import { getInstructionData, getProgramName, getPubkeyString } from './utils';
 
/**
 * Adapter for unified transaction data access
 */
export class TransactionAdapter {
  public readonly accountKeys: string[] = [];
  public readonly splTokenMap: Map<string, TokenInfo> = new Map();
  public readonly splDecimalsMap: Map<string, number> = new Map();
 
  constructor(
    private tx: SolanaTransaction,
    public config?: ParseConfig
  ) {
    this.accountKeys = this.extractAccountKeys();
    this.extractTokenInfo();
  }
 
  get txMessage() {
    return this.tx.transaction.message as any;
  }
 
  get isMessageV0() {
    const message = this.tx.transaction.message;
    return (
      message instanceof MessageV0 ||
      ('header' in message && 'staticAccountKeys' in message && 'compiledInstructions' in message)
    );
  }
  /**
   * Get transaction slot
   */
  get slot() {
    return this.tx.slot;
  }
 
  get version() {
    return this.tx.version;
  }
 
  /**
   * Get transaction block time
   */
  get blockTime() {
    return this.tx.blockTime || 0;
  }
 
  /**
   * Get transaction signature
   */
  get signature() {
    return this.tx.transaction.signatures[0];
  }
 
  /**
   * Get all instructions
   */
  get instructions() {
    return this.txMessage.instructions || this.txMessage.compiledInstructions;
  }
 
  /**
   * Get inner instructions
   */
  get innerInstructions() {
    return this.tx.meta?.innerInstructions;
  }
 
  /**
   * Get pre balances
   */
  get preBalances() {
    return this.tx.meta?.preBalances;
  }
 
  /**
   * Get post balances
   */
  get postBalances() {
    return this.tx.meta?.postBalances;
  }
 
  /**
   * Get pre token balances
   */
  get preTokenBalances() {
    return this.tx.meta?.preTokenBalances;
  }
 
  /**
   * Get post token balances
   */
  get postTokenBalances() {
    return this.tx.meta?.postTokenBalances;
  }
 
  /**
   * Get first signer account
   */
  get signer(): string {
    return this.getAccountKey(0);
  }
 
  extractAccountKeys() {
    if (this.isMessageV0) {
      const keys = this.txMessage.staticAccountKeys.map((it: any) => getPubkeyString(it)) || [];
      const key2 = this.tx.meta?.loadedAddresses?.writable.map((it) => getPubkeyString(it)) || [];
      const key3 = this.tx.meta?.loadedAddresses?.readonly.map((it) => getPubkeyString(it)) || [];
      return [...keys, ...key2, ...key3];
    } else Eif (this.version == 0) {
      const keys = this.getAccountKeys(this.txMessage.accountKeys) || [];
      const key2 = this.getAccountKeys(this.tx.meta?.loadedAddresses?.writable ?? []) || [];
      const key3 = this.getAccountKeys(this.tx.meta?.loadedAddresses?.readonly ?? []) || [];
      return [...keys, ...key2, ...key3];
    } else {
      return this.getAccountKeys(this.txMessage.accountKeys) || [];
    }
  }
 
  /**
   * Get unified instruction data
   */
  getInstruction(instruction: any) {
    const isParsed = !this.isCompiledInstruction(instruction);
    return {
      programId: isParsed ? getPubkeyString(instruction.programId) : this.accountKeys[instruction.programIdIndex],
      accounts: this.getInstructionAccounts(instruction),
      data: 'data' in instruction ? instruction.data : '',
      parsed: 'parsed' in instruction ? instruction.parsed : undefined,
      program: instruction.program || '',
    };
  }
 
  getInnerInstruction(outerIndex: number, innterIndex: number) {
    return this.innerInstructions?.find((it) => it.index == outerIndex)?.instructions[innterIndex];
  }
 
  getAccountKeys(accounts: any[]): string[] {
    return accounts?.map((it: any) => {
      Iif (it instanceof PublicKey) return it.toBase58();
      Iif (typeof it == 'string') return it;
      if (typeof it == 'number') return this.accountKeys[it];
      Iif ('pubkey' in it) return getPubkeyString(it.pubkey);
      return it;
    });
  }
 
  getInstructionAccounts(instruction: any): string[] {
    const accounts = instruction.accounts || instruction.accountKeyIndexes;
    return this.getAccountKeys(accounts);
  }
 
  /**
   * Check if instruction is Compiled
   */
  isCompiledInstruction(instruction: any): boolean {
    return 'programIdIndex' in instruction && !('parsed' in instruction);
  }
 
  /**
   * Get instruction type
   * returns string name if instruction Parsed, e.g. 'transfer';
   * returns number if instruction is Compiled, e.g. 3
   */
  getInstructionType(instruction: any): string | undefined {
    Iif ('parsed' in instruction && instruction.parsed) {
      return instruction.parsed.type; // string name, e.g. 'transfer'
    }
 
    // For compiled instructions, try to decode type from data
    const data = getInstructionData(instruction);
    return data.length > 0 ? data[0].toString() : undefined; // number, e.g. 3
  }
 
  /**
   * Get account key by index
   */
  getAccountKey(index: number): string {
    return this.accountKeys[index];
  }
 
  getAccountIndex(address: string): number {
    return this.accountKeys.findIndex((it) => it == address);
  }
 
  /**
   * Get token account owner
   */
  getTokenAccountOwner(accountKey: string): string | undefined {
    const accountInfo = this.tx.meta?.postTokenBalances?.find(
      (balance) => this.accountKeys[balance.accountIndex] === accountKey
    );
 
    if (accountInfo) {
      return accountInfo.owner;
    }
 
    return undefined;
  }
 
  getAccountBalance(accountKeys: string[]): (TokenAmount | undefined)[] {
    return accountKeys.map((accountKey) => {
      Iif (accountKey == '') return undefined;
      const index = this.accountKeys.findIndex((it) => it == accountKey);
      Iif (index == -1) return undefined;
      const amount = this.tx.meta?.postBalances[index] || 0;
      return {
        amount: amount.toString(),
        uiAmount: convertToUiAmount(amount.toString()),
        decimals: 9,
      };
    });
  }
 
  getAccountPreBalance(accountKeys: string[]): (TokenAmount | undefined)[] {
    return accountKeys.map((accountKey) => {
      Iif (accountKey == '') return undefined;
      const index = this.accountKeys.findIndex((it) => it == accountKey);
      Iif (index == -1) return undefined;
      const amount = this.tx.meta?.preBalances[index] || 0;
      return {
        amount: amount.toString(),
        uiAmount: convertToUiAmount(amount.toString()),
        decimals: 9,
      };
    });
  }
 
  getTokenAccountBalance(accountKeys: string[]): (TokenAmount | undefined)[] {
    return accountKeys.map((accountKey) =>
      accountKey == ''
        ? undefined
        : this.tx.meta?.postTokenBalances?.find((balance) => this.accountKeys[balance.accountIndex] === accountKey)
            ?.uiTokenAmount
    );
  }
 
  getTokenAccountPreBalance(accountKeys: string[]): (TokenAmount | undefined)[] {
    return accountKeys.map((accountKey) =>
      accountKey == ''
        ? undefined
        : this.tx.meta?.preTokenBalances?.find((balance) => this.accountKeys[balance.accountIndex] === accountKey)
            ?.uiTokenAmount
    );
  }
 
  private readonly defaultSolInfo: TokenInfo = {
    mint: TOKENS.SOL,
    amount: 0,
    amountRaw: '0',
    decimals: 9,
  };
 
  /**
   * Check if token is supported
   */
  isSupportedToken(mint: string): boolean {
    return Object.values(TOKENS).includes(mint);
  }
 
  /**
   * Get program ID from instruction
   */
  getInstructionProgramId(instruction: any): string {
    const ix = this.getInstruction(instruction);
    return ix.programId;
  }
 
  getTokenDecimals(mint: string): number {
    return (
      this.preTokenBalances?.find((b) => b.mint === mint)?.uiTokenAmount?.decimals ||
      this.postTokenBalances?.find((b) => b.mint === mint)?.uiTokenAmount?.decimals ||
      9
    );
  }
 
  /**
   * Create base pool event data
   * @param type - Type of pool event
   * @param tx - The parsed transaction with metadata
   * @param programId - The program ID associated with the event
   * @returns Base pool event object
   */
  getPoolEventBase = (type: PoolEventType, programId: string) => ({
    user: this.signer,
    type,
    programId,
    amm: getProgramName(programId),
    slot: this.slot,
    timestamp: this.blockTime,
    signature: this.signature,
  });
 
  /**
   * Extract token information from transaction
   */
  private extractTokenInfo() {
    // Process token balances
    this.extractTokenBalances();
 
    // Process transfer instructions for additional token info
    this.extractTokenFromInstructions();
 
    // Add SOL token info if not exists
    if (!this.splTokenMap.has(TOKENS.SOL)) {
      this.splTokenMap.set(TOKENS.SOL, this.defaultSolInfo);
    }
 
    Iif (!this.splDecimalsMap.has(TOKENS.SOL)) {
      this.splDecimalsMap.set(TOKENS.SOL, this.defaultSolInfo.decimals);
    }
  }
 
  /**
   * Extract token balances from pre and post states
   */
  private extractTokenBalances() {
    const postBalances = this.postTokenBalances || [];
    postBalances.forEach((balance) => {
      Iif (!balance.mint) return;
 
      const accountKey = this.accountKeys[balance.accountIndex];
      if (!this.splTokenMap.has(accountKey)) {
        const tokenInfo: TokenInfo = {
          mint: balance.mint,
          amount: balance.uiTokenAmount.uiAmount || 0,
          amountRaw: balance.uiTokenAmount.amount,
          decimals: balance.uiTokenAmount.decimals,
        };
        this.splTokenMap.set(accountKey, tokenInfo);
      }
 
      if (!this.splDecimalsMap.has(balance.mint)) {
        this.splDecimalsMap.set(balance.mint, balance.uiTokenAmount.decimals);
      }
    });
  }
 
  /**
   * Extract token info from transfer instructions
   */
  private extractTokenFromInstructions() {
    this.instructions.forEach((ix: any) => {
      if (this.isCompiledInstruction(ix)) {
        this.extractFromCompiledTransfer(ix);
      } else E{
        this.extractFromParsedTransfer(ix);
      }
    });
 
    // Process inner instructions
    this.innerInstructions?.forEach((inner) => {
      inner.instructions.forEach((ix) => {
        if (this.isCompiledInstruction(ix)) {
          this.extractFromCompiledTransfer(ix);
        } else E{
          this.extractFromParsedTransfer(ix);
        }
      });
    });
  }
 
  private setTokenInfo(source?: string, destination?: string, mint?: string, decimals?: number) {
    if (source) {
      if (this.splTokenMap.has(source) && mint && decimals) {
        this.splTokenMap.set(source, { mint, amount: 0, amountRaw: '0', decimals });
      } else if (!this.splTokenMap.has(source)) {
        this.splTokenMap.set(source, {
          mint: mint || TOKENS.SOL,
          amount: 0,
          amountRaw: '0',
          decimals: decimals || 9,
        });
      }
    }
 
    if (destination) {
      if (this.splTokenMap.has(destination) && mint && decimals) {
        this.splTokenMap.set(destination, { mint, amount: 0, amountRaw: '0', decimals });
      } else IEif (!this.splTokenMap.has(destination)) {
        this.splTokenMap.set(destination, {
          mint: mint || TOKENS.SOL,
          amount: 0,
          amountRaw: '0',
          decimals: decimals || 9,
        });
      }
    }
 
    Iif (mint && decimals && !this.splDecimalsMap.has(mint)) {
      this.splDecimalsMap.set(mint, decimals);
    }
  }
 
  /**
   * Extract token info from parsed transfer instruction
   */
  private extractFromParsedTransfer(ix: any) {
    Iif (!ix.parsed || !ix.program) return;
    Iif (ix.programId != TOKEN_PROGRAM_ID && ix.programId != TOKEN_2022_PROGRAM_ID) return;
 
    const { source, destination, mint, decimals } = ix.parsed?.info || {};
    Iif (!source && !destination) return;
 
    this.setTokenInfo(source, destination, mint, decimals);
  }
 
  /**
   * Extract token info from compiled transfer instruction
   */
  private extractFromCompiledTransfer(ix: any) {
    const decoded = getInstructionData(ix);
    Iif (!decoded) return;
    const programId = this.accountKeys[ix.programIdIndex];
    if (programId != TOKEN_PROGRAM_ID && programId != TOKEN_2022_PROGRAM_ID) return;
 
    let source, destination, mint, decimals;
    // const amount = decoded.readBigUInt64LE(1);
    const accounts = ix.accounts as number[];
    if (!accounts) return;
    switch (decoded[0]) {
      case SPL_TOKEN_INSTRUCTION_TYPES.Transfer:
        Iif (accounts.length < 3) return;
        [source, destination] = [this.accountKeys[accounts[0]], this.accountKeys[accounts[1]]]; // source, destination,amount, authority
        break;
      case SPL_TOKEN_INSTRUCTION_TYPES.TransferChecked:
        Iif (accounts.length < 4) return;
        [source, mint, destination] = [
          this.accountKeys[accounts[0]],
          this.accountKeys[accounts[1]],
          this.accountKeys[accounts[2]],
        ]; // source, mint, destination, authority,amount,decimals
        decimals = decoded.readUint8(9);
        break;
      case SPL_TOKEN_INSTRUCTION_TYPES.InitializeMint:
        Iif (accounts.length < 2) return;
        [mint, destination] = [this.accountKeys[accounts[0]], this.accountKeys[accounts[1]]]; // mint, decimals, authority,freezeAuthority
        break;
      case SPL_TOKEN_INSTRUCTION_TYPES.MintTo:
        Iif (accounts.length < 2) return;
        [mint, destination] = [this.accountKeys[accounts[0]], this.accountKeys[accounts[1]]]; // mint, destination, authority, amount
        break;
      case SPL_TOKEN_INSTRUCTION_TYPES.MintToChecked:
        Iif (accounts.length < 3) return;
        [mint, destination] = [this.accountKeys[accounts[0]], this.accountKeys[accounts[1]]]; // mint, destination, authority, amount,decimals
        decimals = decoded.readUint8(9);
        break;
      case SPL_TOKEN_INSTRUCTION_TYPES.Burn:
        Iif (accounts.length < 2) return;
        [source, mint] = [this.accountKeys[accounts[0]], this.accountKeys[accounts[1]]]; // account, mint, authority, amount
        break;
      case SPL_TOKEN_INSTRUCTION_TYPES.BurnChecked:
        Iif (accounts.length < 3) return;
        [source, mint] = [this.accountKeys[accounts[0]], this.accountKeys[accounts[1]]]; // account, mint, authority, amount,decimals
        decimals = decoded.readUint8(9);
        break;
      case SPL_TOKEN_INSTRUCTION_TYPES.CloseAccount:
        Iif (accounts.length < 3) return;
        [source, destination] = [this.accountKeys[accounts[0]], this.accountKeys[accounts[1]]]; // account, destination, authority
        break;
    }
    this.setTokenInfo(source, destination, mint, decimals);
  }
}