|
| 1 | +import { |
| 2 | + CompiledInstruction, |
| 3 | + Message, |
| 4 | + MessageCompiledInstruction, |
| 5 | + MessageV0, |
| 6 | +} from '@solana/web3.js'; |
| 7 | +import { decode } from 'bs58'; |
| 8 | +import { Connection } from '@solana/web3.js'; |
| 9 | +import { RPCS_BY_CHAIN } from '@certusone/wormhole-sdk/lib/cjs/relayer'; |
| 10 | +import { CONTRACTS } from '@certusone/wormhole-sdk'; |
| 11 | + |
| 12 | +export const isLegacyMessage = (message: Message | MessageV0): message is Message => { |
| 13 | + return message.version === 'legacy'; |
| 14 | +}; |
| 15 | + |
| 16 | +export const normalizeCompileInstruction = ( |
| 17 | + instruction: CompiledInstruction | MessageCompiledInstruction |
| 18 | +): MessageCompiledInstruction => { |
| 19 | + if ('accounts' in instruction) { |
| 20 | + return { |
| 21 | + accountKeyIndexes: instruction.accounts, |
| 22 | + data: decode(instruction.data), |
| 23 | + programIdIndex: instruction.programIdIndex, |
| 24 | + }; |
| 25 | + } else { |
| 26 | + return instruction; |
| 27 | + } |
| 28 | +}; |
| 29 | + |
| 30 | +export async function convertSolanaTxToAcct(txHash: string): Promise<string> { |
| 31 | + const POST_MESSAGE_IX_ID = 0x01; |
| 32 | + const connection = new Connection(RPCS_BY_CHAIN.MAINNET.solana!, 'finalized'); |
| 33 | + const txs = await connection.getTransactions([txHash], { |
| 34 | + maxSupportedTransactionVersion: 0, |
| 35 | + }); |
| 36 | + for (const tx of txs) { |
| 37 | + if (!tx) { |
| 38 | + continue; |
| 39 | + } |
| 40 | + const message = tx.transaction.message; |
| 41 | + const accountKeys = isLegacyMessage(message) ? message.accountKeys : message.staticAccountKeys; |
| 42 | + const programIdIndex = accountKeys.findIndex( |
| 43 | + (i) => i.toBase58() === CONTRACTS.MAINNET.solana.core |
| 44 | + ); |
| 45 | + const instructions = message.compiledInstructions; |
| 46 | + const innerInstructions = |
| 47 | + tx.meta?.innerInstructions?.flatMap((i) => i.instructions.map(normalizeCompileInstruction)) || |
| 48 | + []; |
| 49 | + const whInstructions = innerInstructions |
| 50 | + .concat(instructions) |
| 51 | + .filter((i) => i.programIdIndex === programIdIndex); |
| 52 | + for (const instruction of whInstructions) { |
| 53 | + // skip if not postMessage instruction |
| 54 | + const instructionId = instruction.data; |
| 55 | + if (instructionId[0] !== POST_MESSAGE_IX_ID) continue; |
| 56 | + |
| 57 | + return accountKeys[instruction.accountKeyIndexes[1]].toBase58(); |
| 58 | + } |
| 59 | + } |
| 60 | + return ''; |
| 61 | +} |
0 commit comments