|
| 1 | +import { keccak256 } from "viem"; |
| 2 | +import idl from "../abi/input_settler_escrow.json"; |
| 3 | +import { SOLANA_INPUT_SETTLER_ESCROW, SOLANA_POLYMER_ORACLE } from "../config"; |
| 4 | +import type { MandateOutput, StandardSolana } from "@lifi/intent"; |
| 5 | +import type { SignerWalletAdapter } from "@solana/wallet-adapter-base"; |
| 6 | +import type { Connection } from "@solana/web3.js"; |
| 7 | + |
| 8 | +const SOLANA_CONFIRMATION_TIMEOUT_MS = 60_000; |
| 9 | + |
| 10 | +/** Convert a 0x-prefixed hex string (32 bytes) to a number[] */ |
| 11 | +function hexToBytes32(hex: `0x${string}`): number[] { |
| 12 | + return Array.from(Buffer.from(hex.slice(2), "hex")); |
| 13 | +} |
| 14 | + |
| 15 | +/** Convert a bigint to a 32-byte big-endian number[] */ |
| 16 | +function bigintToBeBytes32(n: bigint): number[] { |
| 17 | + return Array.from(Buffer.from(n.toString(16).padStart(64, "0"), "hex")); |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Open a Solana→EVM intent by calling input_settler_escrow.open() on Solana devnet. |
| 22 | + * |
| 23 | + * @param order StandardSolana from @lifi/intent |
| 24 | + * @param solanaPublicKey Base58-encoded Solana wallet public key (becomes order.user) |
| 25 | + * @param walletAdapter Connected Solana wallet adapter (Phantom, Solflare, …) |
| 26 | + * @param connection Solana Connection instance |
| 27 | + * @returns Solana transaction signature string |
| 28 | + */ |
| 29 | +export async function openSolanaEscrow(params: { |
| 30 | + order: StandardSolana; |
| 31 | + solanaPublicKey: string; |
| 32 | + walletAdapter: SignerWalletAdapter; |
| 33 | + connection: Connection; |
| 34 | +}): Promise<string> { |
| 35 | + const { order, solanaPublicKey, walletAdapter, connection } = params; |
| 36 | + |
| 37 | + if (!order.inputs.length) throw new Error("StandardSolana order has no inputs"); |
| 38 | + |
| 39 | + // Dynamic imports to avoid CJS/ESM bundling issues with Rollup |
| 40 | + const { AnchorProvider, BN, Program } = await import("@coral-xyz/anchor"); |
| 41 | + const { PublicKey, SystemProgram } = await import("@solana/web3.js"); |
| 42 | + const { ASSOCIATED_TOKEN_PROGRAM_ID, TOKEN_PROGRAM_ID, getAssociatedTokenAddressSync } = |
| 43 | + await import("@solana/spl-token"); |
| 44 | + |
| 45 | + const userPubkey = new PublicKey(solanaPublicKey); |
| 46 | + const inputSettlerProgramId = new PublicKey(SOLANA_INPUT_SETTLER_ESCROW); |
| 47 | + const polymerProgramId = new PublicKey(SOLANA_POLYMER_ORACLE); |
| 48 | + |
| 49 | + // Wrap the wallet adapter as an Anchor-compatible wallet. |
| 50 | + // Cast through any so Transaction/VersionedTransaction generics align with Anchor's expectations. |
| 51 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 52 | + const anchorWallet = { |
| 53 | + publicKey: userPubkey, |
| 54 | + signTransaction: (tx: any) => walletAdapter.signTransaction(tx), |
| 55 | + signAllTransactions: (txs: any[]) => walletAdapter.signAllTransactions(txs) |
| 56 | + }; |
| 57 | + |
| 58 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 59 | + const typedIdl = idl as any; |
| 60 | + const provider = new AnchorProvider(connection as any, anchorWallet as any, { |
| 61 | + commitment: "confirmed" |
| 62 | + }); |
| 63 | + // Program converts the IDL to camelCase internally; its coder uses camelCase field names. |
| 64 | + // A standalone BorshCoder(rawIdl) would use snake_case names and fail to encode camelCase objects. |
| 65 | + const program = new Program(typedIdl, provider); |
| 66 | + |
| 67 | + // Derive polymer oracle PDA (seed: "polymer", program: SOLANA_POLYMER_ORACLE) |
| 68 | + const [polymerOraclePda] = PublicKey.findProgramAddressSync( |
| 69 | + [Buffer.from("polymer")], |
| 70 | + polymerProgramId |
| 71 | + ); |
| 72 | + |
| 73 | + // Derive input settler escrow PDA (seed: "input_settler_escrow", program: SOLANA_INPUT_SETTLER_ESCROW) |
| 74 | + const [inputSettlerEscrowPda] = PublicKey.findProgramAddressSync( |
| 75 | + [Buffer.from("input_settler_escrow")], |
| 76 | + inputSettlerProgramId |
| 77 | + ); |
| 78 | + |
| 79 | + // Extract input token from StandardSolana. |
| 80 | + // Solana token IDs are full 32-byte public keys stored as bigint — do NOT use idToToken() |
| 81 | + // which strips the first 12 bytes (EVM-only helper that returns 20-byte addresses). |
| 82 | + const tokenIdHex = order.inputs[0][0].toString(16).padStart(64, "0"); |
| 83 | + const inputMint = new PublicKey(Buffer.from(tokenIdHex, "hex")); |
| 84 | + const inputAmount = new BN(order.inputs[0][1].toString()); |
| 85 | + |
| 86 | + // Build Anchor-format order. |
| 87 | + // Field names are camelCase here; Anchor's BorshCoder maps them to the IDL's snake_case names. |
| 88 | + const anchorOrder = { |
| 89 | + user: userPubkey, |
| 90 | + nonce: new BN(order.nonce.toString()), |
| 91 | + originChainId: new BN(order.originChainId.toString()), |
| 92 | + expires: order.expires, |
| 93 | + fillDeadline: order.fillDeadline, |
| 94 | + inputOracle: polymerOraclePda, |
| 95 | + input: { token: inputMint, amount: inputAmount }, |
| 96 | + outputs: order.outputs.map((o: MandateOutput) => ({ |
| 97 | + oracle: hexToBytes32(o.oracle), |
| 98 | + settler: hexToBytes32(o.settler), |
| 99 | + chainId: bigintToBeBytes32(o.chainId), |
| 100 | + token: hexToBytes32(o.token), |
| 101 | + amount: bigintToBeBytes32(o.amount), |
| 102 | + recipient: hexToBytes32(o.recipient), |
| 103 | + callbackData: |
| 104 | + o.callbackData === "0x" ? Buffer.alloc(0) : Buffer.from(o.callbackData.slice(2), "hex"), |
| 105 | + context: o.context === "0x" ? Buffer.alloc(0) : Buffer.from(o.context.slice(2), "hex") |
| 106 | + })) |
| 107 | + }; |
| 108 | + |
| 109 | + // Compute orderId = keccak256(borsh(anchorOrder)) — mirrors Rust's StandardOrder::derive_id(). |
| 110 | + // Anchor's BorshCoder normalizes IDL type names to camelCase internally, so even |
| 111 | + // though the IDL defines this as "StandardOrder", the registry key is "standardOrder". |
| 112 | + let encoded: Uint8Array; |
| 113 | + try { |
| 114 | + encoded = program.coder.types.encode("standardOrder", anchorOrder); |
| 115 | + } catch (e) { |
| 116 | + const message = e instanceof Error ? e.message : String(e); |
| 117 | + throw new Error(`Borsh encoding failed for standardOrder: ${message}`); |
| 118 | + } |
| 119 | + |
| 120 | + const orderIdHex = keccak256(encoded); |
| 121 | + const orderId = Buffer.from(orderIdHex.slice(2), "hex"); |
| 122 | + |
| 123 | + // Derive orderContext PDA (seeds: ["order_context", orderId], program: SOLANA_INPUT_SETTLER_ESCROW) |
| 124 | + const [orderContext] = PublicKey.findProgramAddressSync( |
| 125 | + [Buffer.from("order_context"), orderId], |
| 126 | + inputSettlerProgramId |
| 127 | + ); |
| 128 | + |
| 129 | + // ATA for the user (must already exist — user has a balance) |
| 130 | + const userTokenAccount = getAssociatedTokenAddressSync(inputMint, userPubkey, false); |
| 131 | + // ATA for the order PDA (created by the Anchor instruction) |
| 132 | + const orderPdaTokenAccount = getAssociatedTokenAddressSync(inputMint, orderContext, true); |
| 133 | + |
| 134 | + // Call input_settler_escrow.open(order) with a confirmation timeout. |
| 135 | + const signature = await Promise.race([ |
| 136 | + program.methods |
| 137 | + .open(anchorOrder) |
| 138 | + .accounts({ |
| 139 | + user: userPubkey, |
| 140 | + inputSettlerEscrow: inputSettlerEscrowPda, |
| 141 | + userTokenAccount, |
| 142 | + orderContext, |
| 143 | + orderPdaTokenAccount, |
| 144 | + mint: inputMint, |
| 145 | + tokenProgram: TOKEN_PROGRAM_ID, |
| 146 | + associatedTokenProgram: ASSOCIATED_TOKEN_PROGRAM_ID, |
| 147 | + systemProgram: SystemProgram.programId |
| 148 | + }) |
| 149 | + .rpc({ commitment: "confirmed" }), |
| 150 | + new Promise<never>((_, reject) => |
| 151 | + setTimeout( |
| 152 | + () => |
| 153 | + reject( |
| 154 | + new Error( |
| 155 | + `Solana transaction timed out after ${SOLANA_CONFIRMATION_TIMEOUT_MS / 1000}s` |
| 156 | + ) |
| 157 | + ), |
| 158 | + SOLANA_CONFIRMATION_TIMEOUT_MS |
| 159 | + ) |
| 160 | + ) |
| 161 | + ]); |
| 162 | + |
| 163 | + return signature; |
| 164 | +} |
0 commit comments