@provablehq/aleo-bridge-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/connections/resolve.ts","../src/protocols/hyperlane/aleo.ts","../src/utils/hyperlane.ts","../src/utils/units.ts","../src/protocols/hyperlane/evm.ts","../src/solana/extractHyperlaneMessageId.ts","../src/protocols/hyperlane/solanaMetadata.ts","../src/protocols/hyperlane/solana.ts","../src/protocols/xreserve/aleoToEvm.ts","../src/protocols/xreserve/evmToAleo.ts","../src/actions/internal/resolveTransferRoute.ts","../src/actions/createBridgeCheckpoint.ts","../src/actions/internal/readDestinationBalance.ts","../src/actions/execute.ts","../src/actions/prepare.ts","../src/actions/quote.ts","../src/actions/complete.ts","../src/actions/getStatus.ts","../src/utils/hyperlaneDelivery.ts","../src/utils/xreserveDelivery.ts","../src/actions/internal/toBridgeProgress.ts","../src/actions/recover.ts","../src/actions/resume.ts","../src/actions/wait.ts","../src/actions/internal/aleoPrivacy.ts","../src/actions/shield.ts","../src/actions/unshield.ts","../src/clients/decorators/bridge.ts","../src/registry/default.ts","../src/registry/validate.ts","../src/clients/createBridgeClient.ts","../src/connections/evm.ts","../src/connections/aleo.ts","../src/protocols/index.ts","../src/builders/buildXReserveBurnCall.ts","../src/builders/buildAleoHyperlaneTransferRemoteCall.ts"],"sourcesContent":["import { BridgeError } from '../errors/bridgeErrors.js'\nimport type { BridgeRegistry } from '../types/protocol.js'\nimport type { AleoClient } from './aleo.js'\nimport type { AleoWalletClient } from '../types/aleo.js'\nimport type { EvmClient, EvmWalletClient } from './evm.js'\nimport type { SolanaClient, SolanaWalletClient } from './solana.js'\n\n/** Represents the EVM, Solana, or Aleo network access stored for one registry chain. */\nexport type BridgeChainClient = EvmClient | SolanaClient | AleoClient\n\n/** Stores network and optional wallet access under the same chain identifiers used by routes. */\nexport type BridgeChainClients = Readonly<Record<string, BridgeChainClient>>\n\nfunction resolve(\n registry: BridgeRegistry,\n clients: BridgeChainClients,\n chainId: string,\n family: BridgeChainClient['family'],\n): BridgeChainClient {\n // Check both the registry declaration and the client discriminator. A client\n // stored under the wrong key must fail before any RPC request or signature.\n const chain = registry.chains.find((entry) => entry.id === chainId)\n if (!chain) throw new BridgeError(`Unknown bridge chain: \"${chainId}\"`)\n const client = clients[chainId]\n if (!client) throw new BridgeError(`No client is configured for chain \"${chainId}\"`)\n if (client.family !== chain.family || client.family !== family) {\n throw new BridgeError(`Client \"${chainId}\" has family \"${client.family}\"; the registry declares \"${chain.family}\"`)\n }\n return client\n}\n\n/** Returns EVM network access for a registry chain without requiring wallet authorization. */\nexport function requireEvmClient(registry: BridgeRegistry, clients: BridgeChainClients, chainId: string): EvmClient {\n return resolve(registry, clients, chainId, 'evm') as EvmClient\n}\n\n/** Returns EVM network and wallet access, or fails before an action can request a signature. */\nexport function requireEvmClientWithWallet(registry: BridgeRegistry, clients: BridgeChainClients, chainId: string, action: string): EvmClient & { walletClient: EvmWalletClient } {\n const client = requireEvmClient(registry, clients, chainId)\n if (!client.walletClient) throw new BridgeError(`EVM wallet client is required to ${action} on chain \"${chainId}\"`)\n return client as EvmClient & { walletClient: EvmWalletClient }\n}\n\n/** Returns Solana network access for a registry chain without requiring wallet authorization. */\nexport function requireSolanaClient(registry: BridgeRegistry, clients: BridgeChainClients, chainId: string): SolanaClient {\n return resolve(registry, clients, chainId, 'solana') as SolanaClient\n}\n\n/** Returns Solana network and wallet access, or fails before an action can request a signature. */\nexport function requireSolanaClientWithWallet(registry: BridgeRegistry, clients: BridgeChainClients, chainId: string, action: string): SolanaClient & { walletClient: SolanaWalletClient } {\n const client = requireSolanaClient(registry, clients, chainId)\n if (!client.walletClient) throw new BridgeError(`Solana wallet client is required to ${action} on chain \"${chainId}\"`)\n return client as SolanaClient & { walletClient: SolanaWalletClient }\n}\n\n/** Returns Aleo network access for a registry chain without requiring wallet authorization. */\nexport function requireAleoClient(registry: BridgeRegistry, clients: BridgeChainClients, chainId: string): AleoClient {\n return resolve(registry, clients, chainId, 'aleo') as AleoClient\n}\n\n/** Returns Aleo network and wallet access, or fails before an action can request proving or a signature. */\nexport function requireAleoClientWithWallet(registry: BridgeRegistry, clients: BridgeChainClients, chainId: string, action: string): AleoClient & { walletClient: AleoWalletClient } {\n const client = requireAleoClient(registry, clients, chainId)\n if (!client.walletClient) throw new BridgeError(`Aleo wallet client is required to ${action} on chain \"${chainId}\"`)\n return client as AleoClient & { walletClient: AleoWalletClient }\n}\n","import { parsePlaintextValue, readContract, type Client } from '@provablehq/veil-core'\nimport { BridgeError } from '../../errors/bridgeErrors.js'\nimport type {\n AleoWalletClient,\n AleoHyperlaneGasQuote,\n AleoHyperlaneTransferRemoteCall,\n AleoHyperlaneTransferRemoteExecution,\n ExecuteAleoHyperlaneTransferRemoteParameters,\n QuoteAleoHyperlaneGasPaymentParameters,\n} from '../../types/aleo.js'\nimport type { BridgeRegistry, BridgeReceipt, ProtocolBridgeRoute } from '../../types/protocol.js'\nimport {\n evmAddressToAleoHyperlaneRecipient,\n solanaAddressToAleoHyperlaneRecipient,\n} from '../../utils/hyperlane.js'\nimport { parseDecimalAmount } from '../../utils/units.js'\n\nconst MAX_U64 = (1n << 64n) - 1n\n// Divisor and zero-gas-limit fallback fixed by hyp_hook_manager.aleo post_dispatch.\nconst GAS_QUOTE_SCALE = 10_000_000_000n\nconst ZERO_GAS_LIMIT_FALLBACK = 50_000n\n\nconst PLACEHOLDER_FIELDS = [\n 'aleoTokenType',\n 'aleoTokenOwner',\n 'aleoIsm',\n 'aleoHook',\n 'aleoTokenId',\n 'aleoMailboxDefaultHook',\n 'aleoMailboxRequiredHook',\n 'aleoRemoteRouterRecipient',\n 'aleoRemoteRouterGas',\n 'aleoRecipient',\n 'aleoAllowanceSpender0',\n 'aleoAllowanceAmount0',\n 'aleoAllowanceSpender1',\n 'aleoAllowanceAmount1',\n 'aleoAllowanceSpender2',\n 'aleoAllowanceAmount2',\n 'aleoAllowanceSpender3',\n 'aleoAllowanceAmount3',\n] as const\n\nconst APP_METADATA_FIELDS = new Set<string>([\n 'aleoTokenType',\n 'aleoTokenOwner',\n 'aleoIsm',\n 'aleoHook',\n 'aleoTokenId',\n])\n\nconst MAILBOX_STATE_FIELDS = new Set<string>([\n 'aleoMailboxDefaultHook',\n 'aleoMailboxRequiredHook',\n])\n\nconst REMOTE_ROUTER_FIELDS = new Set<string>([\n 'aleoRemoteRouterRecipient',\n 'aleoRemoteRouterGas',\n])\n\nconst ALLOWANCE_SPENDER_FIELDS = new Set<string>([\n 'aleoAllowanceSpender0',\n 'aleoAllowanceSpender1',\n 'aleoAllowanceSpender2',\n 'aleoAllowanceSpender3',\n])\n\nconst UNUSED_ALLOWANCE_AMOUNT_FIELDS = new Set<string>([\n 'aleoAllowanceAmount1',\n 'aleoAllowanceAmount2',\n 'aleoAllowanceAmount3',\n])\n\nfunction metadataString(route: ProtocolBridgeRoute, key: string): string {\n const value = route.metadata?.[key]\n if (typeof value !== 'string' || value.length === 0) throw new BridgeError(`Hyperlane route metadata ${key} is missing: ${route.id}`)\n return value\n}\n\nfunction metadataNumber(route: ProtocolBridgeRoute, key: string): number {\n const value = route.metadata?.[key]\n if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) throw new BridgeError(`Hyperlane route metadata ${key} is invalid: ${route.id}`)\n return value\n}\n\nfunction optionalMetadataNumber(route: ProtocolBridgeRoute, key: string, fallback: number): number {\n return route.metadata?.[key] == null ? fallback : metadataNumber(route, key)\n}\n\nfunction validatedRoute(registry: BridgeRegistry, params: ExecuteAleoHyperlaneTransferRemoteParameters) {\n const { plan } = params\n if (plan.protocol !== 'hyperlane' || plan.route.protocol !== 'hyperlane') throw new BridgeError('Aleo transfer_remote requires a Hyperlane transfer plan')\n if (plan.registryVersion !== registry.version) throw new BridgeError(`Transfer plan uses registry ${plan.registryVersion}; expected ${registry.version}`)\n // Reload the deployed programs and remote-domain configuration from the\n // current reviewed registry before constructing wallet inputs.\n const route = registry.routes.find((entry) => entry.id === plan.route.id)\n if (!route || route.protocol !== 'hyperlane') throw new BridgeError(`Hyperlane route is not configured: ${plan.route.id}`)\n if (route.sourceAssetId !== plan.sourceAsset.id || route.destinationAssetId !== plan.destinationAsset.id) throw new BridgeError(`Transfer plan assets do not match configured route: ${route.id}`)\n const sourceChain = registry.chains.find((chain) => chain.id === plan.sourceAsset.chainId)\n if (sourceChain?.family !== 'aleo') throw new BridgeError('transfer_remote requires an Aleo source asset')\n const destinationChain = registry.chains.find((chain) => chain.id === plan.destinationAsset.chainId)\n if (!destinationChain) throw new BridgeError(`Destination chain is not configured: ${plan.destinationAsset.chainId}`)\n const program = metadataString(route, 'aleoRouterProgram')\n if (!program.endsWith('.aleo')) throw new BridgeError(`Aleo Warp Route program is invalid: ${route.id}`)\n return { route, program, destinationChain }\n}\n\nfunction allowance(route: ProtocolBridgeRoute, index: number, amountOverride?: string): string {\n const amount = amountOverride ?? metadataString(route, `aleoAllowanceAmount${index}`)\n return `{ spender: ${metadataString(route, `aleoAllowanceSpender${index}`)}, amount: ${amount}u64 }`\n}\n\nfunction gasConfigBigint(config: Record<string, unknown>, field: string, routeId: string): bigint {\n const value = config[field]\n if (typeof value !== 'bigint' || value < 0n) throw new BridgeError(`Hyperlane gas configuration field ${field} is invalid: ${routeId}`)\n return value\n}\n\n/**\n * Calculates the relayer payment required for a Hyperlane transfer leaving Aleo.\n *\n * The payment covers destination-chain delivery rather than the Aleo\n * transaction fee. It is calculated from the gas oracle values enforced by\n * the bridge program at finalization:\n * `(gas_limit + gas_overhead) * gas_price * exchange_rate / 10^10`.\n * Quote shortly before submission because a stale value causes the source\n * transaction to fail. The action reads Aleo but does not request a signature\n * or move funds.\n *\n * @param registry Supported assets and reviewed Hyperlane deployments.\n * @param client Aleo network access used to read the current destination gas configuration.\n * @param params Aleo-origin route whose destination delivery payment is calculated.\n * @returns Current gas values and the exact relayer payment in Aleo microcredits (u64).\n * @throws BridgeError When the route is unavailable, the on-chain gas configuration is missing or unpriced, or the payment cannot fit in a positive u64.\n *\n * @example\n * const result = await quote(registry, client, { routeId: plan.route.id })\n */\nexport async function quote(\n registry: BridgeRegistry,\n client: Client,\n params: QuoteAleoHyperlaneGasPaymentParameters,\n): Promise<AleoHyperlaneGasQuote> {\n // The route tells the hook manager which IGP and destination-domain tuple is\n // authoritative for this transfer.\n const route = registry.routes.find((entry) => entry.id === params.routeId)\n if (!route || route.protocol !== 'hyperlane') throw new BridgeError(`Hyperlane route is not configured: ${params.routeId}`)\n const sourceAsset = registry.assets.find((asset) => asset.id === route.sourceAssetId)\n const sourceChain = registry.chains.find((chain) => chain.id === sourceAsset?.chainId)\n if (sourceChain?.family !== 'aleo') throw new BridgeError(`Hyperlane gas quotes require an Aleo source asset: ${params.routeId}`)\n const hookManager = metadataString(route, 'aleoHookManagerProgram')\n const igp = metadataString(route, 'aleoMailboxDefaultHook')\n const destination = metadataNumber(route, 'aleoDestinationDomain')\n const gasLimitMetadata = BigInt(metadataString(route, 'aleoRemoteRouterGas'))\n // Read the same mapping entry consumed by hyp_hook_manager.aleo during\n // finalization; an off-chain service quote would not be authoritative.\n const literal = await readContract(client, {\n programId: hookManager,\n mapping: 'destination_gas_configs',\n key: `{ igp: ${igp}, destination: ${destination}u32 }`,\n })\n if (literal == null) throw new BridgeError(`Hyperlane destination gas configuration is missing on chain: ${params.routeId}`)\n const config = parsePlaintextValue(literal)\n if (typeof config !== 'object' || Array.isArray(config)) throw new BridgeError(`Hyperlane destination gas configuration is malformed: ${params.routeId}`)\n // A zero exchange rate or gas price means the destination is configured but\n // cannot currently be priced, so submission would be unsafe.\n const gasOverhead = gasConfigBigint(config, 'gas_overhead', route.id)\n const exchangeRate = gasConfigBigint(config, 'exchange_rate', route.id)\n const gasPrice = gasConfigBigint(config, 'gas_price', route.id)\n if (exchangeRate === 0n || gasPrice === 0n) throw new BridgeError(`Hyperlane destination gas configuration is unpriced: ${params.routeId}`)\n const gasLimit = gasLimitMetadata === 0n ? ZERO_GAS_LIMIT_FALLBACK : gasLimitMetadata\n // Preserve integer operation order and truncation so every language port\n // reproduces the exact u64 amount checked by the Aleo program.\n const paymentMicrocredits = ((gasLimit + gasOverhead) * gasPrice * exchangeRate) / GAS_QUOTE_SCALE\n if (paymentMicrocredits <= 0n || paymentMicrocredits > MAX_U64) {\n throw new BridgeError(`Hyperlane hook payment does not fit a positive u64: ${paymentMicrocredits}`)\n }\n return {\n routeId: route.id,\n gasLimit,\n gasOverhead,\n gasPrice,\n exchangeRate,\n paymentMicrocredits,\n // A public quote cannot authorize the program execution needed to price\n // its Aleo network fee. Keep the absent total explicit so callers do not\n // mistake the Hyperlane hook payment for their complete balance need.\n executionFeeMicrocredits: null,\n totalMicrocredits: null,\n }\n}\n\n/**\n * Builds the Aleo program call that commits an asset to a Hyperlane transfer.\n *\n * The result lets an application inspect the program, transition, amount, remote\n * recipient, and relayer allowance before a wallet is involved. It does not\n * contact Aleo, request a signature, or move funds. Routes still under review\n * return named placeholder fields and MUST NOT be submitted.\n *\n * @param registry Supported assets and reviewed Hyperlane deployments.\n * @param params Route, assets, amount, recipient, authorization mode, and optional current relayer payment.\n * @returns Exact Aleo program, transition, ordered inputs, atomic amount, and any configuration that is not ready for submission.\n * @throws BridgeError When the transfer conflicts with the deployment or the relayer payment cannot fit in a positive u64.\n *\n * @example\n * const call = buildTransferRemoteCall(registry, { plan })\n */\nexport function buildTransferRemoteCall(\n registry: BridgeRegistry,\n params: ExecuteAleoHyperlaneTransferRemoteParameters,\n): AleoHyperlaneTransferRemoteCall {\n if (params.mode != null && params.mode !== 'caller' && params.mode !== 'signer') {\n throw new BridgeError(`Unsupported Aleo Hyperlane transfer mode: ${String(params.mode)}`)\n }\n const gasPayment = params.gasPaymentMicrocredits\n if (gasPayment != null && (gasPayment <= 0n || gasPayment > MAX_U64)) {\n throw new BridgeError(`gasPaymentMicrocredits must be a positive u64: ${gasPayment}`)\n }\n const { route, program, destinationChain } = validatedRoute(registry, params)\n const amountAtomic = parseDecimalAmount(params.plan.amountIn, params.plan.sourceAsset.decimals)\n const destination = metadataNumber(route, 'aleoDestinationDomain')\n const localDecimals = optionalMetadataNumber(route, 'aleoLocalDecimals', params.plan.sourceAsset.decimals)\n const remoteDecimals = optionalMetadataNumber(route, 'aleoRemoteDecimals', params.plan.destinationAsset.decimals)\n // Freeze the reviewed route into the three Aleo structs the Warp Route checks:\n // token configuration, Mailbox hooks, and the enrolled remote router.\n const appMetadata = `{ token_type: ${metadataString(route, 'aleoTokenType')}u8, token_owner: ${metadataString(route, 'aleoTokenOwner')}, ism: ${metadataString(route, 'aleoIsm')}, hook: ${metadataString(route, 'aleoHook')}, token_id: ${metadataString(route, 'aleoTokenId')}, local_decimals: ${localDecimals}u8, remote_decimals: ${remoteDecimals}u8 }`\n const mailboxState = `{ default_hook: ${metadataString(route, 'aleoMailboxDefaultHook')}, required_hook: ${metadataString(route, 'aleoMailboxRequiredHook')} }`\n const remoteRouter = `{ domain: ${destination}u32, recipient: ${metadataString(route, 'aleoRemoteRouterRecipient')}, gas: ${metadataString(route, 'aleoRemoteRouterGas')}u128 }`\n // Aleo represents a 32-byte remote recipient as two little-endian u128 limbs.\n // EVM addresses are left-padded to 32 bytes; Solana public keys already occupy 32.\n const recipientLimbs = destinationChain.family === 'evm'\n ? evmAddressToAleoHyperlaneRecipient(params.plan.recipient)\n : destinationChain.family === 'solana'\n ? solanaAddressToAleoHyperlaneRecipient(params.plan.recipient)\n : undefined\n const recipient = recipientLimbs\n ? `[${recipientLimbs[0]}u128, ${recipientLimbs[1]}u128]`\n : metadataString(route, 'aleoRecipient')\n // The ABI always carries four allowances. Slot 0 pays the live IGP quote;\n // unused slots retain their reviewed zero-value configuration.\n const allowances = `[${[0, 1, 2, 3].map((index) => allowance(route, index, index === 0 ? gasPayment?.toString() : undefined)).join(', ')}]`\n const usesPlaceholderConfiguration = route.metadata?.aleoPlaceholderConfiguration === true\n // Verification flags record which groups were checked against live Aleo data.\n // Report every unverified field so inspection tools cannot mistake a partial\n // deployment snapshot for an executable transaction.\n let placeholderFields = route.metadata?.aleoAppMetadataVerified === true\n ? PLACEHOLDER_FIELDS.filter((field) => !APP_METADATA_FIELDS.has(field))\n : PLACEHOLDER_FIELDS\n if (route.metadata?.aleoMailboxStateVerified === true) {\n placeholderFields = placeholderFields.filter((field) => !MAILBOX_STATE_FIELDS.has(field))\n }\n if (route.metadata?.aleoRemoteRouterVerified === true) {\n placeholderFields = placeholderFields.filter((field) => !REMOTE_ROUTER_FIELDS.has(field))\n }\n if (route.metadata?.aleoAllowanceSpendersVerified === true) {\n placeholderFields = placeholderFields.filter((field) => !ALLOWANCE_SPENDER_FIELDS.has(field))\n }\n if (route.metadata?.aleoUnusedAllowancesVerified === true) {\n placeholderFields = placeholderFields.filter((field) => !UNUSED_ALLOWANCE_AMOUNT_FIELDS.has(field))\n }\n if (recipientLimbs) {\n placeholderFields = placeholderFields.filter((field) => field !== 'aleoRecipient')\n }\n if (gasPayment != null) {\n placeholderFields = placeholderFields.filter((field) => field !== 'aleoAllowanceAmount0')\n }\n const functionName = params.mode === 'signer' ? 'transfer_remote_as_signer' : 'transfer_remote'\n\n return {\n routeId: route.id,\n program,\n function: functionName,\n inputs: [\n appMetadata,\n mailboxState,\n remoteRouter,\n `${destination}u32`,\n recipient,\n `${amountAtomic}u128`,\n allowances,\n ],\n amountAtomic,\n usesPlaceholderConfiguration,\n placeholderFields: usesPlaceholderConfiguration\n ? placeholderFields\n : gasPayment == null ? ['aleoAllowanceAmount0'] : [],\n }\n}\n\n/**\n * Begins a Hyperlane transfer from Aleo by submitting its source transaction.\n *\n * The wallet proves, signs, and broadcasts the call that commits the source\n * asset. An active reviewed route and current relayer payment are required. A\n * stale payment causes the on-chain call to fail before funds move, but the Aleo\n * transaction fee may still be charged.\n *\n * @param registry Supported assets and reviewed Hyperlane deployments.\n * @param client Aleo wallet that proves, signs, and broadcasts the source transaction.\n * @param params Route, assets, amount, recipient, fee preference, current relayer payment, and recovery callbacks.\n * @returns The Aleo transaction identifier and state needed to follow destination delivery.\n * @throws BridgeError When the route is not ready, the relayer payment is absent, or wallet submission fails.\n */\nexport async function execute(\n registry: BridgeRegistry,\n client: AleoWalletClient,\n params: ExecuteAleoHyperlaneTransferRemoteParameters,\n): Promise<AleoHyperlaneTransferRemoteExecution> {\n const call = buildTransferRemoteCall(registry, params)\n // Submission is the hard safety boundary. Builders remain inspectable for\n // incomplete routes, but a wallet must never receive placeholder inputs.\n if (call.usesPlaceholderConfiguration) {\n throw new BridgeError(`Aleo Hyperlane route contains non-executable placeholder configuration: ${call.routeId}`)\n }\n const route = registry.routes.find((entry) => entry.id === call.routeId)\n if (route?.availability !== 'active') {\n throw new BridgeError(`Aleo Hyperlane route is not active: ${call.routeId}`)\n }\n if (params.gasPaymentMicrocredits == null) {\n throw new BridgeError(`Aleo Hyperlane execution requires a live hook gas payment; call quote first: ${call.routeId}`)\n }\n // `onPrepared` runs after proof construction and before broadcast, allowing\n // the caller to persist the exact immutable transaction for crash recovery.\n const transactionId = await client.executeTransaction({\n program: call.program,\n function: call.function,\n inputs: call.inputs,\n privateFee: params.privateFee ?? false,\n onProgress: async (event) => {\n await params.onProgress?.(event)\n if (event.type === 'transaction-prepared') await params.onPrepared?.(event.transaction)\n },\n })\n if (!transactionId) throw new BridgeError('Aleo wallet returned an empty Hyperlane transaction id')\n const receipt: BridgeReceipt = {\n id: transactionId,\n protocol: 'hyperlane',\n status: 'SOURCE_CONFIRMING',\n sourceTxId: transactionId,\n protocolState: { routeId: call.routeId, sourceProgram: call.program, sourceFunction: call.function },\n }\n // After broadcast, persist only the public transaction identifier needed to\n // observe Aleo acceptance and later destination delivery.\n await params.onSubmitted?.(receipt)\n return {\n transactionId,\n receipt,\n }\n}\n","import bs58 from 'bs58'\nimport { getAddress, hexToBytes, isAddress, padHex } from 'viem'\nimport { BridgeError } from '../errors/bridgeErrors.js'\n\nfunction littleEndianU128(bytes: Uint8Array): bigint {\n let value = 0n\n for (let index = 0; index < bytes.length; index++) {\n value |= BigInt(bytes[index]!) << BigInt(index * 8)\n }\n return value\n}\n\n/**\n * Encodes an Ethereum account as the two little-endian limbs used by Aleo Warp Routes.\n *\n * Validates a 20-byte EVM address, left-pads it to Hyperlane bytes32 form, and\n * interprets each 16-byte half as an Aleo `u128` without contacting either\n * chain.\n *\n * @param address Destination Ethereum account supplied by the transfer plan.\n * @returns Two unsigned 128-bit limbs in Hyperlane message order.\n * @throws BridgeError When the destination is not a valid 20-byte EVM address.\n *\n * @example\n * const recipient = evmAddressToAleoHyperlaneRecipient('0x1e196d0a7d8189054c4db744ab3340c3f1c68b19')\n */\nexport function evmAddressToAleoHyperlaneRecipient(address: string): readonly [bigint, bigint] {\n if (!isAddress(address)) throw new BridgeError(`Invalid Ethereum Hyperlane recipient: ${address}`)\n const recipient = hexToBytes(padHex(getAddress(address), { size: 32 }))\n return [\n littleEndianU128(recipient.slice(0, 16)),\n littleEndianU128(recipient.slice(16, 32)),\n ]\n}\n\n/**\n * Encodes a Solana account as the two little-endian limbs used by Aleo Warp Routes.\n *\n * Decodes a base58 account to its 32-byte public key and interprets each\n * 16-byte half as an Aleo `u128` without contacting either chain.\n *\n * @param address Destination Solana account supplied by the transfer plan.\n * @returns Two unsigned 128-bit limbs in Hyperlane message order.\n * @throws BridgeError When the destination is not a base58-encoded 32-byte account.\n *\n * @example\n * const recipient = solanaAddressToAleoHyperlaneRecipient('11111111111111111111111111111111')\n */\nexport function solanaAddressToAleoHyperlaneRecipient(address: string): readonly [bigint, bigint] {\n try {\n const recipient = bs58.decode(address)\n if (recipient.length !== 32) throw new Error('invalid public key width')\n return [\n littleEndianU128(recipient.slice(0, 16)),\n littleEndianU128(recipient.slice(16, 32)),\n ]\n } catch (cause) {\n throw new BridgeError(`Invalid Solana Hyperlane recipient: ${address}`, { cause })\n }\n}\n","import { BridgeError } from '../errors/bridgeErrors.js'\n\n/**\n * Converts a decimal amount string into the asset's atomic units.\n *\n * Protocol inputs use display decimals (`\"0.5\"` ALEO), while onchain calls\n * use atomic integers (`500000n` microcredits). String arithmetic keeps the\n * conversion exact without floating-point rounding or contacting a chain.\n *\n * @param amount Decimal amount as a string (e.g. `\"0.5\"`, `\"100\"`).\n * @param decimals The asset's display decimals (e.g. 6 for ALEO/USDC, 18 for ETH).\n * @returns The atomic amount as a bigint.\n * @throws BridgeError When the string is not a plain decimal number, or has\n * more fractional digits than the asset supports (that precision cannot be\n * represented on chain).\n *\n * @example\n * parseDecimalAmount('0.5', 6) // 500000n\n * parseDecimalAmount('100', 6) // 100000000n\n */\nexport function parseDecimalAmount(amount: string, decimals: number): bigint {\n const match = /^(\\d+)(?:\\.(\\d+))?$/.exec(amount.trim())\n if (!match) {\n throw new BridgeError(`Invalid decimal amount \"${amount}\"`)\n }\n const whole = match[1]!\n const frac = match[2] ?? ''\n if (frac.length > decimals) {\n throw new BridgeError(\n `Amount \"${amount}\" has ${frac.length} fractional digits but the asset supports ${decimals}`,\n )\n }\n return BigInt(whole + frac.padEnd(decimals, '0'))\n}\n\n/**\n * Formats a non-negative atomic amount as an exact decimal display value.\n *\n * String arithmetic removes trailing fractional zeroes without floating-point\n * rounding and does not read a balance or contact a chain.\n *\n * @param amount Atomic amount to format; MUST be non-negative.\n * @param decimals Number of fractional decimal places used by the asset.\n * @returns Canonical decimal text with no redundant trailing zeroes.\n * @throws BridgeError When the amount or decimal width is negative.\n *\n * @example\n * formatDecimalAmount(2_000_001n, 6) // '2.000001'\n */\nexport function formatDecimalAmount(amount: bigint, decimals: number): string {\n if (amount < 0n) throw new BridgeError('Atomic amount must be non-negative')\n if (!Number.isSafeInteger(decimals) || decimals < 0) {\n throw new BridgeError('Asset decimals must be a non-negative safe integer')\n }\n if (decimals === 0) return amount.toString()\n const digits = amount.toString().padStart(decimals + 1, '0')\n const whole = digits.slice(0, -decimals)\n const fraction = digits.slice(-decimals).replace(/0+$/, '')\n return fraction ? `${whole}.${fraction}` : whole\n}\n","import {\n decodeEventLog,\n decodeFunctionResult,\n encodeFunctionData,\n getAddress,\n isAddress,\n isHash,\n parseAbi,\n zeroAddress,\n type Address,\n type Hash,\n type Hex,\n} from 'viem'\nimport { BridgeError } from '../../errors/bridgeErrors.js'\nimport type { EvmClient, EvmReceipt, EvmWalletClient } from '../../connections/evm.js'\nimport type {\n EvmHyperlaneRouteMetadata,\n EvmHyperlaneTransferExecution,\n EvmHyperlaneTransferQuote,\n ExecuteEvmHyperlaneTransferParameters,\n QuoteEvmHyperlaneTransferParameters,\n} from '../../types/evm.js'\nimport type { BridgeCheckpoint, BridgeRegistry, BridgePlan, BridgeReceipt } from '../../types/protocol.js'\nimport { parseDecimalAmount } from '../../utils/units.js'\n\nconst WARP_ROUTE_ABI = parseAbi([\n 'function quoteTransferRemote(uint32 destination, bytes32 recipient, uint256 amount) view returns ((address token, uint256 amount)[] quotes)',\n 'function transferRemote(uint32 destination, bytes32 recipient, uint256 amount) payable returns (bytes32 messageId)',\n 'event SentTransferRemote(uint32 indexed destination, bytes32 indexed recipient, uint256 amount)',\n])\nconst ERC20_ABI = parseAbi([\n 'function allowance(address owner, address spender) view returns (uint256)',\n 'function approve(address spender, uint256 amount) returns (bool)',\n])\nconst DISPATCH_ID_ABI = parseAbi(['event DispatchId(bytes32 indexed messageId)'])\n\nfunction isHexOfBytes(value: string, bytes: number): value is Hex {\n return new RegExp(`^0x[0-9a-fA-F]{${bytes * 2}}$`).test(value)\n}\n\nfunction routeMetadata(registry: BridgeRegistry, plan: BridgePlan): EvmHyperlaneRouteMetadata {\n if (plan.protocol !== 'hyperlane' || plan.route.protocol !== 'hyperlane') {\n throw new BridgeError('Ethereum Hyperlane actions require a Hyperlane transfer plan')\n }\n if (plan.registryVersion !== registry.version) {\n throw new BridgeError(`Transfer plan uses registry ${plan.registryVersion}; expected ${registry.version}`)\n }\n // Resolve deployment addresses from the current reviewed registry rather\n // than trusting the copies carried by a serialized plan.\n const route = registry.routes.find((entry) => entry.id === plan.route.id)\n if (!route || route.protocol !== 'hyperlane') {\n throw new BridgeError(`Hyperlane route is not present in the configured registry: ${plan.route.id}`)\n }\n if (route.sourceAssetId !== plan.sourceAsset.id || route.destinationAssetId !== plan.destinationAsset.id) {\n throw new BridgeError(`Transfer plan assets do not match configured route: ${route.id}`)\n }\n if (route.availability !== 'active') {\n throw new BridgeError(`Hyperlane route is not executable: ${route.id}`)\n }\n const metadata = route.metadata\n if (!metadata) throw new BridgeError(`Hyperlane route metadata is missing: ${plan.route.id}`)\n\n const routerAddress = metadata.routerAddress\n const sourceChainId = metadata.sourceChainId\n const destinationDomain = metadata.destinationDomain\n const routerType = metadata.routerType\n const tokenAddress = metadata.tokenAddress\n const destinationRouter = metadata.destinationRouter\n const mailboxAddress = metadata.mailboxAddress\n const interchainGasPaymaster = metadata.interchainGasPaymaster\n const interchainSecurityModule = metadata.interchainSecurityModule\n const registryCommit = metadata.registryCommit\n\n if (typeof routerAddress !== 'string' || !isAddress(routerAddress)) {\n throw new BridgeError(`Hyperlane route has an invalid routerAddress: ${plan.route.id}`)\n }\n if (!Number.isInteger(sourceChainId) || typeof sourceChainId !== 'number' || sourceChainId <= 0) {\n throw new BridgeError(`Hyperlane route has an invalid sourceChainId: ${plan.route.id}`)\n }\n if (!Number.isInteger(destinationDomain) || typeof destinationDomain !== 'number' || destinationDomain < 0 || destinationDomain > 0xffff_ffff) {\n throw new BridgeError(`Hyperlane route has an invalid destinationDomain: ${plan.route.id}`)\n }\n if (routerType !== 'native' && routerType !== 'collateral') {\n throw new BridgeError(`Hyperlane route has an invalid routerType: ${plan.route.id}`)\n }\n if (routerType === 'collateral' && (typeof tokenAddress !== 'string' || !isAddress(tokenAddress))) {\n throw new BridgeError(`Collateral Hyperlane route has an invalid tokenAddress: ${plan.route.id}`)\n }\n if (typeof destinationRouter !== 'string' || destinationRouter.length === 0) {\n throw new BridgeError(`Hyperlane route has an invalid destinationRouter: ${plan.route.id}`)\n }\n if (typeof mailboxAddress !== 'string' || !isAddress(mailboxAddress)) {\n throw new BridgeError(`Hyperlane route has an invalid mailboxAddress: ${plan.route.id}`)\n }\n if (typeof interchainGasPaymaster !== 'string' || !isAddress(interchainGasPaymaster)) {\n throw new BridgeError(`Hyperlane route has an invalid interchainGasPaymaster: ${plan.route.id}`)\n }\n if (typeof interchainSecurityModule !== 'string' || !isAddress(interchainSecurityModule)) {\n throw new BridgeError(`Hyperlane route has an invalid interchainSecurityModule: ${plan.route.id}`)\n }\n if (typeof registryCommit !== 'string' || !/^[0-9a-f]{40}$/i.test(registryCommit)) {\n throw new BridgeError(`Hyperlane route has an invalid registryCommit: ${plan.route.id}`)\n }\n\n return {\n routerAddress: getAddress(routerAddress),\n sourceChainId,\n destinationDomain,\n routerType,\n ...(typeof tokenAddress === 'string' && isAddress(tokenAddress) ? { tokenAddress: getAddress(tokenAddress) } : {}),\n destinationRouter,\n mailboxAddress: getAddress(mailboxAddress),\n interchainGasPaymaster: getAddress(interchainGasPaymaster),\n interchainSecurityModule: getAddress(interchainSecurityModule),\n registryCommit,\n requiresApprovalReset: metadata.requiresApprovalReset === true,\n }\n}\n\nfunction validateRecipient(recipientBytes32: Hex): void {\n if (!isHexOfBytes(recipientBytes32, 32)) {\n throw new BridgeError('Hyperlane recipientBytes32 must contain exactly 32 bytes')\n }\n}\n\nasync function rpcCall(client: EvmClient, to: Address, data: Hex): Promise<Hex> {\n const result = await client.publicClient.call({ to, data })\n if (typeof result !== 'string' || !result.startsWith('0x')) {\n throw new BridgeError('EVM public client returned an invalid eth_call result')\n }\n return result as Hex\n}\n\nasync function assertChain(client: EvmClient, expectedChainId: number): Promise<void> {\n const actual = await client.publicClient.getChainId()\n if (actual !== expectedChainId) {\n throw new BridgeError(`EVM wallet is connected to chain ${actual}; expected ${expectedChainId}`)\n }\n}\n\nasync function resolveAccount(client: EvmClient & { walletClient: EvmWalletClient }, plan: BridgePlan): Promise<Address> {\n const account = await client.walletClient.getAddress()\n if (!isAddress(account)) throw new BridgeError('EVM wallet client account is invalid')\n const normalized = getAddress(account)\n // A plan can pin the account used for its balance and allowance checks. Never\n // let a later wallet switch commit funds from a different account.\n if (plan.sender && (!isAddress(plan.sender) || getAddress(plan.sender) !== normalized)) {\n throw new BridgeError(`Prepared sender ${plan.sender} does not match connected account ${normalized}`)\n }\n return normalized\n}\n\nasync function sendTransaction(\n client: EvmClient & { walletClient: EvmWalletClient },\n chainId: number,\n transaction: { from: Address, to: Address, data: Hex, value?: Hex | undefined },\n): Promise<Hash> {\n const result = await client.walletClient.sendTransaction({\n chainId,\n from: transaction.from,\n to: transaction.to,\n data: transaction.data,\n ...(transaction.value ? { value: BigInt(transaction.value) } : {}),\n })\n if (!isHash(result)) {\n throw new BridgeError('EVM wallet client returned an invalid transaction hash')\n }\n return result\n}\n\nasync function waitForReceipt(\n client: EvmClient,\n hash: Hash,\n timeoutMs: number,\n pollingIntervalMs: number,\n): Promise<EvmReceipt | undefined> {\n const deadline = Date.now() + timeoutMs\n do {\n const result = await client.publicClient.getTransactionReceipt(hash)\n if (result != null && typeof result === 'object') return result\n if (Date.now() >= deadline) return undefined\n await new Promise<void>((resolve) => setTimeout(resolve, pollingIntervalMs))\n } while (true)\n}\n\nfunction assertSuccessfulReceipt(receipt: EvmReceipt, hash: Hash): void {\n if (receipt.status === 'reverted') throw new BridgeError(`EVM transaction reverted: ${hash}`)\n}\n\nfunction messageIdFromReceipt(receipt: EvmReceipt): Hash | undefined {\n // Hyperlane emits the cross-chain message id from its Mailbox. Other logs in\n // the same receipt belong to the token, router, and gas-payment contracts.\n for (const log of receipt.logs ?? []) {\n try {\n const signature = log.topics[0]\n if (!signature) continue\n const decoded = decodeEventLog({\n abi: DISPATCH_ID_ABI,\n data: log.data,\n topics: [signature, ...log.topics.slice(1)],\n strict: false,\n })\n const messageId = decoded.args.messageId\n if (decoded.eventName === 'DispatchId' && messageId && isHash(messageId)) return messageId\n } catch {\n // Other receipt logs are unrelated to the Hyperlane Mailbox dispatch.\n }\n }\n return undefined\n}\n\n/**\n * Calculates the source funds required for an Ethereum-to-Aleo Hyperlane transfer.\n *\n * Native routes include the asset and relayer payment in `msg.value`; token\n * routes report the ERC-20 amount separately from the native relayer payment.\n * The action reads the current router without requesting a signature or moving\n * funds.\n *\n * @param registry Supported assets and reviewed Hyperlane deployments.\n * @param client Ethereum network access used to read the selected Warp Route router.\n * @param params Route, amount, and Aleo recipient encoded as the router's 32-byte destination value.\n * @returns Atomic source amount, native payment, and token amount that may require approval.\n * @throws BridgeError When the route is unavailable, the client is on the wrong chain, or the router returns values that cannot cover the transfer.\n *\n * @example\n * const result = await quote(registry, client, {\n * plan,\n * recipientBytes32: '0x20e3629764d5338f74bee96675801b1fb29d1fc68b177668f9175708bef84311',\n * })\n */\nexport async function quote(\n registry: BridgeRegistry,\n client: EvmClient,\n params: QuoteEvmHyperlaneTransferParameters,\n): Promise<EvmHyperlaneTransferQuote> {\n validateRecipient(params.recipientBytes32)\n const metadata = routeMetadata(registry, params.plan)\n await assertChain(client, metadata.sourceChainId)\n const sourceAsset = registry.assets.find((asset) => asset.id === params.plan.sourceAsset.id)!\n const amountAtomic = parseDecimalAmount(params.plan.amountIn, sourceAsset.decimals)\n // Ask the deployed router for every asset it requires. Hyperlane returns a\n // list because native value and ERC-20 collateral are accounted separately.\n const data = encodeFunctionData({\n abi: WARP_ROUTE_ABI,\n functionName: 'quoteTransferRemote',\n args: [metadata.destinationDomain, params.recipientBytes32, amountAtomic],\n })\n const encoded = await rpcCall(client, metadata.routerAddress, data)\n const quotes = decodeFunctionResult({\n abi: WARP_ROUTE_ABI,\n functionName: 'quoteTransferRemote',\n data: encoded,\n })\n const nativeValueAtomic = quotes\n .filter((quote) => getAddress(quote.token) === zeroAddress)\n .reduce((sum, quote) => sum + quote.amount, 0n)\n\n if (metadata.routerType === 'native') {\n // On a native route, msg.value contains both the bridged asset and the\n // relayer payment. The difference is the fee visible to the caller.\n if (nativeValueAtomic < amountAtomic) {\n throw new BridgeError('Native Hyperlane quote does not cover the transfer amount')\n }\n return {\n routeId: params.plan.route.id,\n routerAddress: metadata.routerAddress,\n sourceChainId: metadata.sourceChainId,\n destinationDomain: metadata.destinationDomain,\n recipientBytes32: params.recipientBytes32,\n amountAtomic,\n nativeValueAtomic,\n nativeFeeAtomic: nativeValueAtomic - amountAtomic,\n }\n }\n\n // On a collateral route, the ERC-20 amount is approved and transferred while\n // msg.value pays only native-denominated delivery costs.\n const tokenAddress = metadata.tokenAddress!\n const tokenAmountAtomic = quotes\n .filter((quote) => getAddress(quote.token) === tokenAddress)\n .reduce((sum, quote) => sum + quote.amount, 0n)\n if (tokenAmountAtomic < amountAtomic) {\n throw new BridgeError('Collateral Hyperlane quote does not cover the transfer amount')\n }\n return {\n routeId: params.plan.route.id,\n routerAddress: metadata.routerAddress,\n sourceChainId: metadata.sourceChainId,\n destinationDomain: metadata.destinationDomain,\n recipientBytes32: params.recipientBytes32,\n amountAtomic,\n nativeValueAtomic,\n nativeFeeAtomic: nativeValueAtomic,\n tokenAmountAtomic,\n tokenAddress,\n }\n}\n\nfunction executionReceipt(\n plan: BridgePlan,\n status: BridgeReceipt['status'],\n id: string,\n quote: EvmHyperlaneTransferQuote,\n approvalTxIds: Hash[],\n sourceSender: Address,\n sourceTxId?: Hash,\n messageId?: Hash,\n): BridgeReceipt {\n return {\n id,\n protocol: 'hyperlane',\n status,\n ...(sourceTxId ? { sourceTxId } : {}),\n ...(messageId ? { messageId } : {}),\n protocolState: {\n routeId: plan.route.id,\n approvalTxIds: [...approvalTxIds],\n sourceSender,\n recipientBytes32: quote.recipientBytes32,\n destinationDomain: quote.destinationDomain,\n nativeValueAtomic: quote.nativeValueAtomic.toString(),\n amountAtomic: quote.amountAtomic.toString(),\n },\n }\n}\n\nfunction checkpointApprovalIds(receipt: BridgeReceipt): Hash[] {\n const ids = receipt.protocolState.approvalTxIds\n if (!Array.isArray(ids) || ids.some((id) => typeof id !== 'string' || !isHash(id))) {\n throw new BridgeError('Hyperlane checkpoint contains invalid approval transaction ids')\n }\n return [...ids] as Hash[]\n}\n\nfunction validateCheckpoint(\n registry: BridgeRegistry,\n plan: BridgePlan,\n metadata: EvmHyperlaneRouteMetadata,\n recipientBytes32: Hex,\n receipt: BridgeReceipt,\n): void {\n // A checkpoint is application-controlled input. Bind every value that affects\n // the dispatch before trusting its transaction identifiers during recovery.\n const state = receipt.protocolState\n const sourceAsset = registry.assets.find((asset) => asset.id === plan.sourceAsset.id)\n if (!sourceAsset) throw new BridgeError(`Hyperlane source asset is not present in the configured registry: ${plan.sourceAsset.id}`)\n const amountAtomic = parseDecimalAmount(plan.amountIn, sourceAsset.decimals).toString()\n if (receipt.protocol !== 'hyperlane'\n || state.routeId !== plan.route.id\n || state.destinationDomain !== metadata.destinationDomain\n || state.amountAtomic !== amountAtomic\n || typeof state.recipientBytes32 !== 'string'\n || state.recipientBytes32.toLowerCase() !== recipientBytes32.toLowerCase()) {\n throw new BridgeError('Hyperlane checkpoint does not match the prepared transfer')\n }\n}\n\n/** Finds the latest confirmed approval block without treating an unresolved hash as failed. */\nasync function approvalScanBlock(client: EvmClient, approvalTxIds: readonly Hash[]): Promise<bigint | undefined> {\n let blockNumber: bigint | undefined\n for (const approvalTxId of approvalTxIds) {\n const receipt = await client.publicClient.getTransactionReceipt(approvalTxId)\n if (!receipt) continue\n assertSuccessfulReceipt(receipt, approvalTxId)\n if (typeof receipt.blockNumber === 'bigint'\n && (blockNumber === undefined || receipt.blockNumber > blockNumber)) {\n blockNumber = receipt.blockNumber\n }\n }\n return blockNumber\n}\n\n/**\n * Searches only the source blocks following a known approval and requires both\n * the router event and transaction sender to match the saved transfer intent.\n */\nasync function recoverDispatchFromHistory(\n client: EvmClient,\n metadata: EvmHyperlaneRouteMetadata,\n recipientBytes32: Hex,\n receipt: BridgeReceipt,\n approvalTxIds: Hash[],\n options: { required: boolean },\n): Promise<BridgeReceipt | undefined> {\n const sourceSender = receipt.protocolState.sourceSender\n if (typeof sourceSender !== 'string' || !isAddress(sourceSender)) {\n if (options.required) throw new BridgeError('Cannot safely resume Hyperlane without the source account used by the approval')\n return undefined\n }\n const fromBlock = await approvalScanBlock(client, approvalTxIds)\n if (fromBlock === undefined) {\n if (options.required) {\n throw new BridgeError('Cannot safely resume Hyperlane because no confirmed approval block is available for source history verification')\n }\n return undefined\n }\n const amountAtomic = receipt.protocolState.amountAtomic\n if (typeof amountAtomic !== 'string' || !/^\\d+$/.test(amountAtomic)) {\n throw new BridgeError('Hyperlane checkpoint contains an invalid source amount')\n }\n\n const logs = await client.publicClient.getLogs({ address: metadata.routerAddress, fromBlock })\n const candidates = new Set<Hash>()\n for (const log of logs) {\n try {\n const decoded = decodeEventLog({\n abi: WARP_ROUTE_ABI,\n data: log.data,\n topics: log.topics as [Hex, ...Hex[]],\n })\n if (decoded.eventName === 'SentTransferRemote'\n && decoded.args.destination === metadata.destinationDomain\n && decoded.args.recipient.toLowerCase() === recipientBytes32.toLowerCase()\n && decoded.args.amount === BigInt(amountAtomic)) {\n candidates.add(log.transactionHash)\n }\n } catch {\n // Other router events do not identify a source transfer.\n }\n }\n\n const matches: BridgeReceipt[] = []\n for (const transactionHash of candidates) {\n const [transaction, sourceReceipt] = await Promise.all([\n client.publicClient.getTransaction(transactionHash),\n client.publicClient.getTransactionReceipt(transactionHash),\n ])\n if (!transaction || !sourceReceipt\n || getAddress(transaction.from) !== getAddress(sourceSender)\n || !transaction.to\n || getAddress(transaction.to) !== metadata.routerAddress) continue\n assertSuccessfulReceipt(sourceReceipt, transactionHash)\n const messageId = messageIdFromReceipt(sourceReceipt)\n matches.push({\n ...receipt,\n id: messageId ?? transactionHash,\n status: 'DELIVERY_PENDING',\n sourceTxId: transactionHash,\n ...(messageId ? { messageId } : {}),\n })\n }\n if (matches.length > 1) {\n throw new BridgeError('Multiple matching Hyperlane dispatches were found; recovery cannot safely choose one source transaction')\n }\n return matches[0]\n}\n\n/**\n * Checks whether one submitted EVM Hyperlane source transaction has committed funds.\n *\n * A pending transaction leaves the state unchanged. A successful transaction\n * advances to destination delivery and records the canonical Hyperlane message\n * identifier when the receipt contains it. No signature or submission occurs.\n *\n * @param registry Supported assets and reviewed Hyperlane deployments.\n * @param client EVM network access used to read the transaction receipt.\n * @param plan Route, assets, amount, and recipient for the transfer.\n * @param recipientBytes32 Aleo recipient committed by the transaction in its 32-byte wire encoding.\n * @param receipt Latest state containing the submitted source transaction identifier.\n * @returns Unchanged source confirmation state or state ready to follow destination delivery.\n * @throws BridgeError When the saved state does not match the transfer or the source transaction reverted.\n * @example const next = await getSourceStatus(registry, client, plan, recipientBytes32, receipt)\n */\nexport async function getSourceStatus(\n registry: BridgeRegistry,\n client: EvmClient,\n plan: BridgePlan,\n recipientBytes32: Hex,\n receipt: BridgeReceipt,\n): Promise<BridgeReceipt> {\n const metadata = routeMetadata(registry, plan)\n await assertChain(client, metadata.sourceChainId)\n validateCheckpoint(registry, plan, metadata, recipientBytes32, receipt)\n if (receipt.status !== 'SOURCE_CONFIRMING') {\n throw new BridgeError('Hyperlane source status requires a source-confirming receipt')\n }\n const sourceTxId = receipt.sourceTxId\n if (!sourceTxId || !isHash(sourceTxId)) {\n throw new BridgeError('Hyperlane checkpoint is missing the source transaction id')\n }\n const sourceReceipt = await client.publicClient.getTransactionReceipt(sourceTxId)\n if (!sourceReceipt) return receipt\n assertSuccessfulReceipt(sourceReceipt, sourceTxId)\n // Confirmation proves the source dispatch executed. The message id is the\n // preferred destination lookup key, but retaining the source hash still lets\n // an operator diagnose a missing or unparseable Mailbox log.\n const messageId = messageIdFromReceipt(sourceReceipt)\n return {\n ...receipt,\n id: messageId ?? sourceTxId,\n status: 'DELIVERY_PENDING',\n ...(messageId ? { messageId } : {}),\n }\n}\n\n/**\n * Reconstructs an interrupted EVM Hyperlane transfer from saved transaction identifiers.\n *\n * The helper checks whether the last saved token approval or source dispatch\n * was accepted. It never requests a signature or repeats a transaction. A\n * confirmed approval with no dispatch means the source transfer still needs\n * wallet authorization.\n *\n * @param registry Supported assets and reviewed Hyperlane deployments.\n * @param client EVM network access used to check submitted transactions.\n * @param plan Route, assets, amount, and recipient reconstructed from the saved information.\n * @param recipientBytes32 Aleo recipient committed by the transfer in its 32-byte wire encoding.\n * @param checkpoint Saved route and submitted transaction identifiers.\n * @returns Current source state and whether confirmation, submission, or destination delivery comes next.\n * @throws BridgeError When the saved information does not match the transfer or a submitted transaction reverted.\n * @example const receipt = await recoverSourceCheckpoint(registry, client, plan, recipient, checkpoint)\n */\nexport async function recoverSourceCheckpoint(\n registry: BridgeRegistry,\n client: EvmClient,\n plan: BridgePlan,\n recipientBytes32: Hex,\n checkpoint: BridgeCheckpoint,\n): Promise<BridgeReceipt> {\n if (checkpoint.version !== 1 || checkpoint.intent.bridgeProtocol !== 'hyperlane' || checkpoint.route.id !== plan.route.id) {\n throw new BridgeError('Bridge checkpoint does not match the prepared route')\n }\n const metadata = routeMetadata(registry, plan)\n const sourceAsset = registry.assets.find((asset) => asset.id === plan.sourceAsset.id)\n if (!sourceAsset) throw new BridgeError(`Hyperlane source asset is not present in the configured registry: ${plan.sourceAsset.id}`)\n const approvals = [...(checkpoint.source?.approvalTransactionIds ?? [])]\n if (approvals.some((id) => !isHash(id))) throw new BridgeError('Bridge checkpoint contains an invalid approval transaction id')\n const approvalTxIds = approvals as Hash[]\n const protocolState = {\n routeId: plan.route.id,\n approvalTxIds,\n recipientBytes32,\n destinationDomain: metadata.destinationDomain,\n nativeValueAtomic: '0',\n amountAtomic: parseDecimalAmount(plan.amountIn, sourceAsset.decimals).toString(),\n ...(plan.sender && isAddress(plan.sender) ? { sourceSender: getAddress(plan.sender) } : {}),\n }\n if (!checkpoint.source?.transactionId) {\n // With only approvals saved, inspect the latest approval. A confirmed\n // approval stops before dispatch so recovery never moves funds by itself.\n const approvalTxId = approvalTxIds.at(-1)\n if (!approvalTxId) throw new BridgeError('Bridge checkpoint contains no submitted transaction')\n const pending: BridgeReceipt = {\n id: approvalTxId,\n protocol: 'hyperlane',\n status: 'SOURCE_APPROVAL_PENDING',\n protocolState,\n }\n const approvalReceipt = await client.publicClient.getTransactionReceipt(approvalTxId)\n if (!approvalReceipt) return pending\n assertSuccessfulReceipt(approvalReceipt, approvalTxId)\n const recovered = await recoverDispatchFromHistory(\n client,\n metadata,\n recipientBytes32,\n pending,\n approvalTxIds,\n { required: false },\n )\n if (recovered) return recovered\n return { ...pending, status: 'SOURCE_SUBMISSION_PENDING' }\n }\n if (!isHash(checkpoint.source.transactionId)) throw new BridgeError('Bridge checkpoint contains an invalid source transaction id')\n // A saved source transaction is already the irreversible dispatch. Observe\n // it through the normal status path rather than authorizing anything again.\n const pending: BridgeReceipt = {\n id: checkpoint.source.transactionId,\n protocol: 'hyperlane',\n status: 'SOURCE_CONFIRMING',\n sourceTxId: checkpoint.source.transactionId,\n protocolState,\n }\n const observed = await getSourceStatus(registry, client, plan, recipientBytes32, pending)\n if (observed !== pending) return observed\n return await recoverDispatchFromHistory(\n client,\n metadata,\n recipientBytes32,\n pending,\n approvalTxIds,\n { required: false },\n ) ?? observed\n}\n\n/**\n * Begins an Ethereum-to-Aleo Hyperlane transfer by committing funds on Ethereum.\n *\n * A token route requests approval only when the current allowance is too low;\n * tokens such as USDT may require resetting an existing allowance to zero first.\n * The wallet then submits the source dispatch. Every submitted transaction can\n * incur a network fee, and an accepted dispatch may no longer be reversible.\n *\n * @param registry Supported assets and reviewed Hyperlane deployments.\n * @param client Ethereum network and wallet access used to read, authorize, and submit.\n * @param params Route, assets, amount, Aleo recipient, confirmation controls, and optional recovery callback.\n * @returns Submitted approval identifiers and state needed to follow source confirmation or destination delivery. A timeout remains pending rather than reporting failure.\n * @throws BridgeError When the route is unavailable, the wallet uses a different chain or account, authorization fails, or a confirmed transaction reverted.\n *\n * @example\n * const execution = await execute(registry, client, {\n * plan,\n * recipientBytes32: '0x20e3629764d5338f74bee96675801b1fb29d1fc68b177668f9175708bef84311',\n * })\n */\nexport async function execute(\n registry: BridgeRegistry,\n client: EvmClient & { walletClient: EvmWalletClient },\n params: ExecuteEvmHyperlaneTransferParameters,\n): Promise<EvmHyperlaneTransferExecution> {\n const pollingIntervalMs = params.pollingIntervalMs ?? 1_000\n const confirmationTimeoutMs = params.confirmationTimeoutMs ?? 120_000\n if (!Number.isFinite(pollingIntervalMs) || pollingIntervalMs < 0) {\n throw new BridgeError('pollingIntervalMs must be a non-negative finite number')\n }\n if (!Number.isFinite(confirmationTimeoutMs) || confirmationTimeoutMs < 0) {\n throw new BridgeError('confirmationTimeoutMs must be a non-negative finite number')\n }\n\n const metadata = routeMetadata(registry, params.plan)\n await assertChain(client, metadata.sourceChainId)\n let approvalTxIds: Hash[] = []\n\n if (params.resume) {\n // Resume receipts represent already-submitted work. Each branch observes\n // the recorded transaction and only the approval-complete branch may fall\n // through to a new source dispatch.\n validateCheckpoint(registry, params.plan, metadata, params.recipientBytes32, params.resume)\n approvalTxIds = checkpointApprovalIds(params.resume)\n if (params.resume.status === 'DELIVERY_PENDING') {\n return { approvalTxIds, receipt: params.resume }\n }\n if (params.resume.status === 'SOURCE_CONFIRMING') {\n const sourceTxId = params.resume.sourceTxId\n if (!sourceTxId || !isHash(sourceTxId)) throw new BridgeError('Hyperlane checkpoint is missing the source transaction id')\n const sourceReceipt = await waitForReceipt(client, sourceTxId, confirmationTimeoutMs, pollingIntervalMs)\n if (!sourceReceipt) return { approvalTxIds, receipt: params.resume }\n assertSuccessfulReceipt(sourceReceipt, sourceTxId)\n const messageId = messageIdFromReceipt(sourceReceipt)\n return {\n approvalTxIds,\n receipt: {\n ...params.resume,\n id: messageId ?? sourceTxId,\n status: 'DELIVERY_PENDING',\n ...(messageId ? { messageId } : {}),\n },\n }\n }\n if (params.resume.status === 'SOURCE_SUBMISSION_PENDING') {\n const recovered = await recoverDispatchFromHistory(\n client,\n metadata,\n params.recipientBytes32,\n params.resume,\n approvalTxIds,\n { required: true },\n )\n if (recovered) return { approvalTxIds, receipt: recovered }\n // Recovery already observed the final approval as successful. Requote\n // current allowance and fees only after source history proves that no\n // matching dispatch has finalized.\n } else if (params.resume.status === 'SOURCE_APPROVAL_PENDING') {\n const approvalTxId = approvalTxIds.at(-1)\n if (!approvalTxId) throw new BridgeError('Hyperlane checkpoint is missing the approval transaction id')\n const approvalReceipt = await waitForReceipt(client, approvalTxId, confirmationTimeoutMs, pollingIntervalMs)\n if (!approvalReceipt) return { approvalTxIds, receipt: params.resume }\n assertSuccessfulReceipt(approvalReceipt, approvalTxId)\n } else {\n throw new BridgeError(`Unsupported Hyperlane resume status: ${params.resume.status}`)\n }\n }\n\n // Quote at the last responsible moment because router fees and token\n // allowances can change between display and wallet authorization.\n const transferQuote = await quote(registry, client, params)\n const account = await resolveAccount(client, params.plan)\n\n if (metadata.routerType === 'collateral') {\n // The router, not Hyperlane globally, is the ERC-20 spender. Approval is a\n // separate transaction and does not yet commit funds to the bridge.\n const allowanceData = encodeFunctionData({\n abi: ERC20_ABI,\n functionName: 'allowance',\n args: [account, metadata.routerAddress],\n })\n const allowanceResult = await rpcCall(client, metadata.tokenAddress!, allowanceData)\n const allowance = decodeFunctionResult({\n abi: ERC20_ABI,\n functionName: 'allowance',\n data: allowanceResult,\n })\n const required = transferQuote.tokenAmountAtomic!\n\n const approveAndConfirm = async (amount: bigint): Promise<boolean> => {\n const data = encodeFunctionData({\n abi: ERC20_ABI,\n functionName: 'approve',\n args: [metadata.routerAddress, amount],\n })\n const hash = await sendTransaction(client, metadata.sourceChainId, { from: account, to: metadata.tokenAddress!, data })\n approvalTxIds.push(hash)\n // Persist immediately after broadcast and before polling. A process crash\n // can then recover this exact transaction rather than submit it again.\n const checkpoint = executionReceipt(params.plan, 'SOURCE_APPROVAL_PENDING', hash, transferQuote, approvalTxIds, account)\n await params.onSubmitted?.(checkpoint)\n const receipt = await waitForReceipt(client, hash, confirmationTimeoutMs, pollingIntervalMs)\n if (!receipt) return false\n assertSuccessfulReceipt(receipt, hash)\n return true\n }\n\n if (allowance < required) {\n if (allowance > 0n && metadata.requiresApprovalReset) {\n // Some tokens, notably USDT, reject non-zero-to-non-zero allowance\n // changes. Confirm the zero reset before setting the required amount.\n if (!await approveAndConfirm(0n)) {\n return {\n approvalTxIds,\n receipt: executionReceipt(params.plan, 'SOURCE_APPROVAL_PENDING', approvalTxIds.at(-1)!, transferQuote, approvalTxIds, account),\n }\n }\n }\n if (!await approveAndConfirm(required)) {\n return {\n approvalTxIds,\n receipt: executionReceipt(params.plan, 'SOURCE_APPROVAL_PENDING', approvalTxIds.at(-1)!, transferQuote, approvalTxIds, account),\n }\n }\n }\n }\n\n // This dispatch is the irreversible source boundary: the router locks or\n // burns the source asset and emits the cross-chain message.\n const transferData = encodeFunctionData({\n abi: WARP_ROUTE_ABI,\n functionName: 'transferRemote',\n args: [transferQuote.destinationDomain, transferQuote.recipientBytes32, transferQuote.amountAtomic],\n })\n const sourceTxId = await sendTransaction(client, metadata.sourceChainId, {\n from: account,\n to: transferQuote.routerAddress,\n data: transferData,\n value: `0x${transferQuote.nativeValueAtomic.toString(16)}`,\n })\n const checkpoint = executionReceipt(params.plan, 'SOURCE_CONFIRMING', sourceTxId, transferQuote, approvalTxIds, account, sourceTxId)\n // The transaction may land even if receipt polling times out or the process\n // exits, so checkpoint the hash before any confirmation read.\n await params.onSubmitted?.(checkpoint)\n const sourceReceipt = await waitForReceipt(\n client,\n sourceTxId,\n confirmationTimeoutMs,\n pollingIntervalMs,\n )\n if (!sourceReceipt) {\n // Lack of a receipt is unknown, not failure. Return enough state for a later\n // status check to distinguish pending, success, and revert.\n return {\n approvalTxIds,\n receipt: checkpoint,\n }\n }\n assertSuccessfulReceipt(sourceReceipt, sourceTxId)\n // Destination verification is keyed by the Mailbox message id when present.\n const messageId = messageIdFromReceipt(sourceReceipt)\n return {\n approvalTxIds,\n receipt: executionReceipt(\n params.plan,\n 'DELIVERY_PENDING',\n messageId ?? sourceTxId,\n transferQuote,\n approvalTxIds,\n account,\n sourceTxId,\n messageId,\n ),\n }\n}\n","// SEALEVEL_NOTES.md §5: only the Mailbox dispatch log carries the complete id.\nconst DISPATCHED_MESSAGE_LOG_PATTERN = /Dispatched message to \\d+, ID (0x[0-9a-fA-F]{64})/\n\n/**\n * Extracts the Hyperlane message id from confirmed Solana program logs.\n *\n * Reads only the supplied logs and ignores abbreviated IGP and warp-completion\n * identifiers. It does not contact Solana.\n *\n * @param logs Program log lines, or `null` when the transaction was not found.\n * @returns The complete 32-byte message id, or `undefined` when absent.\n * @example const messageId = extractSolanaHyperlaneMessageId(logs)\n */\nexport function extractSolanaHyperlaneMessageId(logs: string[] | null): string | undefined {\n if (!logs) return undefined\n for (const line of logs) {\n const match = DISPATCHED_MESSAGE_LOG_PATTERN.exec(line)\n if (match) return match[1]\n }\n return undefined\n}\n","import { BridgeError } from '../../errors/bridgeErrors.js'\nimport type { BridgeRegistry, BridgePlan } from '../../types/protocol.js'\nimport type { SolanaHyperlaneRouteMetadata } from '../../types/solana.js'\n\n// Base58, excluding the visually ambiguous 0/O/I/l — matches how Solana\n// encodes a 32-byte account or program public key.\nconst SOLANA_PUBKEY = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/\n\nfunction requirePubkey(value: unknown, field: string, routeId: string): string {\n if (typeof value !== 'string' || !SOLANA_PUBKEY.test(value)) {\n throw new BridgeError(`Solana Hyperlane route has an invalid ${field}: ${routeId}`)\n }\n return value\n}\n\n/**\n * Validates transfer details against the registry's Solana Hyperlane route and\n * returns its reviewed deployment metadata.\n *\n * Confirms the plan's protocol, registry version, route presence, asset\n * pairing, and availability, then validates each metadata field without\n * contacting Solana or requesting a signature. These checks prevent an\n * incomplete or stale deployment snapshot from becoming an account list for a\n * signed Solana transaction.\n *\n * @param registry Supported assets and reviewed Solana Hyperlane deployment accounts.\n * @param plan Route, amount, and recipient selected for the transfer.\n * @returns The route's validated Solana Hyperlane deployment metadata.\n * @throws BridgeError When the plan is not a Hyperlane plan, was built from a\n * different registry version, the route is missing from the registry, its\n * assets do not match the plan, it is not active, or its metadata is\n * absent or malformed.\n *\n * @example\n * const metadata = solanaRouteMetadata(registry, plan)\n */\nexport function solanaRouteMetadata(\n registry: BridgeRegistry,\n plan: BridgePlan,\n): SolanaHyperlaneRouteMetadata {\n if (plan.protocol !== 'hyperlane' || plan.route.protocol !== 'hyperlane') {\n throw new BridgeError('Solana Hyperlane actions require a Hyperlane transfer plan')\n }\n if (plan.registryVersion !== registry.version) {\n throw new BridgeError(`Transfer plan uses registry ${plan.registryVersion}; expected ${registry.version}`)\n }\n // Resolve the current registry entry rather than trusting metadata copied\n // into an older plan after the application or registry has changed.\n const route = registry.routes.find((entry) => entry.id === plan.route.id)\n if (!route || route.protocol !== 'hyperlane') {\n throw new BridgeError(`Hyperlane route is not present in the configured registry: ${plan.route.id}`)\n }\n if (route.sourceAssetId !== plan.sourceAsset.id || route.destinationAssetId !== plan.destinationAsset.id) {\n throw new BridgeError(`Transfer plan assets do not match configured route: ${route.id}`)\n }\n if (route.availability !== 'active') {\n throw new BridgeError(`Hyperlane route is not executable: ${route.id}`)\n }\n // Every address below participates in instruction account ordering. Reject\n // the entire route instead of letting a missing field become a bad public key.\n const metadata = route.metadata\n if (!metadata) throw new BridgeError(`Solana Hyperlane route metadata is missing: ${plan.route.id}`)\n\n const routeId = plan.route.id\n const warpProgramAddress = requirePubkey(metadata.warpProgramAddress, 'warpProgramAddress', routeId)\n const tokenPda = requirePubkey(metadata.tokenPda, 'tokenPda', routeId)\n const nativeCollateralPda = requirePubkey(metadata.nativeCollateralPda, 'nativeCollateralPda', routeId)\n const dispatchAuthorityPda = requirePubkey(metadata.dispatchAuthorityPda, 'dispatchAuthorityPda', routeId)\n const mailboxProgramAddress = requirePubkey(metadata.mailboxProgramAddress, 'mailboxProgramAddress', routeId)\n const mailboxOutboxPda = requirePubkey(metadata.mailboxOutboxPda, 'mailboxOutboxPda', routeId)\n const igpProgramAddress = requirePubkey(metadata.igpProgramAddress, 'igpProgramAddress', routeId)\n const igpProgramDataPda = requirePubkey(metadata.igpProgramDataPda, 'igpProgramDataPda', routeId)\n const igpAccount = requirePubkey(metadata.igpAccount, 'igpAccount', routeId)\n const splNoopProgramAddress = requirePubkey(metadata.splNoopProgramAddress, 'splNoopProgramAddress', routeId)\n\n const igpOverheadAccountRaw = metadata.igpOverheadAccount\n const igpOverheadAccount = igpOverheadAccountRaw == null\n ? undefined\n : requirePubkey(igpOverheadAccountRaw, 'igpOverheadAccount', routeId)\n\n const destinationDomain = metadata.destinationDomain\n if (\n typeof destinationDomain !== 'number'\n || !Number.isInteger(destinationDomain)\n || destinationDomain < 0\n || destinationDomain > 0xffff_ffff\n ) {\n throw new BridgeError(`Solana Hyperlane route has an invalid destinationDomain: ${routeId}`)\n }\n\n const destinationGasAmount = metadata.destinationGasAmount\n if (typeof destinationGasAmount !== 'string' || !/^\\d+$/.test(destinationGasAmount)) {\n throw new BridgeError(`Solana Hyperlane route has an invalid destinationGasAmount: ${routeId}`)\n }\n\n // Provenance does not prove the live accounts are unchanged, but it makes a\n // reviewed deployment reproducible across implementations and languages.\n const registryCommit = metadata.registryCommit\n if (typeof registryCommit !== 'string' || !/^[0-9a-f]{40}$/i.test(registryCommit)) {\n throw new BridgeError(`Solana Hyperlane route has an invalid registryCommit: ${routeId}`)\n }\n\n const solanaReviewedAt = metadata.solanaReviewedAt\n if (typeof solanaReviewedAt !== 'string' || Number.isNaN(Date.parse(solanaReviewedAt))) {\n throw new BridgeError(`Solana Hyperlane route has an invalid solanaReviewedAt: ${routeId}`)\n }\n\n const solanaConfigSource = metadata.solanaConfigSource\n if (typeof solanaConfigSource !== 'string' || solanaConfigSource.length === 0) {\n throw new BridgeError(`Solana Hyperlane route has an invalid solanaConfigSource: ${routeId}`)\n }\n\n return {\n warpProgramAddress,\n tokenPda,\n nativeCollateralPda,\n dispatchAuthorityPda,\n mailboxProgramAddress,\n mailboxOutboxPda,\n igpProgramAddress,\n igpProgramDataPda,\n igpAccount,\n ...(igpOverheadAccount == null ? {} : { igpOverheadAccount }),\n splNoopProgramAddress,\n destinationDomain,\n destinationGasAmount,\n registryCommit,\n solanaReviewedAt,\n solanaConfigSource,\n }\n}\n","import { BridgeError } from '../../errors/bridgeErrors.js'\nimport type { SolanaClient, SolanaWalletClient } from '../../connections/solana.js'\nimport { quoteIgpGasPayment } from '../../solana/igp.js'\nimport { loadKit } from '../../solana/kit.js'\nimport type { SolanaRpcClient } from '../../solana/rpc.js'\nimport { buildTransferRemoteInstruction, type SolanaAccountMeta } from '../../solana/transferRemote.js'\nimport { extractSolanaHyperlaneMessageId } from '../../solana/extractHyperlaneMessageId.js'\nimport type { BridgeRegistry, BridgeReceipt } from '../../types/protocol.js'\nimport type {\n ExecuteSolanaHyperlaneTransferParameters,\n SolanaHyperlaneRouteMetadata,\n SolanaHyperlaneTransferExecution,\n SolanaHyperlaneTransferQuote,\n QuoteSolanaHyperlaneTransferParameters,\n} from '../../types/solana.js'\nimport { parseDecimalAmount } from '../../utils/units.js'\nimport { solanaRouteMetadata } from './solanaMetadata.js'\n\n// SEALEVEL_NOTES.md \"Observed total lamport overhead\": rent for the two\n// program-derived accounts a transfer creates fresh — the gas-payment PDA\n// (1,872,240 lamports) and the dispatched-message storage PDA (2,241,120\n// lamports) — derived as the observed lamportDelta (7,023,360) minus the\n// IGP gas payment (2,900,000) and the Solana network fee (10,000), both of\n// which the quote already accounts for.\nconst GAS_PAYMENT_ACCOUNT_DATA_LENGTH = 141\nconst DISPATCHED_MESSAGE_ACCOUNT_DATA_LENGTH = 194\nconst SOLANA_HYPERLANE_COMPUTE_UNIT_LIMIT = 400_000\n\nfunction accountRole(kit: Awaited<ReturnType<typeof loadKit>>, account: SolanaAccountMeta) {\n if (account.signer && account.writable) return kit.AccountRole.WRITABLE_SIGNER\n if (account.signer) return kit.AccountRole.READONLY_SIGNER\n if (account.writable) return kit.AccountRole.WRITABLE\n return kit.AccountRole.READONLY\n}\n\n/**\n * Calculates the SOL required for a Solana-to-Aleo Hyperlane transfer.\n *\n * The total includes the transferred amount, relayer payment, current network\n * fee, and rent for accounts created by the dispatch. The action reads Solana\n * without requesting a signature or moving funds.\n *\n * @param registry Supported assets and reviewed Hyperlane deployments.\n * @param client Solana network access used to read route accounts, fees, and rent.\n * @param params Route, amount, recipient, and source account used to compile the fee quote.\n * @returns Transfer amount, relayer payment, network fee, rent, and total in lamports.\n * @throws BridgeError When the route is unavailable, no source account is supplied, or Solana returns invalid account or fee data.\n * @example const result = await quote(registry, client, { plan })\n */\nexport async function quote(\n registry: BridgeRegistry,\n client: SolanaClient,\n params: QuoteSolanaHyperlaneTransferParameters,\n): Promise<SolanaHyperlaneTransferQuote> {\n // Validate every reviewed program and account address before reading Solana;\n // ports must not infer these deployment-specific accounts from token symbols.\n const metadata = solanaRouteMetadata(registry, params.plan)\n const rpc = client.publicClient\n const amountLamports = parseDecimalAmount(params.plan.amountIn, params.plan.sourceAsset.decimals)\n // The on-chain IGP account is authoritative for destination gas price and\n // exchange rate. A registry snapshot alone cannot safely quote this payment.\n const igpAccountData = await rpc.getAccountData(metadata.igpAccount)\n if (!igpAccountData) throw new BridgeError(`Solana IGP account does not exist: ${metadata.igpAccount}`)\n const igpPaymentLamports = quoteIgpGasPayment({\n igpAccountData,\n destinationDomain: metadata.destinationDomain,\n gasAmount: BigInt(metadata.destinationGasAmount),\n })\n if (!params.plan.sender) throw new BridgeError('Solana sender is required to quote the transaction fee')\n const kit = await loadKit()\n // A transfer creates message-specific PDAs, so even fee estimation needs a\n // disposable unique-message public key. No signature from this key is sent.\n const uniqueMessageSigner = await kit.generateKeyPairSigner()\n const built = await buildTransferRemoteInstruction({\n metadata,\n senderAddress: params.plan.sender,\n uniqueMessageAddress: uniqueMessageSigner.address,\n recipientAleoAddress: params.plan.recipient,\n amountLamports,\n })\n const { blockhash, lastValidBlockHeight } = await rpc.getLatestBlockhash()\n const message = kit.pipe(\n kit.createTransactionMessage({ version: 0 }),\n (transaction) => kit.setTransactionMessageFeePayer(kit.address(params.plan.sender!), transaction),\n (transaction) => kit.setTransactionMessageLifetimeUsingBlockhash({ blockhash: kit.blockhash(blockhash), lastValidBlockHeight }, transaction),\n (transaction) => kit.setTransactionMessageComputeUnitLimit(SOLANA_HYPERLANE_COMPUTE_UNIT_LIMIT, transaction),\n (transaction) => kit.appendTransactionMessageInstruction({\n programAddress: kit.address(built.programAddress),\n accounts: built.accounts.map((account) => ({ address: kit.address(account.address), role: accountRole(kit, account) })),\n data: built.data,\n }, transaction),\n )\n const compiled = kit.compileTransaction(message)\n // Network fee and rent are independent reads. Include both newly created\n // protocol accounts plus the sender's rent floor in the required balance.\n const [networkFeeLamports, gasPaymentRent, dispatchedMessageRent, senderRent] = await Promise.all([\n rpc.getFeeForMessage(new Uint8Array(compiled.messageBytes)),\n rpc.getMinimumBalanceForRentExemption(GAS_PAYMENT_ACCOUNT_DATA_LENGTH),\n rpc.getMinimumBalanceForRentExemption(DISPATCHED_MESSAGE_ACCOUNT_DATA_LENGTH),\n rpc.getMinimumBalanceForRentExemption(0),\n ])\n const rentLamports = gasPaymentRent + dispatchedMessageRent + senderRent\n return {\n routeId: params.plan.route.id,\n amountLamports,\n igpPaymentLamports,\n networkFeeLamports,\n rentLamports,\n totalLamports: amountLamports + igpPaymentLamports + networkFeeLamports + rentLamports,\n }\n}\n\n/**\n * Polls a submitted Solana signature until Hyperlane's confirmation\n * threshold is reached, the network reports failure, or the caller's\n * timeout elapses.\n *\n * Reads Solana repeatedly, sleeping `pollingIntervalMs` between requests. It\n * never signs or submits a transaction.\n *\n * A thrown error from the status read itself (a transient RPC hiccup, a rate\n * limit) never aborts the wait — the transaction was already broadcast, so\n * treating a read failure as a transfer failure would report a false\n * negative. Such errors are swallowed and polling continues until the\n * timeout, at which point the caller gets the same `undefined` timeout\n * outcome it would from a run of plain unresolved statuses.\n *\n * @param rpc Solana JSON-RPC client used for the status lookup.\n * @param signature Submitted transaction signature to track.\n * @param pollingIntervalMs Delay between confirmation checks.\n * @param confirmationTimeoutMs Maximum time to wait before giving up.\n * @returns A confirmed state, `'expired'` once the blockhash is invalid, or `undefined` on timeout.\n * @throws BridgeError When the network reports the transaction failed.\n */\nasync function pollForConfirmation(\n rpc: SolanaRpcClient,\n signature: string,\n pollingIntervalMs: number,\n confirmationTimeoutMs: number,\n blockhash: string,\n): Promise<'confirmed' | 'finalized' | 'expired' | undefined> {\n const deadline = Date.now() + confirmationTimeoutMs\n do {\n let status: Awaited<ReturnType<SolanaRpcClient['getSignatureStatus']>>\n try {\n status = await rpc.getSignatureStatus(signature)\n } catch {\n // Transient status-read error: the signature is already broadcast, so\n // keep polling rather than surface this as an unsigned failure.\n status = null\n }\n if (status === 'failed') {\n throw new BridgeError(`Solana Hyperlane transfer failed on-chain: ${signature}`)\n }\n if (status === 'confirmed' || status === 'finalized') return status\n try {\n if (!await rpc.isBlockhashValid(blockhash)) return 'expired'\n } catch {\n // A blockhash-validity read is advisory while the signature may still land.\n }\n if (Date.now() >= deadline) return undefined\n await new Promise<void>((resolve) => setTimeout(resolve, pollingIntervalMs))\n } while (true)\n}\n\nfunction buildReceipt(\n status: Extract<BridgeReceipt['status'], 'SOURCE_CONFIRMING' | 'DELIVERY_PENDING'>,\n signature: string,\n routeId: string,\n metadata: SolanaHyperlaneRouteMetadata,\n uniqueMessageAddress: string,\n quote: SolanaHyperlaneTransferQuote,\n blockhash: string,\n lastValidBlockHeight: bigint,\n messageId?: string,\n blockhashExpired = false,\n): BridgeReceipt {\n return {\n id: messageId ?? signature,\n protocol: 'hyperlane',\n status,\n sourceTxId: signature,\n ...(messageId ? { messageId } : {}),\n protocolState: {\n routeId,\n signature,\n uniqueMessageAddress,\n destinationDomain: metadata.destinationDomain,\n quotedLamports: quote.totalLamports.toString(),\n blockhash,\n lastValidBlockHeight: lastValidBlockHeight.toString(),\n ...(blockhashExpired ? { blockhashExpired: true } : {}),\n // The transaction confirmed but the Mailbox dispatch log line was\n // absent or unparsable — note it rather than throwing.\n ...(status === 'DELIVERY_PENDING' && !messageId ? { messageIdUnavailable: true } : {}),\n },\n }\n}\n\n/**\n * Checks whether one submitted Solana Hyperlane source transaction has committed funds.\n *\n * A pending signature leaves the state unchanged. A successful transaction\n * advances to destination delivery and records the canonical Hyperlane message\n * identifier when its log is available. No signature or submission occurs.\n *\n * @param client Solana network access used to read signature status and transaction logs.\n * @param receipt Latest state containing the submitted Solana signature.\n * @returns Unchanged source confirmation state or state ready to follow destination delivery.\n * @throws BridgeError When the saved state is invalid or Solana reports that the transaction failed.\n * @example const next = await getSourceStatus(client, receipt)\n */\nexport async function getSourceStatus(\n client: SolanaClient,\n receipt: BridgeReceipt,\n): Promise<BridgeReceipt> {\n if (receipt.protocol !== 'hyperlane' || receipt.status !== 'SOURCE_CONFIRMING' || !receipt.sourceTxId) {\n throw new BridgeError('Solana Hyperlane source status requires a source-confirming receipt')\n }\n const status = await client.publicClient.getSignatureStatus(receipt.sourceTxId)\n if (status == null) {\n const { blockhash, lastValidBlockHeight } = receipt.protocolState\n if (blockhash === undefined && lastValidBlockHeight === undefined) return receipt\n if (typeof blockhash !== 'string' || !blockhash\n || typeof lastValidBlockHeight !== 'string' || !/^\\d+$/.test(lastValidBlockHeight)) {\n throw new BridgeError('Solana Hyperlane source receipt has an invalid blockhash lifetime')\n }\n try {\n if (!await client.publicClient.isBlockhashValid(blockhash)) {\n return {\n ...receipt,\n status: 'EXPIRED',\n protocolState: {\n ...receipt.protocolState,\n blockhashExpired: true,\n sourceError: `Solana transaction expired before confirmation: ${receipt.sourceTxId}`,\n },\n }\n }\n } catch {\n return receipt\n }\n return receipt\n }\n if (status === 'processed') return receipt\n if (status === 'failed') throw new BridgeError(`Solana Hyperlane transfer failed on-chain: ${receipt.sourceTxId}`)\n // Confirmation proves the source instruction committed. The Mailbox log is\n // then the canonical source of the message id used for destination delivery.\n const messageId = extractSolanaHyperlaneMessageId(await client.publicClient.getTransactionLogs(receipt.sourceTxId))\n return {\n ...receipt,\n id: messageId ?? receipt.sourceTxId,\n status: 'DELIVERY_PENDING',\n ...(messageId ? { messageId } : {}),\n protocolState: {\n ...receipt.protocolState,\n ...(!messageId ? { messageIdUnavailable: true } : {}),\n },\n }\n}\n\n/**\n * Begins a Solana-to-Aleo Hyperlane transfer by committing SOL on Solana.\n *\n * The source account must cover the transfer, relayer payment, network fee, and\n * account rent while retaining its own rent-exempt floor. The connected wallet\n * MUST match any sender chosen earlier. After broadcast, a confirmation timeout\n * remains pending because the transaction may still land; it is not reported as\n * a failed transfer.\n *\n * @param registry Supported assets and reviewed Hyperlane deployments.\n * @param client Solana network and wallet access used to read, sign, and submit.\n * @param params Route, amount, Aleo recipient, confirmation controls, and optional recovery callback.\n * @returns The source signature and state needed to follow source confirmation or destination delivery.\n * @throws BridgeError When the route is unavailable, the wallet account differs from the selected sender, funds are insufficient, authorization fails, or Solana reports failure.\n *\n * @example\n * const execution = await execute(registry, client, { plan })\n */\nexport async function execute(\n registry: BridgeRegistry,\n client: SolanaClient & { walletClient: SolanaWalletClient },\n params: ExecuteSolanaHyperlaneTransferParameters,\n): Promise<SolanaHyperlaneTransferExecution> {\n const rpc = client.publicClient\n const walletClient = client.walletClient\n const requestedPollingIntervalMs = params.pollingIntervalMs ?? 1_000\n const confirmationTimeoutMs = params.confirmationTimeoutMs ?? 120_000\n if (!Number.isFinite(requestedPollingIntervalMs) || requestedPollingIntervalMs < 0) {\n throw new BridgeError('pollingIntervalMs must be a non-negative finite number')\n }\n if (!Number.isFinite(confirmationTimeoutMs) || confirmationTimeoutMs < 0) {\n throw new BridgeError('confirmationTimeoutMs must be a non-negative finite number')\n }\n // Floor the effective interval so a caller-supplied 0 (or another very\n // small value) does not busy-poll the RPC endpoint.\n const pollingIntervalMs = Math.max(requestedPollingIntervalMs, 100)\n\n // 1. Validate the route.\n const metadata = solanaRouteMetadata(registry, params.plan)\n\n // A persisted source receipt represents an already-broadcast transaction.\n // Resume by observing that signature only; never quote, sign, or submit it again.\n if (params.resume) {\n const receipt = params.resume\n const state = receipt.protocolState\n if (receipt.protocol !== 'hyperlane'\n || (receipt.status !== 'SOURCE_CONFIRMING' && receipt.status !== 'DELIVERY_PENDING')\n || typeof receipt.sourceTxId !== 'string'\n || state.routeId !== params.plan.route.id\n || state.destinationDomain !== metadata.destinationDomain) {\n throw new BridgeError('Solana Hyperlane resume receipt does not match the prepared route')\n }\n if (receipt.status === 'DELIVERY_PENDING' || state.blockhashExpired === true) {\n return { receipt }\n }\n if (typeof state.blockhash !== 'string'\n || typeof state.lastValidBlockHeight !== 'string'\n || !/^\\d+$/.test(state.lastValidBlockHeight)) {\n throw new BridgeError('Solana Hyperlane resume receipt is missing its blockhash lifetime')\n }\n const signature = receipt.sourceTxId\n try {\n const confirmation = await pollForConfirmation(\n client.publicClient,\n signature,\n pollingIntervalMs,\n confirmationTimeoutMs,\n state.blockhash,\n )\n if (!confirmation) return { receipt }\n if (confirmation === 'expired') {\n return { receipt: { ...receipt, protocolState: { ...state, blockhashExpired: true } } }\n }\n const messageId = extractSolanaHyperlaneMessageId(await client.publicClient.getTransactionLogs(signature))\n return {\n receipt: {\n ...receipt,\n id: messageId ?? signature,\n status: 'DELIVERY_PENDING',\n ...(messageId ? { messageId } : {}),\n protocolState: {\n ...state,\n ...(!messageId ? { messageIdUnavailable: true } : {}),\n },\n },\n }\n } catch (error) {\n if (error instanceof BridgeError && error.message.includes(signature)) throw error\n const message = error instanceof Error ? error.message : String(error)\n throw new BridgeError(`Solana Hyperlane transfer ${signature} was submitted, but confirmation failed: ${message}`)\n }\n }\n\n // 2. Resolve the fee payer and refuse to execute a plan prepared for a\n // different account, before any network read. Solana addresses are\n // case-sensitive base58, so an exact string comparison is the equality check.\n const senderAddress = await walletClient.getAddress()\n if (params.plan.sender && params.plan.sender !== senderAddress) {\n throw new BridgeError(`Prepared sender ${params.plan.sender} does not match connected account ${senderAddress}`)\n }\n\n // 3. Quote the live IGP payment through the shared oracle-reading action.\n const transferQuote = await quote(registry, client, { plan: { ...params.plan, sender: senderAddress } })\n\n // 4. Preflight: the sender must cover the amount, gas, and the rent for\n // the two accounts (gas-payment PDA, dispatched-message PDA) the\n // instruction creates fresh, and must still clear its own rent-exempt\n // floor once every one of those lamports has left it.\n const requiredLamports = transferQuote.totalLamports\n const balance = await rpc.getBalance(senderAddress)\n if (balance < requiredLamports) {\n throw new BridgeError(\n `Insufficient Solana balance for this Hyperlane transfer: balance ${balance} lamports, `\n + `required ${requiredLamports} lamports (amount ${transferQuote.amountLamports} `\n + `+ gas ${transferQuote.igpPaymentLamports + transferQuote.networkFeeLamports} + rent ${transferQuote.rentLamports})`,\n )\n }\n\n // 5. Generate the ephemeral unique-message signer that seeds the\n // dispatched-message and gas-payment program-derived addresses.\n const kit = await loadKit()\n const uniqueMessageSigner = await kit.generateKeyPairSigner()\n\n // 6. Build the instruction and assemble, compile, and partially sign the\n // v0 transaction; the fee payer's signature is added later by the wallet client.\n const built = await buildTransferRemoteInstruction({\n metadata,\n senderAddress,\n uniqueMessageAddress: uniqueMessageSigner.address,\n recipientAleoAddress: params.plan.recipient,\n amountLamports: transferQuote.amountLamports,\n })\n const instruction = {\n programAddress: kit.address(built.programAddress),\n accounts: built.accounts.map((account) => ({\n address: kit.address(account.address),\n role: accountRole(kit, account),\n })),\n data: built.data,\n }\n const { blockhash, lastValidBlockHeight } = await rpc.getLatestBlockhash()\n const message = kit.pipe(\n kit.createTransactionMessage({ version: 0 }),\n (tx) => kit.setTransactionMessageFeePayer(kit.address(senderAddress), tx),\n (tx) => kit.setTransactionMessageLifetimeUsingBlockhash(\n { blockhash: kit.blockhash(blockhash), lastValidBlockHeight },\n tx,\n ),\n (tx) => kit.setTransactionMessageComputeUnitLimit(SOLANA_HYPERLANE_COMPUTE_UNIT_LIMIT, tx),\n (tx) => kit.appendTransactionMessageInstruction(instruction, tx),\n )\n const compiledTransaction = kit.compileTransaction(message)\n const signedTransaction = await kit.partiallySignTransaction(\n [uniqueMessageSigner.keyPair],\n compiledTransaction,\n )\n const wireTransaction = new Uint8Array(kit.getTransactionEncoder().encode(signedTransaction))\n\n // 7. Hand the partially signed transaction to the wallet client, which adds the\n // fee payer's signature and submits it.\n const { signature } = await walletClient.sendTransaction(wireTransaction)\n const submittedReceipt = buildReceipt(\n 'SOURCE_CONFIRMING',\n signature,\n params.plan.route.id,\n metadata,\n uniqueMessageSigner.address,\n transferQuote,\n blockhash,\n lastValidBlockHeight,\n )\n await params.onSubmitted?.(submittedReceipt)\n\n // Once broadcast, the transaction is out of this action's hands — any\n // error surfaced from here on must still name the signature, so a caller\n // (or an operator reading logs) can look it up rather than lose track of\n // an already-submitted transfer.\n try {\n // 8. Poll for confirmation; a timeout returns a resumable pending receipt\n // rather than throwing, since the transaction may still land.\n const confirmation = await pollForConfirmation(rpc, signature, pollingIntervalMs, confirmationTimeoutMs, blockhash)\n if (!confirmation) {\n return {\n receipt: submittedReceipt,\n }\n }\n if (confirmation === 'expired') {\n return {\n receipt: buildReceipt('SOURCE_CONFIRMING', signature, params.plan.route.id, metadata, uniqueMessageSigner.address, transferQuote, blockhash, lastValidBlockHeight, undefined, true),\n }\n }\n\n // 9. Extract the Hyperlane message id from the Mailbox dispatch log line.\n // Its absence does not throw — the receipt keeps the signature and leaves\n // `messageId` undefined.\n const logs = await rpc.getTransactionLogs(signature)\n const messageId = extractSolanaHyperlaneMessageId(logs)\n\n // 10. Return the resumable, protocol-neutral receipt.\n return {\n receipt: buildReceipt('DELIVERY_PENDING', signature, params.plan.route.id, metadata, uniqueMessageSigner.address, transferQuote, blockhash, lastValidBlockHeight, messageId),\n }\n } catch (error) {\n if (error instanceof BridgeError && error.message.includes(signature)) throw error\n const message = error instanceof Error ? error.message : String(error)\n throw new BridgeError(`Solana Hyperlane transfer ${signature} failed after broadcast: ${message}`, { cause: error })\n }\n}\n","import type { TransactionInput } from '@provablehq/veil-core'\nimport { BridgeError } from '../../errors/bridgeErrors.js'\nimport type {\n AleoWalletClient,\n ExecuteXReserveBurnParameters,\n XReserveBurnCall,\n XReserveBurnExecution,\n} from '../../types/aleo.js'\nimport type { BridgeRegistry, BridgeReceipt } from '../../types/protocol.js'\nimport { formatDecimalAmount, parseDecimalAmount } from '../../utils/units.js'\nimport { evmAddressToXReserveBytes32, xReserveHexToAleoBytes } from '../../utils/xreserve.js'\n\nconst ETHEREUM_DESTINATION_DOMAIN = 0\n\nfunction validatedRoute(registry: BridgeRegistry, params: ExecuteXReserveBurnParameters) {\n const { plan } = params\n if (plan.protocol !== 'xreserve' || plan.route.protocol !== 'xreserve') throw new BridgeError('USDCx burn requires an xReserve transfer plan')\n if (plan.registryVersion !== registry.version) throw new BridgeError(`Transfer plan uses registry ${plan.registryVersion}; expected ${registry.version}`)\n // Resolve programs, token metadata, domain, and fee from the current reviewed\n // registry. The saved transfer identifies the route but cannot replace a\n // current deployment review.\n const route = registry.routes.find((entry) => entry.id === plan.route.id)\n if (!route || route.protocol !== 'xreserve' || route.availability !== 'active') throw new BridgeError(`xReserve route is not executable: ${plan.route.id}`)\n const sourceChain = registry.chains.find((chain) => chain.id === plan.sourceAsset.chainId)\n const destinationChain = registry.chains.find((chain) => chain.id === plan.destinationAsset.chainId)\n if (sourceChain?.family !== 'aleo' || destinationChain?.family !== 'evm') throw new BridgeError('USDCx burn action requires an Aleo-to-Ethereum route')\n if (route.sourceAssetId !== plan.sourceAsset.id || route.destinationAssetId !== plan.destinationAsset.id) throw new BridgeError(`Transfer plan assets do not match configured route: ${route.id}`)\n const bridgeProgram = route.metadata?.bridgeProgram\n const wrapperProgram = route.metadata?.wrapperProgram\n const tokenProgram = route.metadata?.remoteToken\n const nativeDomain = route.metadata?.ethereumDestinationDomain\n const withdrawalFee = route.metadata?.withdrawalFeeAtomic\n if (typeof bridgeProgram !== 'string' || !bridgeProgram.endsWith('.aleo')) throw new BridgeError(`xReserve bridge program is invalid: ${route.id}`)\n if (typeof wrapperProgram !== 'string' || !wrapperProgram.endsWith('.aleo')) throw new BridgeError(`xReserve wrapper program is invalid: ${route.id}`)\n if (typeof tokenProgram !== 'string' || !tokenProgram.endsWith('.aleo')) throw new BridgeError(`xReserve token program is invalid: ${route.id}`)\n if (typeof withdrawalFee !== 'string' || !/^\\d+$/.test(withdrawalFee)) throw new BridgeError(`xReserve withdrawal fee is invalid: ${route.id}`)\n if (nativeDomain !== ETHEREUM_DESTINATION_DOMAIN) throw new BridgeError(`xReserve Ethereum destination domain must be ${ETHEREUM_DESTINATION_DOMAIN}: ${route.id}`)\n return { route, bridgeProgram, wrapperProgram, tokenProgram, nativeDomain, withdrawalFeeAtomic: BigInt(withdrawalFee) }\n}\n\nfunction assertPrivateInputs(userRecord: TransactionInput | undefined, merkleProof: string | undefined, tokenProgram: string): asserts userRecord is TransactionInput {\n // A structured request lets a compatible wallet select the record without\n // exposing plaintext to the application. A literal record remains supported\n // for local accounts and wallets that do not implement record selection.\n if (userRecord == null) throw new BridgeError('private_burn requires a USDCx userRecord input')\n if (typeof userRecord === 'object') {\n if (userRecord.type !== 'record' || userRecord.program !== tokenProgram || userRecord.recordname !== 'Token') {\n throw new BridgeError(`private_burn record requests must select ${tokenProgram}/Token`)\n }\n }\n if (typeof merkleProof !== 'string' || !merkleProof.startsWith('[') || !merkleProof.endsWith(']')) {\n throw new BridgeError('private_burn requires an encoded [MerkleProof; 2] Aleo literal')\n }\n}\n\n/**\n * Builds the Aleo program call that begins a USDCx-to-USDC xReserve transfer.\n *\n * The result lets an application inspect the source program, public or private\n * funding mode, amount, withdrawal fee, and Ethereum recipient before a wallet\n * is involved. It does not contact Aleo, request a signature, or move funds.\n * Pauses, frozen accounts, and burn limits remain enforced by the source program\n * when the call is eventually submitted.\n *\n * @param registry Supported assets and reviewed xReserve deployments.\n * @param params Route, amount, Ethereum recipient, public or private funding preference, and private record proof when applicable.\n * @returns Exact Aleo program, transition, ordered inputs, atomic amount, destination domain, and encoded recipient.\n * @throws BridgeError When the route is unavailable, the amount cannot cover the withdrawal fee, the recipient is invalid, or private funding inputs are missing.\n *\n * @example\n * const call = buildBurnCall(registry, { plan, mode: 'public-as-signer' })\n */\nexport function buildBurnCall(\n registry: BridgeRegistry,\n params: ExecuteXReserveBurnParameters,\n): XReserveBurnCall {\n const deployment = validatedRoute(registry, params)\n const mode = params.mode ?? 'private'\n if (mode !== 'public-as-signer' && mode !== 'public' && mode !== 'private') throw new BridgeError(`Unsupported USDCx burn mode: ${String(mode)}`)\n const amountAtomic = parseDecimalAmount(params.plan.amountIn, params.plan.sourceAsset.decimals)\n if (amountAtomic <= 0n) throw new BridgeError('USDCx burn amount must be greater than zero')\n if (amountAtomic <= deployment.withdrawalFeeAtomic) {\n const fee = formatDecimalAmount(deployment.withdrawalFeeAtomic, params.plan.sourceAsset.decimals)\n throw new BridgeError(`USDCx burn amount must exceed the ${fee} ${params.plan.sourceAsset.symbol} withdrawal fee`)\n }\n // Circle domains use a 32-byte recipient. Ethereum addresses occupy the low\n // 20 bytes and are left-padded with twelve zero bytes.\n const nativeRecipientBytes32 = evmAddressToXReserveBytes32(params.plan.recipient)\n const amount = `${amountAtomic}u128`\n const nativeDomain = `${deployment.nativeDomain}u32`\n const nativeRecipient = xReserveHexToAleoBytes(nativeRecipientBytes32, 32)\n\n if (mode === 'private') {\n // Private USDCx lives in the wrapper's Token record and requires the\n // freeze-list witness expected by private_burn.\n assertPrivateInputs(params.userRecord, params.merkleProof, deployment.tokenProgram)\n return {\n routeId: deployment.route.id,\n mode,\n program: deployment.wrapperProgram,\n function: 'private_burn',\n inputs: [params.userRecord, amount, nativeDomain, nativeRecipient, params.merkleProof!],\n amountAtomic,\n nativeDomain: deployment.nativeDomain,\n nativeRecipientBytes32,\n }\n }\n\n // Public balance funding uses the bridge program directly. The signer-bound\n // variant debits the connected account; `public` accepts the program's\n // explicit public-owner semantics.\n return {\n routeId: deployment.route.id,\n mode,\n program: deployment.bridgeProgram,\n function: mode === 'public' ? 'burn_public' : 'burn_public_as_signer',\n inputs: [amount, nativeDomain, nativeRecipient],\n amountAtomic,\n nativeDomain: deployment.nativeDomain,\n nativeRecipientBytes32,\n }\n}\n\n/**\n * Begins a USDCx-to-USDC transfer by burning USDCx on Aleo.\n *\n * The Aleo wallet proves, signs, and broadcasts the source burn, which commits\n * USDCx and incurs an Aleo transaction fee. After acceptance, the Aleo burn\n * attestation service forwards the withdrawal to Circle; no destination wallet\n * authorization is required.\n *\n * @param registry Supported assets and reviewed xReserve deployments.\n * @param client Aleo wallet that proves, signs, and broadcasts the source burn.\n * @param params Route, amount, Ethereum recipient, public or private funding preference, fee preference, and recovery callbacks.\n * @returns The Aleo transaction identifier and state needed to follow provider-managed delivery.\n * @throws BridgeError When the burn inputs are invalid or wallet submission fails.\n *\n * @example\n * const burn = await execute(registry, client, {\n * plan,\n * userRecord,\n * merkleProof,\n * })\n */\nexport async function execute(\n registry: BridgeRegistry,\n client: AleoWalletClient,\n params: ExecuteXReserveBurnParameters,\n): Promise<XReserveBurnExecution> {\n const call = buildBurnCall(registry, params)\n // Aleo wallets may finish proving before broadcasting. Forward that prepared\n // transaction so an application can persist the exact bytes and recover the\n // crash window without proving or burning again.\n const transactionId = await client.executeTransaction({\n program: call.program,\n function: call.function,\n inputs: call.inputs,\n privateFee: params.privateFee ?? false,\n onProgress: async (event) => {\n await params.onProgress?.(event)\n if (event.type === 'transaction-prepared') await params.onPrepared?.(event.transaction)\n },\n })\n if (!transactionId) throw new BridgeError('Aleo wallet returned an empty burn transaction id')\n // Source acceptance completes caller-authorized work. The public transaction\n // id is sufficient for the burn attestation service and Circle to continue\n // Ethereum delivery without an EVM wallet.\n const receipt: BridgeReceipt = {\n id: transactionId,\n protocol: 'xreserve',\n status: 'SOURCE_CONFIRMING',\n sourceTxId: transactionId,\n protocolState: {\n routeId: call.routeId,\n burnMode: call.mode,\n amountAtomic: call.amountAtomic.toString(),\n nativeDomain: call.nativeDomain,\n nativeRecipientBytes32: call.nativeRecipientBytes32,\n sourceProgram: call.program,\n sourceFunction: call.function,\n forwardingService: 'aleo-burn-attestation',\n },\n }\n await params.onSubmitted?.(receipt)\n return { transactionId, receipt }\n}\n","import {\n decodeEventLog,\n decodeFunctionResult,\n encodeFunctionData,\n getAddress,\n isAddress,\n isHash,\n isHex,\n parseAbi,\n type Address,\n type Hash,\n type Hex,\n} from 'viem'\nimport { BridgeError } from '../../errors/bridgeErrors.js'\nimport type { EvmClient, EvmReceipt, EvmWalletClient } from '../../connections/evm.js'\nimport type {\n AleoWalletClient,\n ExecuteXReservePrivateMintParameters,\n XReservePrivateMintExecution,\n} from '../../types/aleo.js'\nimport type { BridgeCheckpoint, BridgeRegistry, BridgePlan, BridgeReceipt } from '../../types/protocol.js'\nimport type {\n EvmXReserveRouteMetadata,\n EvmXReserveTransferExecution,\n EvmXReserveTransferQuote,\n ExecuteEvmXReserveTransferParameters,\n GetXReserveAttestationParameters,\n QuoteEvmXReserveTransferParameters,\n XReserveAttestationResult,\n XReserveHttpTransport,\n} from '../../types/xreserve.js'\nimport { parseDecimalAmount } from '../../utils/units.js'\nimport {\n aleoAddressToBytes32,\n aleoProgramAddress,\n buildXReserveDepositPayload,\n buildXReserveHookData,\n calculateXReserveDepositNonce,\n calculateXReserveMessageHash,\n xReserveHexToAleoBytes,\n} from '../../utils/xreserve.js'\n\nconst ERC20_ABI = parseAbi([\n 'function balanceOf(address owner) view returns (uint256)',\n 'function allowance(address owner, address spender) view returns (uint256)',\n 'function approve(address spender, uint256 amount) returns (bool)',\n])\nconst XRESERVE_ABI = parseAbi([\n 'function depositToRemote(uint256 value, uint32 remoteDomain, bytes32 remoteRecipient, address localToken, uint256 maxFee, bytes hookData)',\n 'event DepositedToRemote(address indexed localToken, uint256 value, address indexed localDepositor, bytes32 indexed remoteRecipient, uint32 remoteDomain, bytes32 remoteToken, uint256 maxFee, bytes hookData)',\n])\n\nfunction metadata(registry: BridgeRegistry, plan: BridgePlan): EvmXReserveRouteMetadata {\n if (plan.protocol !== 'xreserve' || plan.route.protocol !== 'xreserve') throw new BridgeError('xReserve actions require an xReserve transfer plan')\n if (plan.registryVersion !== registry.version) throw new BridgeError(`Transfer plan uses registry ${plan.registryVersion}; expected ${registry.version}`)\n // Resolve contracts, domains, limits, and provider endpoints from the current\n // reviewed registry. A serialized plan identifies a route but is not trusted\n // as a source of deployment addresses after an application restart.\n const route = registry.routes.find((entry) => entry.id === plan.route.id)\n if (!route || route.availability !== 'active') throw new BridgeError(`xReserve route is not executable: ${plan.route.id}`)\n if (route.sourceAssetId !== plan.sourceAsset.id || route.destinationAssetId !== plan.destinationAsset.id) throw new BridgeError(`Transfer plan assets do not match configured route: ${route.id}`)\n const sourceChain = registry.chains.find((chain) => chain.id === plan.sourceAsset.chainId)\n if (sourceChain?.family !== 'evm' || plan.destinationAsset.chainId !== (route.environment === 'mainnet' ? 'aleo' : 'aleo-testnet')) {\n throw new BridgeError('This action supports Ethereum-to-Aleo xReserve deposits only')\n }\n const raw = route.metadata ?? {}\n const xReserveContract = raw.xReserveContract\n const sourceChainId = raw.sourceChainId\n const sourceDomain = raw.sourceDomain\n const remoteDomain = raw.remoteDomain\n const remoteTokenBytes32 = raw.remoteTokenBytes32\n const minimumAmountAtomic = raw.minimumAmountAtomic\n const maxFeeAtomic = raw.maxFeeAtomic\n const bridgeProgram = raw.bridgeProgram\n const wrapperProgram = raw.wrapperProgram\n const attestationBaseUrl = raw.attestationBaseUrl\n if (typeof xReserveContract !== 'string' || !isAddress(xReserveContract)) throw new BridgeError(`xReserve contract is invalid: ${route.id}`)\n if (typeof sourceChainId !== 'number' || !Number.isSafeInteger(sourceChainId) || sourceChainId <= 0) throw new BridgeError(`xReserve sourceChainId is invalid: ${route.id}`)\n if (typeof sourceDomain !== 'number' || !Number.isInteger(sourceDomain) || sourceDomain < 0) throw new BridgeError(`xReserve sourceDomain is invalid: ${route.id}`)\n if (typeof remoteDomain !== 'number' || !Number.isInteger(remoteDomain) || remoteDomain < 0) throw new BridgeError(`xReserve remoteDomain is invalid: ${route.id}`)\n if (typeof remoteTokenBytes32 !== 'string' || !/^0x[0-9a-f]{64}$/i.test(remoteTokenBytes32)) throw new BridgeError(`xReserve remote token is invalid: ${route.id}`)\n if (typeof minimumAmountAtomic !== 'string' || !/^\\d+$/.test(minimumAmountAtomic)) throw new BridgeError(`xReserve minimum amount is invalid: ${route.id}`)\n if (typeof maxFeeAtomic !== 'string' || !/^\\d+$/.test(maxFeeAtomic)) throw new BridgeError(`xReserve max fee is invalid: ${route.id}`)\n if (typeof bridgeProgram !== 'string' || !bridgeProgram.endsWith('.aleo')) throw new BridgeError(`xReserve bridge program is invalid: ${route.id}`)\n if (typeof wrapperProgram !== 'string' || !wrapperProgram.endsWith('.aleo')) throw new BridgeError(`xReserve wrapper program is invalid: ${route.id}`)\n if (typeof attestationBaseUrl !== 'string' || !attestationBaseUrl.startsWith('https://')) throw new BridgeError(`xReserve attestation URL is invalid: ${route.id}`)\n return { xReserveContract: getAddress(xReserveContract), sourceChainId, sourceDomain, remoteDomain, remoteTokenBytes32: remoteTokenBytes32 as Hex, minimumAmountAtomic: BigInt(minimumAmountAtomic), maxFeeAtomic: BigInt(maxFeeAtomic), bridgeProgram, wrapperProgram, attestationBaseUrl }\n}\n\nasync function assertChain(client: EvmClient, expected: number): Promise<void> {\n const chain = await client.publicClient.getChainId()\n if (chain !== expected) throw new BridgeError(`EVM client is connected to chain ${chain}; expected ${expected}`)\n}\n\nasync function observedAccount(client: EvmClient, plan: BridgePlan, receipt?: BridgeReceipt): Promise<Address> {\n // Recovery can run with network access alone. Prefer the sender committed to\n // the receipt or plan so checking a past transfer never prompts a wallet.\n const saved = receipt?.protocolState.sourceSender\n const candidate = typeof saved === 'string' ? saved : plan.sender\n if (candidate && isAddress(candidate)) return getAddress(candidate)\n if (client.walletClient) return account(client as EvmClient & { walletClient: EvmWalletClient }, plan)\n throw new BridgeError('Read-only EVM access requires the prepared sender address')\n}\n\nasync function account(client: EvmClient & { walletClient: EvmWalletClient }, plan: BridgePlan): Promise<Address> {\n const value = await client.walletClient.getAddress()\n if (typeof value !== 'string' || !isAddress(value)) throw new BridgeError('EVM wallet client has no connected account')\n const resolved = getAddress(value)\n if (plan.sender && (!isAddress(plan.sender) || getAddress(plan.sender) !== resolved)) throw new BridgeError(`Prepared sender ${plan.sender} does not match connected account ${resolved}`)\n return resolved\n}\n\n/** Reads one unsigned integer from the USDC contract and rejects malformed RPC data before it can influence authorization. */\nasync function callUint(client: EvmClient, to: Address, data: Hex, functionName: 'balanceOf' | 'allowance'): Promise<bigint> {\n const result = await client.publicClient.call({ to, data })\n if (typeof result !== 'string' || !isHex(result)) throw new BridgeError('EVM public client returned an invalid contract result')\n return decodeFunctionResult({ abi: ERC20_ABI, functionName, data: result })\n}\n\n/** Submits one EVM transaction after binding the requested chain and sender to the connected wallet. */\nasync function send(client: EvmClient & { walletClient: EvmWalletClient }, chainId: number, transaction: { from: Address, to: Address, data: Hex }): Promise<Hash> {\n const hash = await client.walletClient.sendTransaction({ chainId, ...transaction })\n if (typeof hash !== 'string' || !isHash(hash)) throw new BridgeError('EVM wallet client returned an invalid transaction hash')\n return hash\n}\n\n/** Polls an already-submitted EVM transaction. A timeout remains unknown because the transaction may still land. */\nasync function wait(client: EvmClient & { walletClient: EvmWalletClient }, hash: Hash, timeout: number, interval: number): Promise<EvmReceipt | undefined> {\n const deadline = Date.now() + timeout\n do {\n const result = await client.publicClient.getTransactionReceipt(hash)\n if (result && typeof result === 'object') return result\n if (Date.now() >= deadline) return undefined\n await new Promise<void>((resolve) => setTimeout(resolve, interval))\n } while (true)\n}\n\n/** Turns a confirmed EVM revert into a terminal bridge error while accepting any successful receipt representation. */\nfunction successful(receipt: EvmReceipt, hash: Hash): void {\n if (receipt.status === 'reverted') throw new BridgeError(`EVM transaction reverted: ${hash}`)\n}\n\n/**\n * Calculates the USDC and approval required for an Ethereum-to-Aleo xReserve deposit.\n *\n * The result includes the source account's balance, current xReserve\n * allowance, maximum provider fee, and the Aleo delivery instruction committed\n * by the deposit. It reads Ethereum but does not request a signature or move funds.\n *\n * @param registry Supported assets and reviewed xReserve deployments.\n * @param client Ethereum network access, plus a wallet when the plan does not identify the source account.\n * @param params Route, amount, Aleo recipient, privacy preference, and private mint secret when applicable.\n * @returns Deposit amount, maximum provider fee, balance, allowance, delivery instruction, and whether approval is required.\n * @throws BridgeError When the route is unavailable, the client uses the wrong chain or account, funds are insufficient, or the Aleo recipient is invalid.\n *\n * @example\n * const result = await quote(registry, client, { plan })\n */\nexport async function quote(\n registry: BridgeRegistry,\n client: EvmClient,\n params: QuoteEvmXReserveTransferParameters,\n): Promise<EvmXReserveTransferQuote> {\n const route = metadata(registry, params.plan)\n await assertChain(client, route.sourceChainId)\n const owner = await observedAccount(client, params.plan)\n const token = params.plan.sourceAsset.locator?.value\n if (params.plan.sourceAsset.locator?.kind !== 'evm-contract' || !token || !isAddress(token)) throw new BridgeError('xReserve source token contract is missing')\n const amountAtomic = parseDecimalAmount(params.plan.amountIn, params.plan.sourceAsset.decimals)\n if (amountAtomic < route.minimumAmountAtomic) throw new BridgeError(`xReserve minimum deposit is ${route.minimumAmountAtomic} atomic units`)\n const environment = params.plan.route.environment\n // Hook data tells the Aleo side whether Circle may mint publicly on arrival\n // or must wait for the recipient to reveal a secret and authorize private_mint.\n const hookData = await buildXReserveHookData(\n params.plan.mintMode,\n params.plan.recipient,\n environment,\n params.privateMintSecretNonce ?? '0scalar',\n )\n const recipient = params.plan.mintMode === 'private'\n ? await aleoProgramAddress(route.wrapperProgram, environment)\n : params.plan.recipient\n // Private deposits target the wrapper program, which holds the attested mint\n // until the intended recipient supplies the secret. Public deposits target\n // the recipient address directly.\n const remoteRecipientBytes32 = aleoAddressToBytes32(recipient)\n const balanceData = encodeFunctionData({ abi: ERC20_ABI, functionName: 'balanceOf', args: [owner] })\n const allowanceData = encodeFunctionData({ abi: ERC20_ABI, functionName: 'allowance', args: [owner, route.xReserveContract] })\n // Balance and allowance describe the same account at approximately the same\n // block. Read them together to reduce quote latency without changing state.\n const [balanceAtomic, allowanceAtomic] = await Promise.all([\n callUint(client, getAddress(token), balanceData, 'balanceOf'),\n callUint(client, getAddress(token), allowanceData, 'allowance'),\n ])\n if (balanceAtomic < amountAtomic) throw new BridgeError(`Insufficient ${params.plan.sourceAsset.symbol} balance`)\n return { routeId: params.plan.route.id, xReserveContract: route.xReserveContract, tokenAddress: getAddress(token), sourceChainId: route.sourceChainId, remoteDomain: route.remoteDomain, remoteRecipientBytes32, amountAtomic, maxFeeAtomic: route.maxFeeAtomic, hookData, balanceAtomic, allowanceAtomic, approvalRequired: allowanceAtomic < amountAtomic }\n}\n\n/** Captures every value that determines an xReserve deposit so later recovery can verify rather than reconstruct the submitted call. */\nfunction pendingReceipt(plan: BridgePlan, status: BridgeReceipt['status'], id: string, approvalTxIds: Hash[], quote: EvmXReserveTransferQuote, sourceSender: Address, sourceTxId?: Hash): BridgeReceipt {\n return { id, protocol: 'xreserve', status, ...(sourceTxId ? { sourceTxId } : {}), protocolState: { routeId: plan.route.id, approvalTxIds, sourceSender, mintMode: plan.mintMode, intendedRecipient: plan.recipient, xReserveContract: quote.xReserveContract, tokenAddress: quote.tokenAddress, sourceChainId: quote.sourceChainId, remoteDomain: quote.remoteDomain, remoteRecipientBytes32: quote.remoteRecipientBytes32, hookData: quote.hookData, amountAtomic: quote.amountAtomic.toString(), maxFeeAtomic: quote.maxFeeAtomic.toString() } }\n}\n\n/** Rebuilds the deposit arguments from saved state and binds them to the current transfer before any transaction is observed or submitted. */\nfunction resumeQuote(plan: BridgePlan, receipt: BridgeReceipt): EvmXReserveTransferQuote {\n const state = receipt.protocolState\n if (receipt.protocol !== 'xreserve' || state.routeId !== plan.route.id) {\n throw new BridgeError('Checkpoint does not match the prepared xReserve route')\n }\n if (state.mintMode !== plan.mintMode || state.intendedRecipient !== plan.recipient) {\n throw new BridgeError('Checkpoint does not match the prepared xReserve recipient')\n }\n if (typeof state.xReserveContract !== 'string' || !isAddress(state.xReserveContract)\n || typeof state.tokenAddress !== 'string' || !isAddress(state.tokenAddress)\n || typeof state.sourceChainId !== 'number' || typeof state.remoteDomain !== 'number'\n || typeof state.remoteRecipientBytes32 !== 'string' || !isHex(state.remoteRecipientBytes32)\n || typeof state.hookData !== 'string' || !isHex(state.hookData)\n || typeof state.amountAtomic !== 'string' || !/^\\d+$/.test(state.amountAtomic)\n || typeof state.maxFeeAtomic !== 'string' || !/^\\d+$/.test(state.maxFeeAtomic)) {\n throw new BridgeError('Checkpoint contains invalid xReserve submission state')\n }\n return {\n routeId: plan.route.id,\n xReserveContract: getAddress(state.xReserveContract),\n tokenAddress: getAddress(state.tokenAddress),\n sourceChainId: state.sourceChainId,\n remoteDomain: state.remoteDomain,\n remoteRecipientBytes32: state.remoteRecipientBytes32,\n amountAtomic: BigInt(state.amountAtomic),\n maxFeeAtomic: BigInt(state.maxFeeAtomic),\n hookData: state.hookData,\n balanceAtomic: 0n,\n allowanceAtomic: 0n,\n approvalRequired: false,\n }\n}\n\n/** Returns only well-formed approval transaction hashes from application-controlled recovery state. */\nfunction approvalIds(receipt: BridgeReceipt): Hash[] {\n const ids = receipt.protocolState.approvalTxIds\n if (!Array.isArray(ids) || ids.some((id) => typeof id !== 'string' || !isHash(id))) {\n throw new BridgeError('Checkpoint contains invalid xReserve approval transaction ids')\n }\n return ids as Hash[]\n}\n\n/** Verifies the source deposit event and derives the exact Circle attestation lookup key from its canonical fields. */\nfunction confirmedDepositReceipt(\n plan: BridgePlan,\n route: EvmXReserveRouteMetadata,\n quote: EvmXReserveTransferQuote,\n owner: Address,\n approvalTxIds: Hash[],\n sourceTxId: Hash,\n receipt: EvmReceipt,\n): BridgeReceipt {\n successful(receipt, sourceTxId)\n let matched: { log: NonNullable<EvmReceipt['logs']>[number], args: {\n localToken: Address\n value: bigint\n localDepositor: Address\n remoteRecipient: Hex\n remoteDomain: number\n remoteToken: Hex\n maxFee: bigint\n hookData: Hex\n } } | undefined\n for (const log of receipt.logs ?? []) {\n if (log.address && getAddress(log.address) !== route.xReserveContract) continue\n try {\n const decoded = decodeEventLog({ abi: XRESERVE_ABI, data: log.data, topics: log.topics as [Hex, ...Hex[]] })\n if (decoded.eventName === 'DepositedToRemote') matched = { log, args: decoded.args }\n } catch {\n // The receipt also contains ERC-20 and xReserve implementation logs.\n }\n }\n if (!matched) throw new BridgeError('Confirmed receipt does not contain a valid DepositedToRemote event')\n const { log: eventLog, args } = matched\n // A successful transaction is not enough: verify every event field against\n // the authorized deposit before trusting it as the source of an Aleo mint.\n if (getAddress(args.localToken) !== quote.tokenAddress || getAddress(args.localDepositor) !== owner || args.value !== quote.amountAtomic || args.remoteDomain !== route.remoteDomain || args.remoteRecipient.toLowerCase() !== quote.remoteRecipientBytes32.toLowerCase() || args.remoteToken.toLowerCase() !== route.remoteTokenBytes32.toLowerCase() || args.maxFee !== route.maxFeeAtomic || args.hookData.toLowerCase() !== quote.hookData.toLowerCase()) throw new BridgeError('DepositedToRemote event does not match the prepared transfer')\n const rawIndex = eventLog.logIndex\n const logIndex = typeof rawIndex === 'string' ? Number(BigInt(rawIndex)) : rawIndex\n if (!Number.isSafeInteger(logIndex) || logIndex == null || logIndex < 0) throw new BridgeError('DepositedToRemote log index is missing or invalid')\n // xReserve identifies one deposit by source domain, transaction hash, and log\n // index. The ordered payload below is the message Circle signs; its hash is\n // therefore the only safe attestation lookup identifier.\n const nonce = calculateXReserveDepositNonce(route.sourceDomain, sourceTxId, logIndex)\n const payload = buildXReserveDepositPayload({ amount: args.value, remoteDomain: args.remoteDomain, remoteToken: args.remoteToken, remoteRecipient: args.remoteRecipient, localToken: args.localToken, depositor: args.localDepositor, maxFee: args.maxFee, nonce, hookData: args.hookData })\n const messageHash = calculateXReserveMessageHash(payload)\n return { id: messageHash, protocol: 'xreserve', status: 'ATTESTATION_PENDING', sourceTxId, protocolState: { ...pendingReceipt(plan, 'ATTESTATION_PENDING', messageHash, approvalTxIds, quote, owner, sourceTxId).protocolState, sourceDomain: route.sourceDomain, remoteDomain: route.remoteDomain, depositLogIndex: logIndex, nonce, payload, messageHash, bridgeProgram: route.bridgeProgram, wrapperProgram: route.wrapperProgram } }\n}\n\n/** Finds the latest confirmed approval block without treating an unresolved hash as failed. */\nasync function approvalScanBlock(client: EvmClient, approvalTxIds: readonly Hash[]): Promise<bigint | undefined> {\n let blockNumber: bigint | undefined\n for (const approvalTxId of approvalTxIds) {\n const receipt = await client.publicClient.getTransactionReceipt(approvalTxId)\n if (!receipt) continue\n successful(receipt, approvalTxId)\n if (typeof receipt.blockNumber === 'bigint'\n && (blockNumber === undefined || receipt.blockNumber > blockNumber)) {\n blockNumber = receipt.blockNumber\n }\n }\n return blockNumber\n}\n\n/**\n * Searches only the source blocks following a known approval and accepts a\n * deposit only when every emitted field matches the saved transfer intent.\n */\nasync function recoverConfirmedDepositFromHistory(\n plan: BridgePlan,\n route: EvmXReserveRouteMetadata,\n client: EvmClient,\n quote: EvmXReserveTransferQuote,\n owner: Address,\n approvalTxIds: Hash[],\n options: { required: boolean },\n): Promise<BridgeReceipt | undefined> {\n const fromBlock = await approvalScanBlock(client, approvalTxIds)\n if (fromBlock === undefined) {\n if (options.required) {\n throw new BridgeError('Cannot safely resume xReserve because no confirmed approval block is available for source history verification')\n }\n return undefined\n }\n\n const logs = await client.publicClient.getLogs({ address: route.xReserveContract, fromBlock })\n const transactionHashes = [...new Set(logs.map((log) => log.transactionHash))]\n const matches: BridgeReceipt[] = []\n for (const transactionHash of transactionHashes) {\n const receipt = await client.publicClient.getTransactionReceipt(transactionHash)\n if (!receipt) continue\n try {\n matches.push(confirmedDepositReceipt(plan, route, quote, owner, approvalTxIds, transactionHash, receipt))\n } catch (error) {\n if (!(error instanceof BridgeError)) throw error\n // The xReserve contract emits deposits for many accounts and routes. A\n // rejected candidate is unrelated unless every canonical field matches.\n }\n }\n if (matches.length > 1) {\n throw new BridgeError('Multiple matching xReserve deposits were found; recovery cannot safely choose one source transaction')\n }\n return matches[0]\n}\n\n/**\n * Checks whether one submitted xReserve deposit has committed USDC on Ethereum.\n *\n * A pending transaction leaves the state unchanged. A successful deposit is\n * verified against its event before the Circle message and attestation lookup\n * identifier are derived. No signature or submission occurs.\n *\n * @param registry Supported assets and reviewed xReserve deployments.\n * @param client Ethereum network access used to read the transaction receipt.\n * @param plan Route, assets, amount, recipient, and privacy preference for the transfer.\n * @param receipt Latest state containing the submitted deposit transaction identifier.\n * @returns Unchanged source confirmation state or state ready for Circle attestation checks.\n * @throws BridgeError When the saved state does not match the transfer, the transaction reverted, or its deposit event differs from the intended transfer.\n * @example const next = await getSourceStatus(registry, client, plan, receipt)\n */\nexport async function getSourceStatus(\n registry: BridgeRegistry,\n client: EvmClient,\n plan: BridgePlan,\n receipt: BridgeReceipt,\n): Promise<BridgeReceipt> {\n if (receipt.status !== 'SOURCE_CONFIRMING') {\n throw new BridgeError('xReserve source status requires a source-confirming receipt')\n }\n const route = metadata(registry, plan)\n const owner = await observedAccount(client, plan, receipt)\n const transferQuote = resumeQuote(plan, receipt)\n const approvalTxIds = approvalIds(receipt)\n const sourceTxId = receipt.sourceTxId\n if (!sourceTxId || !isHash(sourceTxId)) {\n throw new BridgeError('Checkpoint is missing the xReserve source transaction id')\n }\n const sourceReceipt = await client.publicClient.getTransactionReceipt(sourceTxId)\n if (!sourceReceipt) return receipt\n return confirmedDepositReceipt(plan, route, transferQuote, owner, approvalTxIds, sourceTxId, sourceReceipt)\n}\n\n/**\n * Reconstructs an interrupted Ethereum-to-Aleo xReserve transfer from saved transaction identifiers.\n *\n * The helper checks whether the last saved USDC approval or xReserve deposit was\n * accepted. It never requests a signature or repeats a transaction. A confirmed\n * approval with no deposit means the source transfer still needs wallet\n * authorization.\n *\n * @param registry Supported assets and reviewed xReserve deployments.\n * @param client Ethereum network access used to check submitted transactions.\n * @param plan Route, assets, amount, recipient, and privacy preference reconstructed from saved information.\n * @param checkpoint Saved route, delivery instruction, and submitted transaction identifiers.\n * @returns Current source state and whether confirmation, deposit submission, or Circle attestation comes next.\n * @throws BridgeError When the saved information does not match the transfer or a submitted transaction reverted.\n * @example const receipt = await recoverSourceCheckpoint(registry, client, plan, checkpoint)\n */\nexport async function recoverSourceCheckpoint(\n registry: BridgeRegistry,\n client: EvmClient,\n plan: BridgePlan,\n checkpoint: BridgeCheckpoint,\n): Promise<BridgeReceipt> {\n if (checkpoint.version !== 1 || checkpoint.intent.bridgeProtocol !== 'xreserve' || checkpoint.route.id !== plan.route.id) {\n throw new BridgeError('Bridge checkpoint does not match the prepared route')\n }\n const route = metadata(registry, plan)\n await assertChain(client, route.sourceChainId)\n const owner = await observedAccount(client, plan)\n const token = plan.sourceAsset.locator?.value\n if (plan.sourceAsset.locator?.kind !== 'evm-contract' || !token || !isAddress(token)) {\n throw new BridgeError('xReserve source token contract is missing')\n }\n const amountAtomic = parseDecimalAmount(plan.amountIn, plan.sourceAsset.decimals)\n const storedHookData = checkpoint.source?.hookData\n if (storedHookData !== undefined && (!isHex(storedHookData, { strict: true }) || storedHookData.length !== 132)) {\n throw new BridgeError('Bridge checkpoint contains invalid xReserve hook data')\n }\n const hookData = storedHookData ?? await buildXReserveHookData(\n plan.mintMode,\n plan.recipient,\n plan.route.environment,\n '0scalar',\n )\n const recipient = plan.mintMode === 'private'\n ? await aleoProgramAddress(route.wrapperProgram, plan.route.environment)\n : plan.recipient\n const quote: EvmXReserveTransferQuote = {\n routeId: plan.route.id,\n xReserveContract: route.xReserveContract,\n tokenAddress: getAddress(token),\n sourceChainId: route.sourceChainId,\n remoteDomain: route.remoteDomain,\n remoteRecipientBytes32: aleoAddressToBytes32(recipient),\n amountAtomic,\n maxFeeAtomic: route.maxFeeAtomic,\n hookData,\n balanceAtomic: 0n,\n allowanceAtomic: 0n,\n approvalRequired: false,\n }\n const approvals = [...(checkpoint.source?.approvalTransactionIds ?? [])]\n if (approvals.some((id) => !isHash(id))) {\n throw new BridgeError('Bridge checkpoint contains an invalid approval transaction id')\n }\n const approvalTxIds = approvals as Hash[]\n\n if (!checkpoint.source?.transactionId) {\n // No source transaction means the checkpoint ended after approval\n // broadcast. Observe the latest approval, then stop before the deposit so\n // recovery itself never commits USDC to xReserve.\n const approvalTxId = approvalTxIds.at(-1)\n if (!approvalTxId) throw new BridgeError('Bridge checkpoint contains no submitted transaction')\n const pending = pendingReceipt(plan, 'SOURCE_APPROVAL_PENDING', approvalTxId, approvalTxIds, quote, owner)\n const approvalReceipt = await client.publicClient.getTransactionReceipt(approvalTxId)\n if (!approvalReceipt) return pending\n successful(approvalReceipt, approvalTxId)\n const recovered = await recoverConfirmedDepositFromHistory(\n plan,\n route,\n client,\n quote,\n owner,\n approvalTxIds,\n { required: false },\n )\n if (recovered) return recovered\n return { ...pending, status: 'SOURCE_SUBMISSION_PENDING' }\n }\n if (!isHash(checkpoint.source.transactionId)) {\n throw new BridgeError('Bridge checkpoint contains an invalid source transaction id')\n }\n const pending = pendingReceipt(\n plan,\n 'SOURCE_CONFIRMING',\n checkpoint.source.transactionId,\n approvalTxIds,\n quote,\n owner,\n checkpoint.source.transactionId,\n )\n // A saved source transaction is already the irreversible deposit. From this\n // point recovery only observes Ethereum and verifies the emitted message.\n const observed = await getSourceStatus(registry, client, plan, pending)\n if (observed !== pending) return observed\n return await recoverConfirmedDepositFromHistory(\n plan,\n route,\n client,\n quote,\n owner,\n approvalTxIds,\n { required: false },\n ) ?? observed\n}\n\n/**\n * Begins a USDC-to-USDCx transfer by committing USDC to xReserve on Ethereum.\n *\n * The wallet approves USDC only when the current allowance is too low, then\n * submits the deposit. Every submitted transaction can incur an Ethereum fee.\n * Once the deposit is accepted, Circle attestation and Aleo delivery happen in\n * later stages and the source transfer may no longer be reversible.\n *\n * @param registry Supported assets and reviewed xReserve deployments.\n * @param client Ethereum network and wallet access used to read, authorize, and submit.\n * @param params Route, amount, Aleo recipient, privacy preference, confirmation controls, and recovery callback.\n * @returns Submitted approval identifiers and state needed to follow source confirmation or Circle attestation.\n * @throws BridgeError When the route is unavailable, funds are insufficient, wallet authorization fails, a transaction reverts, or the deposit event differs from the intended transfer.\n *\n * @example\n * const execution = await execute(registry, client, { plan })\n */\nexport async function execute(\n registry: BridgeRegistry,\n client: EvmClient & { walletClient: EvmWalletClient },\n params: ExecuteEvmXReserveTransferParameters,\n): Promise<EvmXReserveTransferExecution> {\n const pollingIntervalMs = params.pollingIntervalMs ?? 1_000\n const confirmationTimeoutMs = params.confirmationTimeoutMs ?? 120_000\n if (!Number.isFinite(pollingIntervalMs) || pollingIntervalMs < 0 || !Number.isFinite(confirmationTimeoutMs) || confirmationTimeoutMs < 0) throw new BridgeError('Receipt polling controls must be non-negative finite numbers')\n const route = metadata(registry, params.plan)\n const owner = await account(client, params.plan)\n let transferQuote: EvmXReserveTransferQuote\n let approvalTxIds: Hash[] = []\n\n if (params.resume?.status === 'ATTESTATION_PENDING') {\n // Ethereum already accepted and verified the deposit. Returning the saved\n // state prevents another approval or deposit while Circle is still working.\n resumeQuote(params.plan, params.resume)\n return { approvalTxIds: approvalIds(params.resume), receipt: params.resume }\n }\n\n if (params.resume?.status === 'SOURCE_CONFIRMING') {\n // The deposit hash is known, so confirmation reads are the only permitted\n // operation in this branch.\n transferQuote = resumeQuote(params.plan, params.resume)\n approvalTxIds = approvalIds(params.resume)\n const sourceTxId = params.resume.sourceTxId\n if (!sourceTxId || !isHash(sourceTxId)) throw new BridgeError('Checkpoint is missing the xReserve source transaction id')\n const receipt = await wait(client, sourceTxId, confirmationTimeoutMs, pollingIntervalMs)\n if (!receipt) return { approvalTxIds, receipt: params.resume }\n return { approvalTxIds, receipt: confirmedDepositReceipt(params.plan, route, transferQuote, owner, approvalTxIds, sourceTxId, receipt) }\n }\n\n if (params.resume?.status === 'SOURCE_SUBMISSION_PENDING') {\n const checkpointQuote = resumeQuote(params.plan, params.resume)\n approvalTxIds = approvalIds(params.resume)\n // Recheck source history immediately before the wallet boundary. A process\n // may have broadcast the deposit before its checkpoint was saved, and the\n // resulting transaction can have a different hash than the wallet returned.\n const recovered = await recoverConfirmedDepositFromHistory(\n params.plan,\n route,\n client,\n checkpointQuote,\n owner,\n approvalTxIds,\n { required: true },\n )\n if (recovered) return { approvalTxIds, receipt: recovered }\n // A prior approval succeeded without a deposit. Re-read balance, allowance,\n // and hook data before asking the wallet to authorize the irreversible step.\n transferQuote = await quote(registry, client, params)\n if (transferQuote.hookData.toLowerCase() !== checkpointQuote.hookData.toLowerCase()) {\n throw new BridgeError('Private mint secret nonce does not match the checkpointed approval')\n }\n if (transferQuote.approvalRequired) {\n throw new BridgeError('The recovered xReserve approval allowance is no longer available. Inspect source history before starting another transfer.')\n }\n } else if (params.resume?.status === 'SOURCE_APPROVAL_PENDING') {\n resumeQuote(params.plan, params.resume)\n approvalTxIds = approvalIds(params.resume)\n const approvalTxId = params.resume.id\n if (!isHash(approvalTxId)) throw new BridgeError('Checkpoint is missing the xReserve approval transaction id')\n const receipt = await wait(client, approvalTxId, confirmationTimeoutMs, pollingIntervalMs)\n if (!receipt) return { approvalTxIds, receipt: params.resume }\n successful(receipt, approvalTxId)\n transferQuote = await quote(registry, client, params)\n } else if (params.resume) {\n throw new BridgeError(`Unsupported xReserve resume status: ${params.resume.status}`)\n } else {\n transferQuote = await quote(registry, client, params)\n }\n\n if (transferQuote.approvalRequired) {\n // Approval authorizes xReserve to spend exactly this amount but does not\n // move USDC. Persist the hash immediately because it may confirm after a\n // timeout or process failure.\n const data = encodeFunctionData({ abi: ERC20_ABI, functionName: 'approve', args: [route.xReserveContract, transferQuote.amountAtomic] })\n const hash = await send(client, route.sourceChainId, { from: owner, to: transferQuote.tokenAddress, data })\n approvalTxIds.push(hash)\n const submitted = pendingReceipt(params.plan, 'SOURCE_APPROVAL_PENDING', hash, approvalTxIds, transferQuote, owner)\n await params.onSubmitted?.(submitted)\n const receipt = await wait(client, hash, confirmationTimeoutMs, pollingIntervalMs)\n if (!receipt) return { approvalTxIds, receipt: submitted }\n successful(receipt, hash)\n }\n // depositToRemote is the irreversible source boundary: xReserve takes USDC\n // custody and commits the Aleo recipient, token, fee ceiling, and hook data.\n const data = encodeFunctionData({ abi: XRESERVE_ABI, functionName: 'depositToRemote', args: [transferQuote.amountAtomic, route.remoteDomain, transferQuote.remoteRecipientBytes32, transferQuote.tokenAddress, route.maxFeeAtomic, transferQuote.hookData] })\n const sourceTxId = await send(client, route.sourceChainId, { from: owner, to: route.xReserveContract, data })\n const submitted = pendingReceipt(params.plan, 'SOURCE_CONFIRMING', sourceTxId, approvalTxIds, transferQuote, owner, sourceTxId)\n await params.onSubmitted?.(submitted)\n const receipt = await wait(client, sourceTxId, confirmationTimeoutMs, pollingIntervalMs)\n if (!receipt) return { approvalTxIds, receipt: submitted }\n return { approvalTxIds, receipt: confirmedDepositReceipt(params.plan, route, transferQuote, owner, approvalTxIds, sourceTxId, receipt) }\n}\n\n/**\n * Checks whether Circle has attested one confirmed xReserve deposit.\n *\n * A missing attestation is reported as pending rather than failed. A completed\n * response is cryptographically tied to the requested deposit hash before it is\n * returned. The helper contacts Circle once and never requests a signature or\n * moves funds.\n *\n * @param registry Supported assets and reviewed xReserve provider endpoints.\n * @param transport HTTP access supplied by the application for the Circle request.\n * @param params Route, deposit message hash, and optional cancellation signal.\n * @returns Pending state or the verified deposit payload and Circle signature.\n * @throws BridgeError When the route is unavailable, Circle cannot be reached, or its response does not match the requested deposit.\n *\n * @example\n * const result = await getAttestation(registry, fetchTransport, { routeId, messageHash })\n */\nexport async function getAttestation(\n registry: BridgeRegistry,\n transport: XReserveHttpTransport,\n params: GetXReserveAttestationParameters,\n): Promise<XReserveAttestationResult> {\n const route = registry.routes.find((entry) => entry.id === params.routeId)\n if (!route) throw new BridgeError(`Unknown bridge route: ${params.routeId}`)\n if (route.protocol !== 'xreserve' || route.availability !== 'active') throw new BridgeError(`xReserve route is not executable: ${params.routeId}`)\n const attestationBaseUrl = route.metadata?.attestationBaseUrl\n if (typeof attestationBaseUrl !== 'string' || !attestationBaseUrl.startsWith('https://')) throw new BridgeError(`xReserve attestation URL is invalid: ${params.routeId}`)\n // A 404 means Circle has not signed yet; other HTTP failures indicate that\n // status is unavailable rather than that the cross-chain transfer failed.\n const response = await transport(`${attestationBaseUrl}/${params.messageHash}`, params.signal ? { signal: params.signal } : undefined)\n if (response.status === 404) return { status: 'pending', messageHash: params.messageHash }\n if (!response.ok) throw new BridgeError(`Circle attester request failed with HTTP ${response.status}`)\n const body = await response.json() as { attestation?: { payload?: unknown, messageHash?: unknown, attestation?: unknown } }\n const value = body.attestation\n if (!value || typeof value.payload !== 'string' || !isHex(value.payload) || typeof value.attestation !== 'string' || !isHex(value.attestation) || typeof value.messageHash !== 'string' || !isHash(value.messageHash) || value.messageHash.toLowerCase() !== params.messageHash.toLowerCase()) throw new BridgeError('Circle attester returned an invalid response')\n // Validate both the provider's echoed hash and a locally recomputed hash so\n // a mismatched response can never authorize an Aleo mint.\n if (calculateXReserveMessageHash(value.payload) !== params.messageHash) throw new BridgeError('Circle attestation payload does not match the requested message hash')\n return { status: 'complete', messageHash: params.messageHash, payload: value.payload, attestation: value.attestation }\n}\n\n/**\n * Delivers a private USDCx record after Circle attests an Ethereum deposit.\n *\n * The private mint secret must reproduce the recipient commitment embedded in\n * the source deposit. The Aleo wallet proves, signs, and submits the mint, which\n * incurs an Aleo transaction fee. The source deposit is never repeated.\n *\n * @param registry Supported assets and reviewed xReserve deployments.\n * @param client Aleo wallet that proves, signs, and broadcasts the private mint.\n * @param params Route, recipient, confirmed deposit, Circle attestation, private mint secret, fee preference, and recovery callbacks.\n * @returns The Aleo transaction identifier and state needed to confirm private delivery.\n * @throws BridgeError When the transfer is not a private mint, the attestation or secret does not match the deposit, or wallet submission fails.\n * @example const mint = await complete(registry, client, { plan, deposit, attestation })\n */\nexport async function complete(\n registry: BridgeRegistry,\n client: AleoWalletClient,\n params: ExecuteXReservePrivateMintParameters,\n): Promise<XReservePrivateMintExecution> {\n const { plan, deposit, attestation } = params\n if (plan.protocol !== 'xreserve' || plan.route.protocol !== 'xreserve' || plan.mintMode !== 'private') {\n throw new BridgeError('private_mint requires a private xReserve transfer plan')\n }\n if (plan.registryVersion !== registry.version) throw new BridgeError(`Transfer plan uses registry ${plan.registryVersion}; expected ${registry.version}`)\n const route = registry.routes.find((entry) => entry.id === plan.route.id)\n if (!route || route.protocol !== 'xreserve' || route.availability !== 'active') throw new BridgeError(`xReserve route is not executable: ${plan.route.id}`)\n const wrapperProgram = route.metadata?.wrapperProgram\n if (typeof wrapperProgram !== 'string' || !wrapperProgram.endsWith('.aleo')) throw new BridgeError(`xReserve wrapper program is invalid: ${plan.route.id}`)\n if (deposit.protocol !== 'xreserve' || deposit.status !== 'ATTESTATION_PENDING') throw new BridgeError('Private mint requires a confirmed xReserve deposit awaiting attestation')\n if (attestation.status !== 'complete') throw new BridgeError('Private mint requires a completed Circle attestation')\n\n const depositPayload = deposit.protocolState.payload\n const depositHash = deposit.protocolState.messageHash\n const intendedRecipient = deposit.protocolState.intendedRecipient\n const mintMode = deposit.protocolState.mintMode\n if (typeof depositPayload !== 'string' || !isHex(depositPayload, { strict: true })) throw new BridgeError('Deposit receipt is missing the canonical xReserve payload')\n if (typeof depositHash !== 'string' || !isHash(depositHash)) throw new BridgeError('Deposit receipt is missing the Circle message hash')\n if (typeof intendedRecipient !== 'string' || intendedRecipient !== plan.recipient || mintMode !== 'private') throw new BridgeError('Deposit receipt does not match the private mint plan')\n if (attestation.payload.toLowerCase() !== depositPayload.toLowerCase() || attestation.messageHash.toLowerCase() !== depositHash.toLowerCase()) throw new BridgeError('Circle attestation does not match the confirmed deposit')\n if (calculateXReserveMessageHash(attestation.payload) !== attestation.messageHash) throw new BridgeError('Circle attestation payload has an invalid message hash')\n const secretNonce = params.privateMintSecretNonce ?? '0scalar'\n // Recreate the commitment embedded in the Ethereum deposit. The wallet is not\n // involved unless the recipient and secret open that exact commitment.\n const expectedHookData = await buildXReserveHookData('private', plan.recipient, route.environment, secretNonce)\n const attestedHookData = `0x${attestation.payload.slice(-130)}`\n if (attestedHookData.toLowerCase() !== expectedHookData.toLowerCase()) {\n throw new BridgeError('Private mint secret nonce and recipient do not match the attested hook data')\n }\n\n // Circle's signed bytes are passed verbatim into the wrapper. The Aleo\n // program verifies the attestation and consumes the deposit exactly once.\n const transactionId = await client.executeTransaction({\n program: wrapperProgram,\n function: 'private_mint',\n inputs: [\n xReserveHexToAleoBytes(attestation.payload, 305),\n xReserveHexToAleoBytes(attestation.attestation, 65),\n xReserveHexToAleoBytes(attestation.messageHash, 32),\n secretNonce,\n plan.recipient,\n ],\n privateFee: params.privateFee ?? false,\n onProgress: async (event) => {\n await params.onProgress?.(event)\n if (event.type === 'transaction-prepared') await params.onPrepared?.(event.transaction)\n },\n })\n if (!transactionId) throw new BridgeError('Aleo wallet returned an empty private mint transaction id')\n const receipt: BridgeReceipt = {\n ...deposit,\n status: 'DESTINATION_CONFIRMING',\n destinationTxId: transactionId,\n protocolState: {\n ...deposit.protocolState,\n attestation: attestation.attestation,\n destinationProgram: wrapperProgram,\n destinationFunction: 'private_mint',\n secretNonce,\n },\n }\n await params.onSubmitted?.(receipt)\n return { transactionId, receipt }\n}\n","import { BridgeError } from '../../errors/bridgeErrors.js'\nimport type {\n BridgeRegistry,\n BridgePlan,\n ProtocolBridgeAsset,\n ProtocolBridgeChain,\n ProtocolBridgeRoute,\n} from '../../types/protocol.js'\n\n/**\n * Groups the current registry entries that define one validated transfer direction.\n *\n * @property route Bridge provider and directional asset pairing.\n * @property sourceAsset Token or native asset committed on the source chain.\n * @property destinationAsset Token or native asset delivered on the destination chain.\n * @property sourceChain Source network and transaction family.\n * @property destinationChain Destination network and transaction family.\n */\nexport type ResolvedTransferRoute = {\n route: ProtocolBridgeRoute\n sourceAsset: ProtocolBridgeAsset\n destinationAsset: ProtocolBridgeAsset\n sourceChain: ProtocolBridgeChain\n destinationChain: ProtocolBridgeChain\n}\n\n/**\n * Resolves saved transfer details against the exact route catalog that created them.\n *\n * Rejects stale or altered route, asset, and chain references using only the\n * supplied registry and transfer details, before any network access or wallet\n * request occurs.\n *\n * @param registry Supported chains, assets, routes, and reviewed deployments expected by the action.\n * @param plan Route, assets, amount, and recipient whose registry references are validated.\n * @returns Canonical route, asset, and chain entries from the registry.\n * @throws BridgeError When the plan is stale or its route topology was altered.\n * @example const route = resolveTransferRoute(registry, plan)\n */\nexport function resolveTransferRoute(\n registry: BridgeRegistry,\n plan: BridgePlan,\n): ResolvedTransferRoute {\n if (plan.registryVersion !== registry.version) {\n throw new BridgeError(`Transfer plan uses registry ${plan.registryVersion}; expected ${registry.version}`)\n }\n const route = registry.routes.find((entry) => entry.id === plan.route.id)\n if (!route || route.protocol !== plan.protocol || plan.route.protocol !== plan.protocol) {\n throw new BridgeError(`Transfer plan route does not match the configured registry: ${plan.route.id}`)\n }\n if (route.sourceAssetId !== plan.sourceAsset.id || route.destinationAssetId !== plan.destinationAsset.id) {\n throw new BridgeError(`Transfer plan assets do not match configured route: ${route.id}`)\n }\n const sourceAsset = registry.assets.find((asset) => asset.id === route.sourceAssetId)\n const destinationAsset = registry.assets.find((asset) => asset.id === route.destinationAssetId)\n if (!sourceAsset || sourceAsset.chainId !== plan.sourceAsset.chainId\n || !destinationAsset || destinationAsset.chainId !== plan.destinationAsset.chainId) {\n throw new BridgeError(`Transfer plan asset chains do not match configured route: ${route.id}`)\n }\n const sourceChain = registry.chains.find((chain) => chain.id === sourceAsset.chainId)\n const destinationChain = registry.chains.find((chain) => chain.id === destinationAsset.chainId)\n if (!sourceChain || !destinationChain) {\n throw new BridgeError(`Transfer plan references an unknown chain: ${route.id}`)\n }\n return { route, sourceAsset, destinationAsset, sourceChain, destinationChain }\n}\n","import { BridgeError } from '../errors/bridgeErrors.js'\nimport type { BridgeCheckpoint, BridgePlan, BridgeReceipt } from '../types/protocol.js'\n\n/**\n * Captures the information an application needs to return to a cross-chain transfer after an interruption.\n *\n * The result includes the route, assets, amount, recipient, and submitted\n * transaction identifiers. It excludes private keys, Aleo record contents, and\n * the secret used for a private xReserve mint.\n *\n * Creating a checkpoint does not contact a network or store data on the\n * caller's behalf. The application decides whether and where to save it.\n *\n * @param plan Transfer details that identify the route, assets, amount, and recipient.\n * @param receipt Latest state returned after a wallet submission.\n * @returns Public recovery information suitable for optional durable storage.\n * @throws BridgeError When the receipt belongs to a different transfer route.\n * @example const checkpoint = createBridgeCheckpoint(plan, execution.receipt)\n */\nexport function createBridgeCheckpoint(\n plan: BridgePlan,\n receipt: BridgeReceipt,\n): BridgeCheckpoint {\n if (receipt.protocol !== plan.protocol || receipt.protocolState.routeId !== plan.route.id) {\n throw new BridgeError('Bridge receipt does not match the prepared route')\n }\n // Checkpoints use an allowlist, not a copy of protocolState. This prevents\n // protocol response bodies and private-mint secrets from leaking into storage.\n const rawApprovals = receipt.protocolState.approvalTxIds\n if (rawApprovals !== undefined\n && (!Array.isArray(rawApprovals) || rawApprovals.some((value) => typeof value !== 'string'))) {\n throw new BridgeError('Bridge receipt contains invalid approval transaction identifiers')\n }\n const approvals = [...(rawApprovals ?? [])] as string[]\n const sourceSender = receipt.protocolState.sourceSender\n if (sourceSender !== undefined && typeof sourceSender !== 'string') {\n throw new BridgeError('Bridge receipt contains an invalid source sender')\n }\n const sender = plan.sender ?? sourceSender\n const preparedTransaction = receipt.protocolState.preparedTransaction\n if (preparedTransaction !== undefined\n && (typeof preparedTransaction !== 'string' || !preparedTransaction)) {\n throw new BridgeError('Bridge receipt contains an invalid prepared transaction')\n }\n const preparedDestinationTransaction = receipt.protocolState.preparedDestinationTransaction\n if (preparedDestinationTransaction !== undefined\n && (typeof preparedDestinationTransaction !== 'string' || !preparedDestinationTransaction)) {\n throw new BridgeError('Bridge receipt contains an invalid prepared destination transaction')\n }\n const blockhash = receipt.protocolState.blockhash\n const lastValidBlockHeight = receipt.protocolState.lastValidBlockHeight\n if ((blockhash !== undefined || lastValidBlockHeight !== undefined)\n && (typeof blockhash !== 'string' || !blockhash\n || typeof lastValidBlockHeight !== 'string' || !/^\\d+$/.test(lastValidBlockHeight))) {\n throw new BridgeError('Bridge receipt contains an invalid Solana blockhash lifetime')\n }\n // Source state records either a proved Aleo transaction, submitted approval\n // transactions, or the irreversible source transaction identifier.\n const source = approvals.length > 0 || receipt.sourceTxId || preparedTransaction\n ? {\n ...(approvals.length > 0 ? { approvalTransactionIds: approvals } : {}),\n ...(receipt.sourceTxId ? { transactionId: receipt.sourceTxId } : {}),\n ...(typeof receipt.protocolState.hookData === 'string'\n ? { hookData: receipt.protocolState.hookData }\n : {}),\n ...(typeof blockhash === 'string' && typeof lastValidBlockHeight === 'string'\n ? { blockhash, lastValidBlockHeight }\n : {}),\n ...(typeof preparedTransaction === 'string'\n ? { preparedTransaction: { transactionId: receipt.id, serializedTransaction: preparedTransaction } }\n : {}),\n }\n : undefined\n const balanceBeforeAtomic = receipt.protocolState.destinationBalanceBeforeAtomic\n const expectedIncreaseAtomic = receipt.protocolState.expectedDestinationIncreaseAtomic\n if ((balanceBeforeAtomic !== undefined || expectedIncreaseAtomic !== undefined)\n && (typeof balanceBeforeAtomic !== 'string' || !/^\\d+$/.test(balanceBeforeAtomic)\n || typeof expectedIncreaseAtomic !== 'string' || !/^\\d+$/.test(expectedIncreaseAtomic))) {\n throw new BridgeError('Bridge receipt contains invalid destination balance verification state')\n }\n // The intent is sufficient to resolve the current route catalog again during\n // recovery; deployed contracts and provider payloads are deliberately omitted.\n return {\n version: 1,\n intent: {\n source: { chain: plan.sourceAsset.chainId, asset: plan.sourceAsset.key },\n destination: { chain: plan.destinationAsset.chainId, asset: plan.destinationAsset.key },\n bridgeProtocol: plan.protocol,\n amount: plan.amountIn,\n recipient: plan.recipient,\n ...(sender ? { sender } : {}),\n ...(plan.destinationAsset.locator?.kind === 'aleo-program' ? { mintMode: plan.mintMode } : {}),\n },\n route: { id: plan.route.id, registryVersion: plan.registryVersion },\n ...(source ? { source } : {}),\n ...(receipt.destinationTxId || typeof preparedDestinationTransaction === 'string'\n ? {\n destination: {\n ...(receipt.destinationTxId ? { transactionId: receipt.destinationTxId } : {}),\n ...(typeof preparedDestinationTransaction === 'string'\n ? { preparedTransaction: { transactionId: receipt.id, serializedTransaction: preparedDestinationTransaction } }\n : {}),\n },\n }\n : {}),\n ...(typeof balanceBeforeAtomic === 'string' && typeof expectedIncreaseAtomic === 'string'\n ? { deliveryVerification: { balanceBeforeAtomic, expectedIncreaseAtomic } }\n : {}),\n }\n}\n","import { decodeFunctionResult, encodeFunctionData, getAddress, parseAbi } from 'viem'\nimport type { BridgeChainClients } from '../../connections/resolve.js'\nimport { requireEvmClient, requireSolanaClient } from '../../connections/resolve.js'\nimport { BridgeError } from '../../errors/bridgeErrors.js'\nimport type { BridgePlan, BridgeRegistry } from '../../types/protocol.js'\n\nconst ERC20_BALANCE_ABI = parseAbi(['function balanceOf(address owner) view returns (uint256)'])\n\n/**\n * Reads a recipient balance that can serve as a fallback delivery signal.\n *\n * Native EVM and Solana balances and EVM ERC-20 balances are supported. The\n * helper returns `undefined` when the destination client or asset reader is not\n * configured, allowing status tracking to report that canonical verification\n * is unavailable rather than claim delivery. It never requests a signature or\n * moves funds.\n */\nexport async function readDestinationBalance(\n registry: BridgeRegistry,\n clients: BridgeChainClients,\n plan: BridgePlan,\n): Promise<bigint | undefined> {\n const chain = registry.chains.find((candidate) => candidate.id === plan.destinationAsset.chainId)\n if (!chain) throw new BridgeError(`Unknown destination chain: ${plan.destinationAsset.chainId}`)\n if (!clients[chain.id]) return undefined\n\n if (chain.family === 'evm') {\n const recipient = getAddress(plan.recipient)\n const client = requireEvmClient(registry, clients, chain.id).publicClient\n // Native balance uses the account balance; ERC-20 delivery must call the\n // destination token selected by the reviewed route.\n if (plan.destinationAsset.locator?.kind === 'native') return client.getBalance(recipient)\n if (plan.destinationAsset.locator?.kind !== 'evm-contract') return undefined\n const data = encodeFunctionData({\n abi: ERC20_BALANCE_ABI,\n functionName: 'balanceOf',\n args: [recipient],\n })\n const result = await client.call({ to: getAddress(plan.destinationAsset.locator.value), data })\n return decodeFunctionResult({ abi: ERC20_BALANCE_ABI, functionName: 'balanceOf', data: result })\n }\n\n if (chain.family === 'solana' && plan.destinationAsset.locator?.kind === 'native') {\n return requireSolanaClient(registry, clients, chain.id).publicClient.getBalance(plan.recipient)\n }\n\n // Aleo private records and unsupported token standards cannot be verified by\n // a public balance read, so callers need a protocol-specific delivery signal.\n return undefined\n}\n","import { BridgeError } from '../errors/bridgeErrors.js'\nimport {\n requireAleoClient,\n requireAleoClientWithWallet,\n requireEvmClientWithWallet,\n requireSolanaClientWithWallet,\n type BridgeChainClients,\n} from '../connections/resolve.js'\nimport type { XReserveBurnMode } from '../types/aleo.js'\nimport type { BridgeReceipt, BridgeRegistry } from '../types/protocol.js'\nimport type { ExecuteParameters, BridgeExecution } from '../types/actions.js'\nimport { aleoAddressToBytes32 } from '../utils/xreserve.js'\nimport * as aleoHyperlane from '../protocols/hyperlane/aleo.js'\nimport * as evmHyperlane from '../protocols/hyperlane/evm.js'\nimport * as solanaHyperlane from '../protocols/hyperlane/solana.js'\nimport * as aleoToEvmXReserve from '../protocols/xreserve/aleoToEvm.js'\nimport * as evmToAleoXReserve from '../protocols/xreserve/evmToAleo.js'\nimport { resolveTransferRoute } from './internal/resolveTransferRoute.js'\nimport { createBridgeCheckpoint } from './createBridgeCheckpoint.js'\nimport type { Transaction } from '@provablehq/veil-core'\nimport { readDestinationBalance } from './internal/readDestinationBalance.js'\nimport { parseDecimalAmount } from '../utils/units.js'\n\ntype DeliveryVerification = {\n destinationBalanceBeforeAtomic: string\n expectedDestinationIncreaseAtomic: string\n}\n\nfunction withDeliveryVerification(\n receipt: BridgeReceipt,\n verification: DeliveryVerification | undefined,\n): BridgeReceipt {\n return verification\n ? { ...receipt, protocolState: { ...receipt.protocolState, ...verification } }\n : receipt\n}\n\nfunction submissionCheckpoint(params: ExecuteParameters) {\n // Protocol executors emit rich receipts. Reduce them to the documented\n // recovery fields before crossing the application-owned persistence boundary.\n return params.onCheckpoint\n ? async (receipt: import('../types/protocol.js').BridgeReceipt) => {\n await params.onCheckpoint?.(createBridgeCheckpoint(params.plan, receipt))\n }\n : undefined\n}\n\nfunction preparedAleoCheckpoint(\n params: ExecuteParameters,\n verification?: DeliveryVerification,\n) {\n // Aleo proving finishes before broadcast. Persisting the immutable proved\n // transaction here closes the crash window between those two operations;\n // recovery can rebroadcast the same transaction id without proving again.\n return params.onCheckpoint\n ? async (transaction: Transaction) => {\n await params.onCheckpoint?.(createBridgeCheckpoint(params.plan, {\n id: transaction.id,\n protocol: params.plan.protocol,\n status: 'SOURCE_SUBMISSION_PENDING',\n protocolState: {\n routeId: params.plan.route.id,\n preparedTransaction: JSON.stringify(transaction),\n ...verification,\n },\n }))\n }\n : undefined\n}\n\nfunction aleoHyperlaneMode(mode: ExecuteParameters['mode']): 'caller' | 'signer' | undefined {\n if (mode == null) return undefined\n if (mode === 'caller' || mode === 'signer') return mode\n throw new BridgeError(`Aleo Hyperlane does not support execution mode \"${mode}\"`)\n}\n\nfunction xReserveBurnMode(mode: ExecuteParameters['mode']): XReserveBurnMode | undefined {\n if (mode == null) return undefined\n if (mode === 'private' || mode === 'public' || mode === 'public-as-signer') return mode\n throw new BridgeError(`Aleo xReserve does not support execution mode \"${mode}\"`)\n}\n\n/**\n * Begins a cross-chain transfer by committing funds on the source chain.\n *\n * Token transfers may first require the source wallet to approve the bridge\n * contract. The action then submits the deposit, burn, or dispatch that commits\n * the asset to the selected bridge provider.\n *\n * The returned receipt identifies the in-progress transfer. Once the source\n * transaction is accepted, the transfer may no longer be reversible. Each\n * submitted transaction may incur a network fee even if a later stage fails.\n *\n * @param registry Supported chains, assets, and bridge provider deployments.\n * @param clients Network and wallet access for the source and destination chains.\n * @param params Transfer details, source wallet preferences, and an optional callback for saving recovery information.\n * @returns The submitted transaction identifier and the initial state of the in-progress transfer.\n * @throws BridgeError When the transfer is unsupported, the connected wallet cannot authorize it, current funds or fees are insufficient, or submission fails.\n * @example const execution = await execute(registry, clients, { plan, onCheckpoint: saveCheckpoint })\n */\nexport async function execute(\n registry: BridgeRegistry,\n clients: BridgeChainClients,\n params: ExecuteParameters,\n): Promise<BridgeExecution> {\n // The selected route, not caller-supplied chain branching, determines which\n // protocol implementation and wallet capability may commit the funds.\n const chain = resolveTransferRoute(registry, params.plan).sourceChain\n const chainId = chain.id\n const onSubmitted = submissionCheckpoint(params)\n\n if (params.plan.protocol === 'hyperlane' && chain.family === 'evm') {\n const execution = await evmHyperlane.execute(\n registry,\n requireEvmClientWithWallet(registry, clients, chainId, 'execute Hyperlane transfer'),\n {\n plan: params.plan,\n recipientBytes32: aleoAddressToBytes32(params.plan.recipient),\n pollingIntervalMs: params.pollingIntervalMs,\n confirmationTimeoutMs: params.confirmationTimeoutMs,\n onSubmitted,\n },\n )\n return { kind: 'evm-hyperlane', ...execution }\n }\n if (params.plan.protocol === 'hyperlane' && chain.family === 'solana') {\n const execution = await solanaHyperlane.execute(\n registry,\n requireSolanaClientWithWallet(registry, clients, chainId, 'execute Hyperlane transfer'),\n {\n plan: params.plan,\n pollingIntervalMs: params.pollingIntervalMs,\n confirmationTimeoutMs: params.confirmationTimeoutMs,\n onSubmitted,\n },\n )\n return { kind: 'solana-hyperlane', ...execution }\n }\n if (params.plan.protocol === 'hyperlane' && chain.family === 'aleo') {\n const client = requireAleoClientWithWallet(registry, clients, chainId, 'execute Hyperlane transfer')\n // Hyperlane's explorer does not index every Aleo-origin route reliably.\n // Capture a destination balance baseline so delivery can still be verified\n // from the destination chain when no canonical message id is available.\n const destinationBalanceBefore = await readDestinationBalance(registry, clients, params.plan)\n const verification = destinationBalanceBefore === undefined\n ? undefined\n : {\n destinationBalanceBeforeAtomic: destinationBalanceBefore.toString(),\n expectedDestinationIncreaseAtomic: parseDecimalAmount(\n params.plan.amountIn,\n params.plan.destinationAsset.decimals,\n ).toString(),\n }\n const onAleoSubmitted = params.onCheckpoint\n ? async (receipt: BridgeReceipt) => {\n await params.onCheckpoint?.(createBridgeCheckpoint(\n params.plan,\n withDeliveryVerification(receipt, verification),\n ))\n }\n : undefined\n // The Aleo hook checks its relayer payment for exact equality on-chain.\n // Read it immediately before proving unless the caller deliberately pinned\n // a value, minimizing failures caused by an oracle update.\n const gasPaymentMicrocredits = params.gasPaymentMicrocredits ?? (await aleoHyperlane.quote(\n registry,\n requireAleoClient(registry, clients, chainId).publicClient,\n { routeId: params.plan.route.id },\n )).paymentMicrocredits\n const execution = await aleoHyperlane.execute(registry, client.walletClient, {\n plan: params.plan,\n mode: aleoHyperlaneMode(params.mode),\n privateFee: params.privateFee,\n gasPaymentMicrocredits,\n onSubmitted: onAleoSubmitted,\n onProgress: params.onProgress,\n onPrepared: preparedAleoCheckpoint(params, verification),\n })\n return {\n kind: 'aleo-hyperlane',\n ...execution,\n receipt: withDeliveryVerification(execution.receipt, verification),\n }\n }\n if (params.plan.protocol === 'xreserve' && chain.family === 'evm') {\n const execution = await evmToAleoXReserve.execute(\n registry,\n requireEvmClientWithWallet(registry, clients, chainId, 'execute xReserve transfer'),\n {\n plan: params.plan,\n pollingIntervalMs: params.pollingIntervalMs,\n confirmationTimeoutMs: params.confirmationTimeoutMs,\n onSubmitted,\n privateMintSecretNonce: params.privateMintSecretNonce,\n },\n )\n return { kind: 'evm-xreserve', ...execution }\n }\n if (params.plan.protocol === 'xreserve' && chain.family === 'aleo') {\n // An Aleo burn is the only caller-authorized step in the outbound xReserve\n // direction. The attestation service and Circle manage Ethereum delivery.\n const execution = await aleoToEvmXReserve.execute(\n registry,\n requireAleoClientWithWallet(registry, clients, chainId, 'execute xReserve burn').walletClient,\n {\n plan: params.plan,\n mode: xReserveBurnMode(params.mode),\n userRecord: params.userRecord,\n merkleProof: params.merkleProof,\n privateFee: params.privateFee,\n onSubmitted,\n onProgress: params.onProgress,\n onPrepared: preparedAleoCheckpoint(params),\n },\n )\n return { kind: 'aleo-xreserve', ...execution }\n }\n\n throw new BridgeError(`Unsupported ${params.plan.protocol} source chain family: ${chain.family}`)\n}\n","import { BridgeError } from '../errors/bridgeErrors.js'\nimport type {\n BridgeExecutionStep,\n BridgeRegistry,\n BridgePlan,\n PrepareParameters,\n ProtocolBridgeAsset,\n ProtocolBridgeChain,\n ProtocolBridgeRoute,\n} from '../types/protocol.js'\nimport { parseDecimalAmount } from '../utils/units.js'\n\nfunction executor(chain: ProtocolBridgeChain): 'aleo-wallet' | 'evm-wallet' | 'solana-wallet' {\n if (chain.family === 'aleo') return 'aleo-wallet'\n if (chain.family === 'evm') return 'evm-wallet'\n return 'solana-wallet'\n}\n\nfunction xreserveSteps(\n route: ProtocolBridgeRoute,\n source: ProtocolBridgeAsset,\n destination: ProtocolBridgeAsset,\n sourceChain: ProtocolBridgeChain,\n destinationChain: ProtocolBridgeChain,\n mintMode: BridgePlan['mintMode'],\n): BridgeExecutionStep[] {\n if (sourceChain.family === 'evm' && destinationChain.family === 'aleo') {\n return [\n { key: 'source-approval', kind: 'approve', chainId: source.chainId, executor: 'evm-wallet', description: `Approve the Circle xReserve contract to spend ${source.symbol}.`, irreversible: false },\n { key: 'source-deposit', kind: 'deposit', chainId: source.chainId, executor: 'evm-wallet', description: `Deposit ${source.symbol} into Circle xReserve for Aleo.`, irreversible: true },\n { key: 'deposit-attestation', kind: 'wait-attestation', executor: 'protocol', description: 'Wait for Circle to attest the confirmed reserve deposit.', irreversible: false },\n { key: 'destination-mint', kind: 'mint', chainId: destination.chainId, executor: mintMode === 'private' ? 'aleo-wallet' : 'protocol', description: mintMode === 'private' ? `Submit private_mint to mint attested ${destination.symbol} through the shielded wrapper.` : `Wait for attested ${destination.symbol} to mint as an Aleo ${mintMode === 'record' ? 'record' : 'public balance'}.`, irreversible: false },\n ]\n }\n if (sourceChain.family === 'aleo' && destinationChain.family === 'evm') {\n return [\n { key: 'source-burn', kind: 'burn', chainId: source.chainId, executor: 'aleo-wallet', description: `Burn ${source.symbol} and create the xReserve withdrawal intent; private burn is the default.`, irreversible: true },\n { key: 'withdrawal-attestation', kind: 'wait-attestation', executor: 'protocol', description: 'Wait for the Aleo burn attestation service to forward the accepted burn to Circle.', irreversible: false },\n { key: 'destination-withdrawal', kind: 'withdraw', chainId: destination.chainId, executor: 'protocol', description: `Wait for Circle to release ${destination.symbol} to the native recipient.`, irreversible: false },\n { key: 'destination-confirmation', kind: 'confirm-delivery', chainId: destination.chainId, executor: 'protocol', description: 'Confirm the destination USDC balance change.', irreversible: false },\n ]\n }\n throw new BridgeError(`Unsupported xReserve route direction: ${route.id}`)\n}\n\nfunction hyperlaneSteps(\n source: ProtocolBridgeAsset,\n destination: ProtocolBridgeAsset,\n sourceChain: ProtocolBridgeChain,\n destinationChain: ProtocolBridgeChain,\n): BridgeExecutionStep[] {\n const steps: BridgeExecutionStep[] = []\n if (source.kind === 'token' && sourceChain.family !== 'aleo') {\n steps.push({\n key: 'source-approval',\n kind: 'approve',\n chainId: source.chainId,\n executor: executor(sourceChain),\n description: `Approve the Hyperlane Warp Route to spend ${source.symbol}.`,\n irreversible: false,\n })\n }\n steps.push(\n { key: 'source-dispatch', kind: 'dispatch', chainId: source.chainId, executor: executor(sourceChain), description: `Dispatch ${source.symbol} through its Hyperlane Warp Route.`, irreversible: true },\n { key: 'message-delivery', kind: 'wait-delivery', executor: 'protocol', description: 'Wait for the Hyperlane message to be relayed and processed.', irreversible: false },\n { key: 'destination-confirmation', kind: 'confirm-delivery', chainId: destination.chainId, executor: 'protocol', description: `Confirm relayer delivery of ${destination.symbol} on the destination chain.`, irreversible: false },\n )\n return steps\n}\n\n/**\n * Describes how an amount of an asset can move between two chains.\n *\n * The caller chooses the source asset, destination asset, amount, recipient,\n * and optionally the bridge provider. The result identifies the supported\n * route, the assets that will be debited and delivered, and each stage required\n * to complete the transfer.\n *\n * No blockchain or bridge provider is contacted, no wallet approval is\n * requested, and no funds move. The returned information can be priced before\n * the caller decides whether to begin the transfer.\n *\n * @param registry Supported chains, assets, and bridge provider deployments.\n * @param params Desired source asset, destination asset, amount, recipient, provider, sender, and Aleo privacy preference.\n * @returns The route, assets, amount, recipient, and stages required for the cross-chain transfer.\n * @throws BridgeError When no available provider supports the requested transfer, the amount cannot be represented by both assets, or the recipient is invalid for the destination chain.\n *\n * @example\n * const plan = prepare(registry, {\n * source: { chain: 'ethereum', asset: 'usdc' },\n * destination: { chain: 'aleo', asset: 'usdcx' },\n * amount: '25',\n * recipient: 'aleo1...',\n * })\n */\nexport function prepare(\n registry: BridgeRegistry,\n params: PrepareParameters,\n): BridgePlan {\n // Resolve both chain-specific asset representations before route selection.\n // The same symbol can refer to different contracts or programs on each chain.\n const sourceAsset = registry.assets.find((asset) => asset.chainId === params.source.chain && asset.key === params.source.asset)\n if (!sourceAsset) throw new BridgeError(`Unknown source asset ${params.source.asset} on ${params.source.chain}`)\n const destinationAsset = registry.assets.find((asset) => asset.chainId === params.destination.chain && asset.key === params.destination.asset)\n if (!destinationAsset) throw new BridgeError(`Unknown destination asset ${params.destination.asset} on ${params.destination.chain}`)\n const routes = registry.routes.filter((entry) => entry.sourceAssetId === sourceAsset.id\n && entry.destinationAssetId === destinationAsset.id\n && entry.availability !== 'disabled'\n && (params.bridgeProtocol == null || entry.protocol === params.bridgeProtocol))\n if (routes.length === 0) {\n throw new BridgeError(`No bridge route from ${params.source.chain}/${params.source.asset} to ${params.destination.chain}/${params.destination.asset}`)\n }\n if (routes.length > 1) {\n throw new BridgeError(`Multiple bridge routes match ${params.source.chain}/${params.source.asset} to ${params.destination.chain}/${params.destination.asset}; specify bridgeProtocol`)\n }\n const route = routes[0]!\n\n const sourceChain = registry.chains.find((chain) => chain.id === sourceAsset.chainId)!\n const destinationChain = registry.chains.find((chain) => chain.id === destinationAsset.chainId)!\n\n if (params.privateRecipient === true && params.mintMode != null && params.mintMode !== 'private') {\n throw new BridgeError('privateRecipient conflicts with the selected mintMode')\n }\n // xReserve delivery on Aleo can be a public balance, a private record minted\n // by the provider, or a private wrapper mint authorized by the recipient.\n const mintMode = params.mintMode ?? (params.privateRecipient === true ? 'private' : 'public')\n if ((params.mintMode != null || params.privateRecipient === true) && destinationChain.family !== 'aleo') {\n throw new BridgeError('Aleo mint mode is only valid when the destination chain is Aleo')\n }\n if (route.protocol !== 'xreserve' && mintMode !== 'public') {\n throw new BridgeError('record and private mint modes are only supported by xReserve routes')\n }\n\n const atomic = parseDecimalAmount(params.amount, sourceAsset.decimals)\n if (atomic <= 0n) throw new BridgeError('Bridge transfer amount must be greater than zero')\n parseDecimalAmount(params.amount, destinationAsset.decimals)\n\n if (destinationAsset.addressValidationRegex) {\n const regex = new RegExp(destinationAsset.addressValidationRegex)\n if (!regex.test(params.recipient)) {\n throw new BridgeError(`Recipient does not match ${destinationAsset.chainId} address format`)\n }\n }\n\n // Steps are descriptive application guidance. They do not execute and are\n // derived from the validated direction and provider rather than caller input.\n const steps = route.protocol === 'xreserve'\n ? xreserveSteps(route, sourceAsset, destinationAsset, sourceChain, destinationChain, mintMode)\n : hyperlaneSteps(sourceAsset, destinationAsset, sourceChain, destinationChain)\n const fees: BridgePlan['fees'] = []\n\n return {\n registryVersion: registry.version,\n protocol: route.protocol,\n route,\n sourceAsset,\n destinationAsset,\n amountIn: params.amount,\n // Both current protocols preserve display units before live fee deduction.\n // Omit a promise about net output until fee quoting is implemented.\n recipient: params.recipient,\n ...(params.sender == null ? {} : { sender: params.sender }),\n mintMode,\n privateRecipient: mintMode === 'private',\n fees,\n steps,\n }\n}\n","import { BridgeError } from '../errors/bridgeErrors.js'\nimport {\n requireAleoClient,\n requireEvmClient,\n requireSolanaClient,\n type BridgeChainClients,\n} from '../connections/resolve.js'\nimport type { BridgeRegistry } from '../types/protocol.js'\nimport type { QuoteParameters, BridgeQuote } from '../types/actions.js'\nimport { aleoAddressToBytes32 } from '../utils/xreserve.js'\nimport * as aleoHyperlane from '../protocols/hyperlane/aleo.js'\nimport * as evmHyperlane from '../protocols/hyperlane/evm.js'\nimport * as solanaHyperlane from '../protocols/hyperlane/solana.js'\nimport * as evmToAleoXReserve from '../protocols/xreserve/evmToAleo.js'\nimport { resolveTransferRoute } from './internal/resolveTransferRoute.js'\nimport { formatDecimalAmount, parseDecimalAmount } from '../utils/units.js'\nimport { prepare } from './prepare.js'\n\n/**\n * Calculates the funds and fees required to begin a cross-chain transfer.\n *\n * The caller supplies the intended source, destination, amount, recipient, and\n * optional provider. The result includes both the validated transfer plan and\n * the bridge and network costs the selected provider can determine. Depending\n * on the route, it also reports the expected destination amount, wallet\n * balance, and token approval requirements.\n *\n * Routes with live pricing read current network and provider state; other routes\n * return their configured costs. The action does not request a wallet signature\n * or move funds.\n *\n * @param registry Supported chains, assets, and bridge provider deployments.\n * @param clients Network access for the chains involved in the transfer.\n * @param params Transfer details whose current cost and requirements are calculated.\n * @returns The amount expected at the destination and the known bridge, network, and approval costs.\n * @throws BridgeError When the selected provider cannot quote the transfer or required network access is unavailable.\n * @example const result = await quote(registry, clients, { source, destination, amount: '1', recipient })\n */\nexport async function quote(\n registry: BridgeRegistry,\n clients: BridgeChainClients,\n params: QuoteParameters,\n): Promise<BridgeQuote> {\n // Build the canonical plan before reading live prices. The returned plan is\n // the exact value the caller passes to execution and stores in progress.\n const plan = prepare(registry, params)\n const protocolParams = {\n plan,\n privateMintSecretNonce: params.privateMintSecretNonce,\n }\n // Quote from the source side because that is where funds, approvals, and the\n // first network fee are paid. The validated route selects the protocol helper.\n const chain = resolveTransferRoute(registry, plan).sourceChain\n const chainId = chain.id\n\n if (plan.protocol === 'hyperlane' && chain.family === 'evm') {\n const client = requireEvmClient(registry, clients, chainId)\n const quote = await evmHyperlane.quote(registry, client, {\n plan,\n recipientBytes32: aleoAddressToBytes32(plan.recipient),\n })\n return { kind: 'evm-hyperlane', plan, ...quote }\n }\n if (plan.protocol === 'hyperlane' && chain.family === 'solana') {\n const quote = await solanaHyperlane.quote(\n registry,\n requireSolanaClient(registry, clients, chainId),\n protocolParams,\n )\n return { kind: 'solana-hyperlane', plan, ...quote }\n }\n if (plan.protocol === 'hyperlane' && chain.family === 'aleo') {\n const quote = await aleoHyperlane.quote(\n registry,\n requireAleoClient(registry, clients, chainId).publicClient,\n { routeId: plan.route.id },\n )\n return { kind: 'aleo-hyperlane', plan, ...quote }\n }\n if (plan.protocol === 'xreserve' && chain.family === 'evm') {\n const quote = await evmToAleoXReserve.quote(\n registry,\n requireEvmClient(registry, clients, chainId),\n protocolParams,\n )\n return { kind: 'evm-xreserve', plan, ...quote }\n }\n if (plan.protocol === 'xreserve' && chain.family === 'aleo') {\n // Aleo-origin xReserve has no provider quote endpoint. Its only known\n // bridge charge is the configured withdrawal fee, so report that fixed\n // deduction without pretending live state was queried.\n const rawFee = plan.route.metadata?.withdrawalFeeAtomic\n if (typeof rawFee !== 'string' || !/^\\d+$/.test(rawFee)) {\n throw new BridgeError(`xReserve withdrawal fee is missing or invalid: ${plan.route.id}`)\n }\n const feeAtomic = BigInt(rawFee)\n const amountAtomic = parseDecimalAmount(plan.amountIn, plan.sourceAsset.decimals)\n const formattedFee = formatDecimalAmount(feeAtomic, plan.sourceAsset.decimals)\n if (amountAtomic <= feeAtomic) {\n throw new BridgeError(`xReserve burn amount must exceed the ${formattedFee} ${plan.sourceAsset.symbol} withdrawal fee`)\n }\n const amountOutAtomic = amountAtomic - feeAtomic\n return {\n kind: 'aleo-xreserve',\n plan,\n routeId: plan.route.id,\n protocol: 'xreserve',\n amountIn: plan.amountIn,\n // xReserve preserves the displayed denomination across USDC and USDCx.\n // The remaining atomic amount is still expressed in source units here;\n // formatting it with destination decimals would change its value.\n amountOut: formatDecimalAmount(amountOutAtomic, plan.sourceAsset.decimals),\n fees: [\n ...plan.fees,\n {\n kind: 'protocol',\n chainId,\n assetId: plan.sourceAsset.id,\n amount: formattedFee,\n estimated: false,\n },\n ],\n status: 'not-queried',\n }\n }\n\n throw new BridgeError(`Unsupported ${plan.protocol} source chain family: ${chain.family}`)\n}\n","import { classifyBroadcastError, DuplicateTransactionError } from '@provablehq/veil-core'\nimport { isHash, isHex } from 'viem'\nimport { requireAleoClient, requireAleoClientWithWallet, type BridgeChainClients } from '../connections/resolve.js'\nimport { BridgeError } from '../errors/bridgeErrors.js'\nimport type { BridgeExecution, CompleteParameters } from '../types/actions.js'\nimport type { BridgeReceipt, BridgeRegistry } from '../types/protocol.js'\nimport { complete as completePrivateMint } from '../protocols/xreserve/evmToAleo.js'\nimport { resolveTransferRoute } from './internal/resolveTransferRoute.js'\nimport { createBridgeCheckpoint } from './createBridgeCheckpoint.js'\n\n/**\n * Submits the destination-chain transaction required to receive bridged funds.\n *\n * This currently applies to a private USDC-to-USDCx xReserve transfer after\n * Circle has attested the source deposit. The Aleo wallet proves, signs, and\n * submits the private mint that delivers a private record to the recipient.\n *\n * The source transaction is never repeated. The destination transaction incurs\n * an Aleo network fee even if it fails.\n *\n * @param registry Supported chains, assets, and bridge provider deployments.\n * @param clients Network and wallet access for the Aleo destination chain.\n * @param params Transfer state ready for private delivery, fee preference, secret nonce, and optional callback for saving recovery information.\n * @returns The Aleo transaction identifier and the destination confirmation state.\n * @throws BridgeError When no destination transaction is required, the Circle attestation is invalid, required wallet access is unavailable, or submission fails.\n * @example const execution = await complete(registry, clients, { plan, receipt: ready, onCheckpoint: save })\n */\nexport async function complete(\n registry: BridgeRegistry,\n clients: BridgeChainClients,\n params: CompleteParameters,\n): Promise<BridgeExecution> {\n let plan: import('../types/protocol.js').BridgePlan\n let receipt: BridgeReceipt\n // Accept either recovered progress or the equivalent in-memory pair. Both\n // paths must reach the same explicit destination-authorization boundary.\n if (params.progress) {\n if (params.progress.next !== 'complete') {\n throw new BridgeError('Bridge progress has no destination action to complete')\n }\n plan = params.progress.plan\n receipt = params.progress.receipt\n } else if (params.plan && params.receipt) {\n plan = params.plan\n receipt = params.receipt\n } else {\n throw new BridgeError('Bridge completion requires recovered progress')\n }\n const route = resolveTransferRoute(registry, plan)\n if (receipt.status !== 'DESTINATION_ACTION_REQUIRED'\n || receipt.nextAction?.kind !== 'xreserve-private-mint'\n || receipt.nextAction.chainId !== route.destinationChain.id) {\n throw new BridgeError('Bridge receipt has no supported destination action ready')\n }\n if (route.route.protocol !== 'xreserve' || route.sourceChain.family !== 'evm' || route.destinationChain.family !== 'aleo') {\n throw new BridgeError('Destination completion is not implemented for this bridge route')\n }\n const payload = receipt.protocolState.payload\n const messageHash = receipt.protocolState.messageHash\n const attestation = receipt.protocolState.attestation\n // These values came from Circle but are untrusted persisted input on a later\n // process. Validate their wire encodings again before involving the wallet.\n if (typeof payload !== 'string' || !isHex(payload, { strict: true })\n || typeof messageHash !== 'string' || !isHash(messageHash)\n || typeof attestation !== 'string' || !isHex(attestation, { strict: true })) {\n throw new BridgeError('Ready xReserve receipt is missing its validated Circle attestation')\n }\n const preparedTransaction = receipt.protocolState.preparedDestinationTransaction\n if (preparedTransaction !== undefined) {\n // A previous process finished proving the private mint but stopped before\n // broadcast. Submit those exact bytes so the transaction id and proof remain stable.\n if (typeof preparedTransaction !== 'string' || !preparedTransaction) {\n throw new BridgeError('Prepared Aleo destination recovery is missing its serialized transaction')\n }\n let decoded: unknown\n try {\n decoded = JSON.parse(preparedTransaction)\n } catch (error) {\n throw new BridgeError('Prepared Aleo destination recovery contains an invalid serialized transaction', { cause: error })\n }\n // Duplicate means the prior broadcast won the crash race. Treat it as the\n // same transfer and continue confirmation rather than creating a new mint.\n const transactionId = decoded && typeof decoded === 'object'\n ? (decoded as { id?: unknown }).id\n : undefined\n if (typeof transactionId !== 'string' || transactionId !== receipt.id) {\n throw new BridgeError('Prepared Aleo destination recovery transaction id does not match its payload')\n }\n try {\n const submittedId = await requireAleoClient(\n registry,\n clients,\n route.destinationChain.id,\n ).publicClient.request({\n method: 'sendTransaction',\n params: { transaction: preparedTransaction },\n }) as string\n if (submittedId !== transactionId) {\n throw new BridgeError(`Aleo node returned transaction id ${submittedId}; expected ${transactionId}`)\n }\n } catch (error) {\n if (error instanceof BridgeError) throw error\n const classified = classifyBroadcastError(error, transactionId)\n if (!(classified instanceof DuplicateTransactionError)) throw classified\n }\n const { nextAction: _nextAction, ...ready } = receipt\n const submitted: BridgeReceipt = {\n ...ready,\n status: 'DESTINATION_CONFIRMING',\n destinationTxId: transactionId,\n protocolState: {\n ...ready.protocolState,\n preparedDestinationTransaction: undefined,\n },\n }\n await params.onCheckpoint?.(createBridgeCheckpoint(plan, submitted))\n return { kind: 'aleo-xreserve', transactionId, receipt: submitted }\n }\n const { nextAction: _nextAction, ...deposit } = receipt\n // No proved transaction was recovered, so this is the only point where the\n // destination wallet may be asked to prove and authorize the private mint.\n const result = await completePrivateMint(\n registry,\n requireAleoClientWithWallet(registry, clients, route.destinationChain.id, 'complete xReserve private mint').walletClient,\n {\n plan,\n deposit: { ...deposit, status: 'ATTESTATION_PENDING' },\n attestation: { status: 'complete', payload, messageHash, attestation },\n privateFee: params.privateFee,\n onProgress: params.onProgress,\n onPrepared: params.onCheckpoint\n ? async (transaction) => params.onCheckpoint?.(createBridgeCheckpoint(plan, {\n ...receipt,\n id: transaction.id,\n protocolState: {\n ...receipt.protocolState,\n preparedDestinationTransaction: JSON.stringify(transaction),\n },\n }))\n : undefined,\n privateMintSecretNonce: params.privateMintSecretNonce,\n onSubmitted: params.onCheckpoint\n ? async (submitted) => params.onCheckpoint?.(createBridgeCheckpoint(plan, submitted))\n : undefined,\n },\n )\n return { kind: 'aleo-xreserve', ...result }\n}\n","import { transactionStatus } from '@provablehq/veil-core'\nimport { isHash } from 'viem'\nimport { requireAleoClient, requireEvmClient, requireSolanaClient, type BridgeChainClients } from '../connections/resolve.js'\nimport { BridgeError } from '../errors/bridgeErrors.js'\nimport type { GetStatusParameters } from '../types/actions.js'\nimport type { BridgeReceipt, BridgeRegistry } from '../types/protocol.js'\nimport type { XReserveHttpTransport } from '../types/xreserve.js'\nimport { getAttestation, getSourceStatus } from '../protocols/xreserve/evmToAleo.js'\nimport { resolveTransferRoute } from './internal/resolveTransferRoute.js'\nimport { aleoAddressToBytes32, xReserveDepositNonceFromPayload } from '../utils/xreserve.js'\nimport { getSourceStatus as getEvmHyperlaneSourceStatus } from '../protocols/hyperlane/evm.js'\nimport { getSourceStatus as getSolanaHyperlaneSourceStatus } from '../protocols/hyperlane/solana.js'\nimport { readDestinationBalance } from './internal/readDestinationBalance.js'\nimport { readHyperlaneDelivery } from '../utils/hyperlaneDelivery.js'\nimport { readXReserveDelivery } from '../utils/xreserveDelivery.js'\n\nfunction withoutNextAction(receipt: BridgeReceipt): Omit<BridgeReceipt, 'nextAction'> {\n const { nextAction: _nextAction, ...rest } = receipt\n return rest\n}\n\n/**\n * Checks one stage of an in-progress cross-chain transfer.\n *\n * The action checks the relevant source chain, bridge provider, or destination\n * chain once. The result advances when that stage has completed and otherwise\n * remains unchanged, which suits refresh buttons and scheduled background jobs.\n *\n * The action does not request a signature, submit a transaction, or move funds.\n *\n * @param registry Supported chains, assets, and bridge provider deployments.\n * @param clients Network access for the chains involved in the transfer.\n * @param client HTTP access for bridge provider status checks.\n * @param params Transfer details, latest receipt, and optional cancellation signal.\n * @returns The latest known state after one network or provider check.\n * @throws BridgeError When the receipt does not belong to the transfer, required network access is unavailable, or a provider returns invalid data.\n * @example const receipt = await getStatus(registry, clients, fetch, { plan, receipt: checkpoint })\n */\nexport async function getStatus(\n registry: BridgeRegistry,\n clients: BridgeChainClients,\n client: XReserveHttpTransport,\n params: GetStatusParameters,\n): Promise<BridgeReceipt> {\n const route = resolveTransferRoute(registry, params.plan)\n const receipt = params.receipt\n if (receipt.protocol !== params.plan.protocol || receipt.protocolState.routeId !== params.plan.route.id) {\n throw new BridgeError('Bridge receipt does not match the prepared route')\n }\n // Terminal receipts are facts already established by an earlier chain read.\n // Checking them again must not route into a protocol-specific pending branch.\n if (receipt.status === 'COMPLETED' || receipt.status === 'FAILED' || receipt.status === 'EXPIRED') {\n return receipt\n }\n\n if (receipt.status === 'SOURCE_APPROVAL_PENDING' && route.sourceChain.family === 'evm') {\n // Approval does not move bridge funds. Once confirmed, stop at an explicit\n // wallet boundary so an application can decide when to submit the deposit.\n if (!isHash(receipt.id)) throw new BridgeError('Bridge receipt is missing its EVM approval transaction id')\n const evm = requireEvmClient(registry, clients, route.sourceChain.id)\n const result = await evm.publicClient.getTransactionReceipt(receipt.id)\n if (!result) return receipt\n if (result.status === 'reverted') {\n return {\n ...withoutNextAction(receipt),\n status: 'FAILED',\n protocolState: { ...receipt.protocolState, sourceError: `EVM approval transaction reverted: ${receipt.id}` },\n }\n }\n return { ...receipt, status: 'SOURCE_SUBMISSION_PENDING' }\n }\n\n if (receipt.status === 'SOURCE_CONFIRMING' && route.sourceChain.family === 'aleo') {\n // Aleo acceptance is the irreversible source boundary. Rejection is a\n // terminal source failure; an unresolved transaction remains observable.\n const transactionId = receipt.sourceTxId\n if (!transactionId) throw new BridgeError('Bridge receipt is missing its Aleo source transaction id')\n const aleo = requireAleoClient(registry, clients, route.sourceChain.id)\n const result = await transactionStatus(aleo.publicClient, { transactionId })\n if (result.status === 'accepted') {\n return { ...withoutNextAction(receipt), status: 'DELIVERY_PENDING' }\n }\n if (result.status === 'rejected') {\n return {\n ...withoutNextAction(receipt),\n status: 'FAILED',\n protocolState: { ...receipt.protocolState, sourceError: result.error ?? 'Aleo transaction was rejected' },\n }\n }\n return receipt\n }\n\n if (receipt.status === 'SOURCE_CONFIRMING'\n && route.route.protocol === 'hyperlane'\n && route.sourceChain.family === 'evm') {\n // EVM Hyperlane confirmation also verifies the dispatch event and extracts\n // the message id used for canonical destination Mailbox checks.\n return getEvmHyperlaneSourceStatus(\n registry,\n requireEvmClient(registry, clients, route.sourceChain.id),\n params.plan,\n aleoAddressToBytes32(params.plan.recipient),\n receipt,\n )\n }\n\n if (receipt.status === 'SOURCE_CONFIRMING'\n && route.route.protocol === 'hyperlane'\n && route.sourceChain.family === 'solana') {\n // Solana confirmation reads the Mailbox log for the same cross-chain\n // message id after the signature reaches confirmed or finalized status.\n return getSolanaHyperlaneSourceStatus(\n requireSolanaClient(registry, clients, route.sourceChain.id),\n receipt,\n )\n }\n\n if (receipt.status === 'DELIVERY_PENDING'\n && route.route.protocol === 'hyperlane'\n && receipt.messageId\n && (route.destinationChain.family === 'aleo' || route.destinationChain.family === 'evm')) {\n // The destination Mailbox is the canonical delivery authority. Explorer\n // APIs are intentionally not used because indexing lag is not chain state.\n const destinationClient = route.destinationChain.family === 'aleo'\n ? requireAleoClient(registry, clients, route.destinationChain.id)\n : requireEvmClient(registry, clients, route.destinationChain.id)\n const mailbox = route.destinationChain.family === 'aleo'\n ? route.route.metadata?.aleoMailboxProgram\n : route.route.metadata?.mailboxAddress\n if (typeof mailbox !== 'string' || !mailbox) {\n throw new BridgeError(`Hyperlane destination mailbox is not configured for ${route.route.id}`)\n }\n const delivered = await readHyperlaneDelivery(destinationClient, { messageId: receipt.messageId, mailbox })\n if (!delivered) return receipt\n return { ...withoutNextAction(receipt), status: 'COMPLETED' }\n }\n\n if (receipt.status === 'DELIVERY_PENDING'\n && route.route.protocol === 'hyperlane'\n && route.sourceChain.family === 'aleo') {\n // Some Aleo-origin transfers do not expose a recoverable message id. For\n // those routes, compare the destination balance against the pre-submit\n // baseline captured by execute().\n const before = receipt.protocolState.destinationBalanceBeforeAtomic\n const expected = receipt.protocolState.expectedDestinationIncreaseAtomic\n if (typeof before !== 'string' || !/^\\d+$/.test(before)\n || typeof expected !== 'string' || !/^\\d+$/.test(expected)) {\n return receipt\n }\n const current = await readDestinationBalance(registry, clients, params.plan)\n if (current === undefined) {\n throw new BridgeError(`No supported destination balance verifier is configured for ${route.destinationChain.id}`)\n }\n if (current < BigInt(before) + BigInt(expected)) return receipt\n return { ...withoutNextAction(receipt), status: 'COMPLETED' }\n }\n\n if (route.route.protocol === 'hyperlane') {\n return receipt\n }\n\n // Circle's Aleo-to-EVM relayer does not expose a canonical delivery query in\n // the current integration. Preserve the last verified source state so a\n // caller can continue displaying or persisting it instead of receiving an\n // unrelated unsupported-route error.\n if (receipt.status === 'DELIVERY_PENDING'\n && route.route.protocol === 'xreserve'\n && route.sourceChain.family === 'aleo'\n && route.destinationChain.family === 'evm') {\n return receipt\n }\n\n if (route.route.protocol !== 'xreserve' || route.sourceChain.family !== 'evm' || route.destinationChain.family !== 'aleo') {\n throw new BridgeError('Status refresh is not implemented for this bridge route')\n }\n\n const shouldCheckDelivery = receipt.status === 'ATTESTATION_PENDING'\n || receipt.status === 'DELIVERY_PENDING'\n || receipt.status === 'DESTINATION_ACTION_REQUIRED'\n if (receipt.status === 'DELIVERY_PENDING' && !clients[route.destinationChain.id]) {\n throw new BridgeError(`An Aleo client is required to verify xReserve delivery on chain \"${route.destinationChain.id}\"`)\n }\n if (shouldCheckDelivery && clients[route.destinationChain.id]) {\n const storedNonce = receipt.protocolState.nonce\n const payload = receipt.protocolState.payload\n const nonce = typeof storedNonce === 'string'\n ? storedNonce\n : typeof payload === 'string'\n ? xReserveDepositNonceFromPayload(payload as `0x${string}`)\n : undefined\n const bridgeProgram = receipt.protocolState.bridgeProgram ?? route.route.metadata?.bridgeProgram\n // Every inbound mint mode consumes the same Circle nonce. Reading that\n // destination nullifier first makes completion independent of stale local\n // UI state, a missing private scalar, or an already-used attestation.\n if (typeof nonce === 'string' && typeof bridgeProgram === 'string') {\n const delivered = await readXReserveDelivery(\n requireAleoClient(registry, clients, route.destinationChain.id),\n { bridgeProgram, nonce },\n )\n if (delivered) return { ...withoutNextAction(receipt), status: 'COMPLETED' }\n }\n }\n\n if (receipt.status === 'SOURCE_CONFIRMING') {\n return getSourceStatus(\n registry,\n requireEvmClient(registry, clients, route.sourceChain.id),\n params.plan,\n receipt,\n )\n }\n\n if (receipt.status === 'ATTESTATION_PENDING') {\n // Circle's attestation authorizes destination minting. Public and record\n // delivery is provider-managed; private delivery must stop for an Aleo\n // wallet because only the recipient can submit the wrapper mint.\n const messageHash = receipt.protocolState.messageHash\n if (typeof messageHash !== 'string' || !isHash(messageHash)) {\n throw new BridgeError('xReserve receipt is missing its Circle message hash')\n }\n const attestation = await getAttestation(registry, client, {\n routeId: params.plan.route.id,\n messageHash,\n signal: params.signal,\n })\n if (attestation.status === 'pending') return receipt\n if (params.plan.mintMode !== 'private') {\n return { ...receipt, status: 'DELIVERY_PENDING', protocolState: { ...receipt.protocolState, attestation: attestation.attestation } }\n }\n return {\n ...receipt,\n status: 'DESTINATION_ACTION_REQUIRED',\n nextAction: { kind: 'xreserve-private-mint', chainId: route.destinationChain.id },\n protocolState: { ...receipt.protocolState, attestation: attestation.attestation },\n }\n }\n\n if (receipt.status === 'DESTINATION_ACTION_REQUIRED') return receipt\n\n if (receipt.status === 'DESTINATION_CONFIRMING') {\n // Private inbound xReserve is complete only after the recipient's Aleo mint\n // is accepted. A rejected mint fails delivery without changing the source deposit.\n const transactionId = receipt.destinationTxId\n if (!transactionId) throw new BridgeError('xReserve receipt is missing its Aleo destination transaction id')\n const aleo = requireAleoClient(registry, clients, route.destinationChain.id)\n const result = await transactionStatus(aleo.publicClient, { transactionId })\n if (result.status === 'accepted') {\n return { ...withoutNextAction(receipt), status: 'COMPLETED' }\n }\n if (result.status === 'rejected') {\n return {\n ...withoutNextAction(receipt),\n status: 'FAILED',\n protocolState: { ...receipt.protocolState, destinationError: result.error ?? 'Aleo transaction was rejected' },\n }\n }\n return receipt\n }\n\n return receipt\n}\n","import { readContract } from '@provablehq/veil-core'\nimport { decodeFunctionResult, encodeFunctionData, getAddress, hexToBytes, isAddress, isHash, parseAbi } from 'viem'\nimport type { AleoClient } from '../connections/aleo.js'\nimport type { EvmClient } from '../connections/evm.js'\nimport { BridgeError } from '../errors/bridgeErrors.js'\n\nconst EVM_MAILBOX_ABI = parseAbi(['function delivered(bytes32 id) view returns (bool)'])\n\n/**\n * Selects the destination mailbox and dispatched Hyperlane message to verify.\n *\n * @property mailbox Destination Mailbox contract address or Aleo program id.\n * @property messageId Canonical 32-byte Hyperlane message identifier.\n */\nexport type ReadHyperlaneDeliveryParameters = {\n mailbox: string\n messageId: string\n}\n\nfunction littleEndianU128(bytes: Uint8Array): bigint {\n let value = 0n\n for (let index = 0; index < bytes.length; index++) {\n value |= BigInt(bytes[index]!) << BigInt(index * 8)\n }\n return value\n}\n\n/** Encodes a 32-byte Hyperlane message id as the two little-endian u128 limbs used by the Aleo Mailbox mapping key. */\nfunction aleoDeliveryKey(messageId: `0x${string}`): string {\n const bytes = hexToBytes(messageId)\n const first = littleEndianU128(bytes.slice(0, 16))\n const second = littleEndianU128(bytes.slice(16, 32))\n return `{ id: [${first}u128, ${second}u128] }`\n}\n\n/**\n * Checks whether the destination Hyperlane Mailbox accepted a transfer message.\n *\n * The Mailbox contract or program is the authoritative delivery record, unlike\n * a third-party explorer that may lag or omit a route. The helper reads the\n * destination chain once and never requests a signature or moves funds.\n *\n * @param client Destination EVM or Aleo network access used to read the Mailbox.\n * @param params Hyperlane message identifier and the destination Mailbox contract or program.\n * @returns Whether the destination chain has recorded the message as delivered.\n * @throws BridgeError When the message identifier is invalid or the Mailbox does not belong to the destination chain family.\n * @example const delivered = await readHyperlaneDelivery(client, { messageId, mailbox: 'hyp_mailbox.aleo' })\n */\nexport async function readHyperlaneDelivery(\n client: AleoClient | EvmClient,\n params: ReadHyperlaneDeliveryParameters,\n): Promise<boolean> {\n if (!isHash(params.messageId)) throw new BridgeError('Hyperlane delivery requires a 32-byte message id')\n\n if (client.family === 'aleo') {\n if (!params.mailbox.endsWith('.aleo')) throw new BridgeError(`Invalid Aleo Hyperlane mailbox program: ${params.mailbox}`)\n // Aleo stores successful deliveries by a struct containing two u128 limbs;\n // mapping presence, not a third-party API, is the acceptance signal.\n return await readContract(client.publicClient, {\n programId: params.mailbox,\n mapping: 'deliveries',\n key: aleoDeliveryKey(params.messageId),\n }) !== null\n }\n\n if (!isAddress(params.mailbox)) throw new BridgeError(`Invalid EVM Hyperlane mailbox address: ${params.mailbox}`)\n const mailbox = getAddress(params.mailbox)\n // EVM Mailboxes expose the same canonical state through delivered(bytes32).\n const data = encodeFunctionData({\n abi: EVM_MAILBOX_ABI,\n functionName: 'delivered',\n args: [params.messageId],\n })\n const result = await client.publicClient.call({ to: mailbox, data })\n return decodeFunctionResult({ abi: EVM_MAILBOX_ABI, functionName: 'delivered', data: result })\n}\n","import { readContract } from '@provablehq/veil-core'\nimport { isHash } from 'viem'\nimport type { AleoClient } from '../connections/aleo.js'\nimport { BridgeError } from '../errors/bridgeErrors.js'\nimport { xReserveHexToAleoBytes } from './xreserve.js'\n\n/**\n * Selects the destination xReserve program and deposit to verify.\n *\n * @property bridgeProgram Destination Aleo bridge program that mints the asset.\n * @property nonce Canonical 32-byte Circle deposit nonce emitted on the source chain.\n */\nexport type ReadXReserveDeliveryParameters = {\n bridgeProgram: string\n nonce: string\n}\n\n/**\n * Checks whether an inbound xReserve deposit has already minted on Aleo.\n *\n * The Aleo bridge program records every completed public, record, and private\n * mint under the deposit nonce. Call this before offering or retrying a mint so\n * a refreshed application does not ask the recipient to complete settled funds.\n *\n * @param client Destination Aleo network access used to read the bridge program.\n * @param params Aleo bridge program and Circle deposit nonce emitted on Ethereum.\n * @returns Whether Aleo has finalized a mint for this deposit.\n * @throws BridgeError When the bridge program or nonce is malformed.\n * @example const delivered = await readXReserveDelivery(client, { bridgeProgram: 'usdcx_bridge_v2.aleo', nonce })\n */\nexport async function readXReserveDelivery(\n client: AleoClient,\n params: ReadXReserveDeliveryParameters,\n): Promise<boolean> {\n if (!params.bridgeProgram.endsWith('.aleo')) {\n throw new BridgeError(`Invalid Aleo xReserve bridge program: ${params.bridgeProgram}`)\n }\n if (!isHash(params.nonce)) throw new BridgeError('xReserve delivery requires a 32-byte deposit nonce')\n\n const value = await readContract(client.publicClient, {\n programId: params.bridgeProgram,\n mapping: 'nullifier',\n key: xReserveHexToAleoBytes(params.nonce, 32),\n })\n if (value === null) return false\n if (typeof value !== 'string') throw new BridgeError('Aleo xReserve bridge returned an invalid nullifier value')\n return value.trim() === 'true'\n}\n","import type { BridgePlan, BridgeProgress, BridgeReceipt } from '../../types/protocol.js'\n\n/** Selects the provider or chain failure recorded in a terminal receipt for display to an operator. */\nfunction failureMessage(receipt: BridgeReceipt): string {\n const state = receipt.protocolState\n const message = state.destinationError ?? state.sourceError\n return typeof message === 'string' ? message : `Bridge transfer ended in ${receipt.status}`\n}\n\n/**\n * Translates protocol status into the one operation an application can perform next.\n *\n * The result separates observation (`wait`) from wallet authorization\n * (`resume` or `complete`) and terminal outcomes (`done` or `failed`). It does\n * not read a network, request a signature, submit a transaction, or store state.\n */\nexport function toBridgeProgress(plan: BridgePlan, receipt: BridgeReceipt): BridgeProgress {\n // Source submission pending means approvals or pre-broadcast proving finished,\n // but the fund-moving source transaction still needs explicit authorization.\n if (receipt.status === 'SOURCE_SUBMISSION_PENDING') return { next: 'resume', plan, receipt }\n // Destination action required is currently xReserve private mint: Circle has\n // attested the deposit, but the Aleo recipient still must authorize delivery.\n if (receipt.status === 'DESTINATION_ACTION_REQUIRED') return { next: 'complete', plan, receipt }\n if (receipt.status === 'COMPLETED') return { next: 'done', plan, receipt }\n if (receipt.status === 'FAILED' || receipt.status === 'EXPIRED') {\n return { next: 'failed', plan, receipt, error: failureMessage(receipt) }\n }\n return { next: 'wait', plan, receipt }\n}\n","import { BridgeError } from '../errors/bridgeErrors.js'\nimport { requireEvmClient, type BridgeChainClients } from '../connections/resolve.js'\nimport type { RecoverParameters } from '../types/actions.js'\nimport type { BridgeProgress, BridgeReceipt, BridgeRegistry } from '../types/protocol.js'\nimport type { XReserveHttpTransport } from '../types/xreserve.js'\nimport { recoverSourceCheckpoint } from '../protocols/xreserve/evmToAleo.js'\nimport { recoverSourceCheckpoint as recoverEvmHyperlaneSource } from '../protocols/hyperlane/evm.js'\nimport { aleoAddressToBytes32 } from '../utils/xreserve.js'\nimport { getStatus } from './getStatus.js'\nimport { resolveTransferRoute } from './internal/resolveTransferRoute.js'\nimport { prepare } from './prepare.js'\nimport { toBridgeProgress } from './internal/toBridgeProgress.js'\n\n/**\n * Reconstructs an interrupted cross-chain transfer from a saved checkpoint.\n *\n * The action determines which transactions were submitted, which stages have\n * completed, and whether the transfer is still moving, finished, failed, or\n * waiting for another wallet authorization.\n *\n * Recovery reads existing network and provider state. It never repeats a\n * transaction or moves funds.\n *\n * @param registry Supported chains, assets, and bridge provider deployments.\n * @param clients Network access for the chains involved in the transfer.\n * @param client HTTP access for bridge provider status checks.\n * @param params Saved route, amount, recipient, and submitted transaction identifiers.\n * @returns The current transfer state and whether to wait, resume source submission, authorize destination completion, or stop.\n * @throws BridgeError When the saved information is invalid, no longer matches the configured route, or describes an unsupported recovery path.\n * @example const progress = await recover(registry, clients, fetch, { checkpoint })\n */\nexport async function recover(\n registry: BridgeRegistry,\n clients: BridgeChainClients,\n client: XReserveHttpTransport,\n params: RecoverParameters,\n): Promise<BridgeProgress> {\n const checkpoint = params.checkpoint\n if (checkpoint.version !== 1 || !checkpoint.intent || !checkpoint.route) {\n throw new BridgeError('Bridge checkpoint format is invalid or unsupported')\n }\n // Rebuild route details from the current reviewed catalog instead of trusting\n // serialized contracts or programs from an older application process.\n const plan = prepare(registry, checkpoint.intent)\n const route = resolveTransferRoute(registry, plan)\n if (checkpoint.version !== 1\n || checkpoint.route.id !== plan.route.id\n || checkpoint.route.registryVersion !== plan.registryVersion) {\n throw new BridgeError('Bridge checkpoint does not match the prepared route')\n }\n let receipt: BridgeReceipt\n if (route.sourceChain.family === 'aleo') {\n // Aleo can checkpoint after proving but before broadcast. This state needs\n // no network read: resume() can submit the exact immutable transaction.\n const deliveryVerification = checkpoint.deliveryVerification\n ? {\n destinationBalanceBeforeAtomic: checkpoint.deliveryVerification.balanceBeforeAtomic,\n expectedDestinationIncreaseAtomic: checkpoint.deliveryVerification.expectedIncreaseAtomic,\n }\n : {}\n const prepared = checkpoint.source?.preparedTransaction\n if (prepared && !checkpoint.source?.transactionId) {\n if (checkpoint.destination || (checkpoint.source?.approvalTransactionIds?.length ?? 0) > 0) {\n throw new BridgeError('Bridge checkpoint contains transactions that are invalid for a prepared Aleo source route')\n }\n let decoded: unknown\n try {\n decoded = JSON.parse(prepared.serializedTransaction)\n } catch (error) {\n throw new BridgeError('Bridge checkpoint contains an invalid prepared Aleo transaction', { cause: error })\n }\n if (!decoded || typeof decoded !== 'object'\n || (decoded as { id?: unknown }).id !== prepared.transactionId) {\n throw new BridgeError('Bridge checkpoint prepared Aleo transaction id does not match its payload')\n }\n return toBridgeProgress(plan, {\n id: prepared.transactionId,\n protocol: plan.protocol,\n status: 'SOURCE_SUBMISSION_PENDING',\n protocolState: {\n routeId: checkpoint.route.id,\n preparedTransaction: prepared.serializedTransaction,\n ...deliveryVerification,\n },\n })\n }\n if (!checkpoint.source?.transactionId) {\n throw new BridgeError('Bridge checkpoint contains no submitted source transaction')\n }\n if (checkpoint.destination || (checkpoint.source.approvalTransactionIds?.length ?? 0) > 0) {\n throw new BridgeError('Bridge checkpoint contains transactions that are invalid for an Aleo source route')\n }\n // A submitted Aleo source transaction is never rebroadcast during recovery;\n // inspect its ledger status once and expose the next caller operation.\n receipt = await getStatus(registry, clients, client, {\n plan,\n receipt: {\n id: checkpoint.source.transactionId,\n protocol: plan.protocol,\n status: 'SOURCE_CONFIRMING',\n sourceTxId: checkpoint.source.transactionId,\n protocolState: { routeId: checkpoint.route.id, ...deliveryVerification },\n },\n signal: params.signal,\n })\n return toBridgeProgress(plan, receipt)\n }\n if (route.sourceChain.family === 'solana') {\n // Solana has one source transaction and no approval phase. Recovery only\n // checks the saved signature and rejects impossible destination state.\n if (!checkpoint.source?.transactionId) {\n throw new BridgeError('Bridge checkpoint contains no submitted source transaction')\n }\n if (checkpoint.destination || (checkpoint.source.approvalTransactionIds?.length ?? 0) > 0) {\n throw new BridgeError('Bridge checkpoint contains transactions that are invalid for a Solana source route')\n }\n const { blockhash, lastValidBlockHeight } = checkpoint.source\n if ((blockhash !== undefined || lastValidBlockHeight !== undefined)\n && (typeof blockhash !== 'string' || !blockhash\n || typeof lastValidBlockHeight !== 'string' || !/^\\d+$/.test(lastValidBlockHeight))) {\n throw new BridgeError('Bridge checkpoint contains an invalid Solana blockhash lifetime')\n }\n receipt = await getStatus(registry, clients, client, {\n plan,\n receipt: {\n id: checkpoint.source.transactionId,\n protocol: plan.protocol,\n status: 'SOURCE_CONFIRMING',\n sourceTxId: checkpoint.source.transactionId,\n protocolState: {\n routeId: checkpoint.route.id,\n ...(typeof blockhash === 'string' && typeof lastValidBlockHeight === 'string'\n ? { blockhash, lastValidBlockHeight }\n : {}),\n },\n },\n signal: params.signal,\n })\n return toBridgeProgress(plan, receipt)\n }\n if (route.route.protocol === 'hyperlane' && route.sourceChain.family === 'evm') {\n // EVM Hyperlane may have one or more token approvals before its dispatch.\n // The protocol helper determines which submitted boundary was reached.\n if (checkpoint.destination) {\n throw new BridgeError('Bridge checkpoint contains a destination transaction that is invalid for this Hyperlane route')\n }\n receipt = await recoverEvmHyperlaneSource(\n registry,\n requireEvmClient(registry, clients, route.sourceChain.id),\n plan,\n aleoAddressToBytes32(plan.recipient),\n checkpoint,\n )\n return toBridgeProgress(plan, receipt)\n }\n if (route.route.protocol !== 'xreserve'\n || route.sourceChain.family !== 'evm'\n || route.destinationChain.family !== 'aleo') {\n throw new BridgeError('Bridge checkpoint recovery is not implemented for this route')\n }\n // EVM xReserve likewise separates token approval from the irreversible\n // deposit, then may add a caller-authorized private mint on Aleo.\n receipt = await recoverSourceCheckpoint(\n registry,\n requireEvmClient(registry, clients, route.sourceChain.id),\n plan,\n checkpoint,\n )\n const preparedDestination = checkpoint.destination?.preparedTransaction\n // A destination transaction is either proved or submitted, never both.\n // Keeping those states exclusive prevents recovery from minting twice.\n if (preparedDestination && checkpoint.destination?.transactionId) {\n throw new BridgeError('Bridge checkpoint cannot contain both prepared and submitted destination transactions')\n }\n if (preparedDestination) {\n let decoded: unknown\n try {\n decoded = JSON.parse(preparedDestination.serializedTransaction)\n } catch (error) {\n throw new BridgeError('Bridge checkpoint contains an invalid prepared Aleo destination transaction', { cause: error })\n }\n if (!decoded || typeof decoded !== 'object'\n || (decoded as { id?: unknown }).id !== preparedDestination.transactionId) {\n throw new BridgeError('Bridge checkpoint prepared Aleo destination transaction id does not match its payload')\n }\n }\n if (checkpoint.destination?.transactionId) {\n // A submitted private mint is observed as destination confirmation; it is\n // never routed back through the wallet.\n receipt = {\n ...receipt,\n status: 'DESTINATION_CONFIRMING',\n destinationTxId: checkpoint.destination.transactionId,\n }\n }\n if (receipt.status === 'ATTESTATION_PENDING' || receipt.status === 'DESTINATION_CONFIRMING') {\n receipt = await getStatus(registry, clients, client, {\n plan,\n receipt,\n signal: params.signal,\n })\n }\n if (preparedDestination) {\n // Preserve the proved transaction only while Circle's attestation still\n // requires the same private destination action.\n if (receipt.status !== 'DESTINATION_ACTION_REQUIRED') {\n throw new BridgeError('Prepared destination transaction is no longer valid for the recovered bridge state')\n }\n receipt = {\n ...receipt,\n id: preparedDestination.transactionId,\n protocolState: {\n ...receipt.protocolState,\n preparedDestinationTransaction: preparedDestination.serializedTransaction,\n },\n }\n }\n return toBridgeProgress(plan, receipt)\n}\n","import { classifyBroadcastError, DuplicateTransactionError } from '@provablehq/veil-core'\nimport { requireAleoClient, requireEvmClientWithWallet, type BridgeChainClients } from '../connections/resolve.js'\nimport { BridgeError } from '../errors/bridgeErrors.js'\nimport * as evmHyperlane from '../protocols/hyperlane/evm.js'\nimport * as evmToAleoXReserve from '../protocols/xreserve/evmToAleo.js'\nimport type { ResumeParameters, BridgeExecution } from '../types/actions.js'\nimport type { BridgeRegistry, BridgeReceipt } from '../types/protocol.js'\nimport { aleoAddressToBytes32 } from '../utils/xreserve.js'\nimport { createBridgeCheckpoint } from './createBridgeCheckpoint.js'\nimport { resolveTransferRoute } from './internal/resolveTransferRoute.js'\n\n/**\n * Submits the source-chain transaction left unfinished after an interruption.\n *\n * This applies when a token approval succeeded without the following deposit,\n * or an Aleo transaction was fully proved before the application stopped. Only\n * the pending submission continues. A proved Aleo transaction may be\n * rebroadcast byte-for-byte with the same transaction identifier, so recovery\n * cannot create a second transfer.\n *\n * The action may request authorization from the source wallet. A submitted\n * transaction can commit funds and incur a network fee.\n *\n * @param registry Supported chains, assets, and bridge provider deployments.\n * @param clients Network and wallet access for the source chain.\n * @param params Recovered transfer state, confirmation controls, and an optional callback for saving the new submission.\n * @returns The submitted transaction identifier and the updated state of the in-progress transfer.\n * @throws BridgeError When no source transaction remains to be submitted, required wallet access is unavailable, or submission fails.\n * @example const execution = await resume(registry, clients, { progress })\n */\nexport async function resume(\n registry: BridgeRegistry,\n clients: BridgeChainClients,\n params: ResumeParameters,\n): Promise<BridgeExecution> {\n const { plan, receipt } = params.progress\n if (params.progress.next !== 'resume' || receipt.status !== 'SOURCE_SUBMISSION_PENDING') {\n throw new BridgeError('Bridge progress has no source submission to resume')\n }\n const route = resolveTransferRoute(registry, plan)\n const onSubmitted = params.onCheckpoint\n ? async (value: BridgeReceipt) => params.onCheckpoint?.(createBridgeCheckpoint(plan, value))\n : undefined\n\n if (route.sourceChain.family === 'aleo') {\n // This checkpoint was written after proving and before broadcast. Validate\n // that the serialized transaction carries the saved id before sending bytes\n // to the node; recovery must not substitute or rebuild a transaction.\n const serializedTransaction = receipt.protocolState.preparedTransaction\n if (typeof serializedTransaction !== 'string' || !serializedTransaction) {\n throw new BridgeError('Prepared Aleo recovery is missing its serialized transaction')\n }\n let decoded: unknown\n try {\n decoded = JSON.parse(serializedTransaction)\n } catch (error) {\n throw new BridgeError('Prepared Aleo recovery contains an invalid serialized transaction', { cause: error })\n }\n const transactionId = decoded && typeof decoded === 'object'\n ? (decoded as { id?: unknown }).id\n : undefined\n if (typeof transactionId !== 'string' || transactionId !== receipt.id) {\n throw new BridgeError('Prepared Aleo recovery transaction id does not match its payload')\n }\n try {\n const submittedId = await requireAleoClient(\n registry,\n clients,\n route.sourceChain.id,\n ).publicClient.request({\n method: 'sendTransaction',\n params: { transaction: serializedTransaction },\n }) as string\n if (submittedId !== transactionId) {\n throw new BridgeError(`Aleo node returned transaction id ${submittedId}; expected ${transactionId}`)\n }\n } catch (error) {\n if (error instanceof BridgeError) throw error\n const classified = classifyBroadcastError(error, transactionId)\n // Re-broadcasting the identical prepared transaction after a crash is\n // idempotent: the ledger's duplicate response means submission won the\n // race with the process failure.\n if (!(classified instanceof DuplicateTransactionError)) throw classified\n }\n // Once broadcast succeeds (or the node reports the same transaction as a\n // duplicate), discard the serialized bytes and retain only public tracking state.\n const submitted: BridgeReceipt = {\n id: transactionId,\n protocol: plan.protocol,\n status: 'SOURCE_CONFIRMING',\n sourceTxId: transactionId,\n protocolState: {\n routeId: plan.route.id,\n ...(typeof receipt.protocolState.destinationBalanceBeforeAtomic === 'string'\n ? { destinationBalanceBeforeAtomic: receipt.protocolState.destinationBalanceBeforeAtomic }\n : {}),\n ...(typeof receipt.protocolState.expectedDestinationIncreaseAtomic === 'string'\n ? { expectedDestinationIncreaseAtomic: receipt.protocolState.expectedDestinationIncreaseAtomic }\n : {}),\n },\n }\n await onSubmitted?.(submitted)\n return plan.protocol === 'hyperlane'\n ? { kind: 'aleo-hyperlane', transactionId, receipt: submitted }\n : { kind: 'aleo-xreserve', transactionId, receipt: submitted }\n }\n\n if (route.route.protocol === 'xreserve' && route.sourceChain.family === 'evm') {\n // The EVM protocol helper accepts only approval-complete state here and\n // requotes allowance, fees, and private hook data before depositing.\n const execution = await evmToAleoXReserve.execute(\n registry,\n requireEvmClientWithWallet(registry, clients, route.sourceChain.id, 'resume xReserve transfer'),\n {\n plan,\n resume: receipt,\n pollingIntervalMs: params.pollingIntervalMs,\n confirmationTimeoutMs: params.confirmationTimeoutMs,\n onSubmitted,\n privateMintSecretNonce: params.privateMintSecretNonce,\n },\n )\n return { kind: 'evm-xreserve', ...execution }\n }\n if (route.route.protocol === 'hyperlane' && route.sourceChain.family === 'evm') {\n // Hyperlane follows the same approval-complete boundary: the saved approval\n // is observed, while the source dispatch is newly authorized once.\n const execution = await evmHyperlane.execute(\n registry,\n requireEvmClientWithWallet(registry, clients, route.sourceChain.id, 'resume Hyperlane transfer'),\n {\n plan,\n recipientBytes32: aleoAddressToBytes32(plan.recipient),\n resume: receipt,\n pollingIntervalMs: params.pollingIntervalMs,\n confirmationTimeoutMs: params.confirmationTimeoutMs,\n onSubmitted,\n },\n )\n return { kind: 'evm-hyperlane', ...execution }\n }\n throw new BridgeError('Source resumption is not implemented for this bridge route')\n}\n","import type { BridgeChainClients } from '../connections/resolve.js'\nimport { BridgeError } from '../errors/bridgeErrors.js'\nimport type { WaitParameters } from '../types/actions.js'\nimport type { BridgeProgress, BridgeRegistry, BridgeStatus } from '../types/protocol.js'\nimport type { XReserveHttpTransport } from '../types/xreserve.js'\nimport { resolveTransferRoute } from './internal/resolveTransferRoute.js'\nimport { toBridgeProgress } from './internal/toBridgeProgress.js'\nimport { getStatus } from './getStatus.js'\n\nconst CALLER_BOUNDARIES: readonly BridgeStatus[] = [\n 'SOURCE_SUBMISSION_PENDING',\n 'DESTINATION_ACTION_REQUIRED',\n 'COMPLETED',\n 'FAILED',\n 'EXPIRED',\n]\n\n/**\n * Follows a cross-chain transfer until it finishes or requires another wallet authorization.\n *\n * The action monitors source confirmation, provider processing, and destination\n * delivery where those stages can be verified. The result states whether the\n * funds arrived, the transfer failed, or another source- or destination-chain\n * transaction is required.\n *\n * Monitoring does not request a signature, submit a transaction, or move funds.\n *\n * @param registry Supported chains, assets, and bridge provider deployments.\n * @param clients Network access for the chains involved in the transfer.\n * @param client HTTP access for bridge provider status checks.\n * @param params Current transfer state, optional stopping statuses, polling controls, and optional progress callback.\n * @returns The completed or failed transfer, or the next transaction the caller must authorize.\n * @throws BridgeError When the saved state does not belong to the transfer, the wait times out or is cancelled, or a network or provider check fails.\n * @example const next = await wait(registry, clients, fetch, { progress })\n */\nexport async function wait(\n registry: BridgeRegistry,\n clients: BridgeChainClients,\n client: XReserveHttpTransport,\n params: WaitParameters,\n): Promise<BridgeProgress> {\n const { plan, receipt } = params.progress\n if (params.until?.length === 0) throw new BridgeError('wait requires at least one target status when until is provided')\n resolveTransferRoute(registry, plan)\n if (receipt.protocol !== plan.protocol || receipt.protocolState.routeId !== plan.route.id) {\n throw new BridgeError('Bridge progress does not match its reconstructed plan')\n }\n const current = toBridgeProgress(plan, receipt)\n const until = [...new Set([...CALLER_BOUNDARIES, ...(params.until ?? [])])]\n if (current.next !== 'wait' || until.includes(receipt.status)) return current\n const requestedInterval = params.pollingIntervalMs ?? 15_000\n const timeoutMs = params.timeoutMs ?? 20 * 60_000\n if (!Number.isFinite(requestedInterval) || requestedInterval < 0 || !Number.isFinite(timeoutMs) || timeoutMs < 0) {\n throw new BridgeError('Status polling controls must be non-negative finite numbers')\n }\n const interval = requestedInterval === 0 ? 0 : Math.max(100, requestedInterval)\n const deadline = Date.now() + timeoutMs\n let updated = receipt\n\n // Poll one canonical status transition at a time so every observed change can\n // be persisted before another provider or chain read begins.\n while (true) {\n if (params.signal?.aborted) throw new BridgeError('Bridge status polling was cancelled')\n const next = await getStatus(registry, clients, client, { plan, receipt: updated, signal: params.signal })\n if (next !== updated) await params.onUpdate?.(toBridgeProgress(plan, next))\n updated = next\n if (until.includes(updated.status)) return toBridgeProgress(plan, updated)\n if (Date.now() >= deadline) throw new BridgeError(`Bridge status polling timed out in state ${updated.status}`)\n await new Promise<void>((resolve) => setTimeout(resolve, interval))\n }\n}\n","import type { TransactionInput } from '@provablehq/veil-core'\nimport { BridgeError } from '../../errors/bridgeErrors.js'\nimport type { BridgeEndpoint, BridgeRegistry, ProtocolBridgeAsset } from '../../types/protocol.js'\nimport { parseDecimalAmount } from '../../utils/units.js'\n\nconst EMPTY_PROOF = `{ siblings: [${Array(16).fill('0field').join(', ')}], leaf_index: 1u32 }`\n\n/**\n * Supplies the canonical proof pair accepted while an ARC-22 freeze list is empty.\n *\n * The value is computed in memory and does not read Aleo or reveal a record.\n *\n * @example\n * const proof = EMPTY_MERKLE_PROOF_PAIR\n */\nexport const EMPTY_MERKLE_PROOF_PAIR = `[${EMPTY_PROOF}, ${EMPTY_PROOF}]`\n\n/**\n * Resolves an Aleo asset that declares the requested privacy conversion.\n *\n * Reads only the supplied registry. No chain, wallet, or private record is\n * accessed while deciding whether the asset supports the conversion.\n *\n * @param registry Registry containing chain and asset capabilities.\n * @param endpoint Chain and asset key selected by the caller.\n * @param operation Conversion name included in unsupported-asset errors.\n * @returns The matching asset with a declared privacy capability.\n * @throws BridgeError When the asset is unknown, is not on Aleo, or lacks the capability.\n * @example\n * const asset = resolvePrivacyAsset(registry, { chain: 'aleo', asset: 'sol' }, 'shielding')\n */\nexport function resolvePrivacyAsset(registry: BridgeRegistry, endpoint: BridgeEndpoint, operation: 'shielding' | 'unshielding'): ProtocolBridgeAsset & { privacy: NonNullable<ProtocolBridgeAsset['privacy']> } {\n const asset = registry.assets.find((entry) => entry.chainId === endpoint.chain && entry.key === endpoint.asset)\n if (!asset) throw new BridgeError(`Unknown bridge asset: \"${endpoint.chain}/${endpoint.asset}\"`)\n const chain = registry.chains.find((entry) => entry.id === asset.chainId)\n if (chain?.family !== 'aleo' || !asset.privacy) {\n throw new BridgeError(`Bridge asset \"${asset.id}\" does not support ${operation}`)\n }\n return asset as ProtocolBridgeAsset & { privacy: NonNullable<ProtocolBridgeAsset['privacy']> }\n}\n\n/**\n * Converts a positive display amount to its u128 Aleo literal.\n *\n * Computes the exact integer in memory without reading a balance, selecting a\n * private record, or contacting Aleo.\n *\n * @param asset Asset whose decimals determine atomic precision.\n * @param amount Positive decimal amount in display units.\n * @param operation Conversion name included in invalid-amount errors.\n * @returns Exact atomic amount and its u128 literal.\n * @throws BridgeError When the amount is invalid, unrepresentable, or zero.\n * @example\n * privacyAmount(asset, '0.25', 'Shielding')\n */\nexport function privacyAmount(asset: ProtocolBridgeAsset, amount: string, operation: 'Shielding' | 'Unshielding'): { amountAtomic: bigint; literal: string } {\n const amountAtomic = parseDecimalAmount(amount, asset.decimals)\n if (amountAtomic <= 0n) throw new BridgeError(`${operation} amount must be greater than zero`)\n return { amountAtomic, literal: `${amountAtomic}u128` }\n}\n\n/**\n * Builds a wallet-side request for a token record covering an amount.\n *\n * Returns selection criteria rather than record plaintext. A compatible wallet\n * searches its private records only when the later transaction is authorized.\n *\n * @param program Program defining the `Token` record.\n * @param amount Minimum u128 amount the selected record must contain.\n * @returns A record request resolved privately by a compatible wallet.\n * @example\n * privacyRecord('arc20_sol.aleo', '1000000u128')\n */\nexport function privacyRecord(program: string, amount: string): TransactionInput {\n return {\n type: 'record',\n program,\n recordname: 'Token',\n filters: { amount: { gte: amount } },\n }\n}\n","import type { TransactionInput } from '@provablehq/veil-core'\nimport { requireAleoClientWithWallet, type BridgeChainClients } from '../connections/resolve.js'\nimport { BridgeError } from '../errors/bridgeErrors.js'\nimport type { AleoPrivacyExecution, ShieldParameters } from '../types/aleo.js'\nimport type { BridgeRegistry } from '../types/protocol.js'\nimport { privacyAmount, resolvePrivacyAsset } from './internal/aleoPrivacy.js'\n\n/**\n * Converts an Aleo token balance visible on the public ledger into a private record owned by the recipient.\n *\n * A private record stores spendable value without exposing the owner or amount\n * in a public account balance. The Aleo wallet proves and submits the\n * conversion, which spends the public balance and incurs an Aleo transaction\n * fee.\n *\n * @param registry Supported Aleo assets and their public-to-private conversion programs.\n * @param clients Network and wallet access for Aleo.\n * @param params Asset, amount, optional private recipient, fee preference, and proving progress callbacks.\n * @returns The submitted Aleo transaction identifier and exact converted amount.\n * @throws BridgeError When the asset cannot be converted privately, the amount is invalid, required wallet access is unavailable, or submission fails.\n * @example\n * await shield(registry, clients, { asset: { chain: 'aleo', asset: 'sol' }, amount: '0.1' })\n */\nexport async function shield(registry: BridgeRegistry, clients: BridgeChainClients, params: ShieldParameters): Promise<AleoPrivacyExecution> {\n const asset = resolvePrivacyAsset(registry, params.asset, 'shielding')\n const { amountAtomic, literal } = privacyAmount(asset, params.amount, 'Shielding')\n const { walletClient } = requireAleoClientWithWallet(registry, clients, asset.chainId, `shield ${asset.symbol}`)\n // ARC-22 names the private recipient explicitly. ARC-20's shield transition\n // always creates the record for its caller and accepts only the amount.\n const inputs: TransactionInput[] = asset.privacy.kind === 'arc22'\n ? [params.recipient ?? { type: 'address', label: `${asset.symbol} private recipient` }, literal]\n : [literal]\n // The wallet performs proving, signing, and broadcast. A prepared-transaction\n // callback lets applications cover the pre-broadcast crash window without\n // giving this action control of storage.\n const transactionId = await walletClient.executeTransaction({\n program: asset.privacy.program,\n function: asset.privacy.kind === 'arc22' ? 'transfer_public_to_private' : 'shield',\n inputs,\n privateFee: params.privateFee ?? false,\n onProgress: async (event) => {\n await params.onProgress?.(event)\n if (event.type === 'transaction-prepared') await params.onPrepared?.(event.transaction)\n },\n })\n if (!transactionId) throw new BridgeError(`Aleo wallet returned an empty ${asset.symbol} shield transaction id`)\n return { transactionId, assetId: asset.id, amount: params.amount, amountAtomic }\n}\n","import type { TransactionInput } from '@provablehq/veil-core'\nimport { requireAleoClientWithWallet, type BridgeChainClients } from '../connections/resolve.js'\nimport { BridgeError } from '../errors/bridgeErrors.js'\nimport type { AleoPrivacyExecution, UnshieldParameters } from '../types/aleo.js'\nimport type { BridgeRegistry } from '../types/protocol.js'\nimport { EMPTY_MERKLE_PROOF_PAIR, privacyAmount, privacyRecord, resolvePrivacyAsset } from './internal/aleoPrivacy.js'\n\n/**\n * Converts an Aleo private record into a token balance visible on the public ledger.\n *\n * A private record stores spendable value without exposing the owner or amount\n * in a public account balance. The wallet selects a sufficient record unless\n * the caller supplies one, then proves and submits the conversion. The public\n * recipient and amount become visible, and the transaction incurs an Aleo fee.\n *\n * @param registry Supported Aleo assets and their private-to-public conversion programs.\n * @param clients Network and wallet access for Aleo.\n * @param params Asset, amount, optional private record and public recipient, fee preference, freeze-list proof, and proving progress callbacks.\n * @returns The submitted Aleo transaction identifier and exact converted amount.\n * @throws BridgeError When the asset cannot be converted publicly, the amount or private record is invalid, required wallet access is unavailable, or submission fails.\n * @example\n * await unshield(registry, clients, { asset: { chain: 'aleo', asset: 'sol' }, amount: '0.1' })\n */\nexport async function unshield(registry: BridgeRegistry, clients: BridgeChainClients, params: UnshieldParameters): Promise<AleoPrivacyExecution> {\n const asset = resolvePrivacyAsset(registry, params.asset, 'unshielding')\n const { amountAtomic, literal } = privacyAmount(asset, params.amount, 'Unshielding')\n const { walletClient } = requireAleoClientWithWallet(registry, clients, asset.chainId, `unshield ${asset.symbol}`)\n // Leave record selection inside the wallet unless the caller supplies a\n // plaintext record. This keeps private ownership data out of browser and bot\n // application state when the wallet supports structured record requests.\n const record: TransactionInput = params.record ?? privacyRecord(asset.privacy.program, literal)\n // ARC-22 additionally names the public recipient and proves the token is not\n // frozen. The empty-tree proof is the currently supported default; callers\n // can replace it when a token publishes a populated freeze list.\n const inputs: TransactionInput[] = asset.privacy.kind === 'arc22'\n ? [\n params.recipient ?? { type: 'address', label: `${asset.symbol} public recipient` },\n literal,\n record,\n params.merkleProof ?? EMPTY_MERKLE_PROOF_PAIR,\n ]\n : [record, literal]\n // The wallet performs proving, signing, and broadcast. A prepared-transaction\n // callback lets applications cover the pre-broadcast crash window without\n // giving this action control of storage.\n const transactionId = await walletClient.executeTransaction({\n program: asset.privacy.program,\n function: asset.privacy.kind === 'arc22' ? 'transfer_private_to_public' : 'unshield',\n inputs,\n privateFee: params.privateFee ?? false,\n onProgress: async (event) => {\n await params.onProgress?.(event)\n if (event.type === 'transaction-prepared') await params.onPrepared?.(event.transaction)\n },\n })\n if (!transactionId) throw new BridgeError(`Aleo wallet returned an empty ${asset.symbol} unshield transaction id`)\n return { transactionId, assetId: asset.id, amount: params.amount, amountAtomic }\n}\n","import { execute } from '../../actions/execute.js'\nimport { quote } from '../../actions/quote.js'\nimport { complete } from '../../actions/complete.js'\nimport { getStatus } from '../../actions/getStatus.js'\nimport { recover } from '../../actions/recover.js'\nimport { resume } from '../../actions/resume.js'\nimport { wait } from '../../actions/wait.js'\nimport { shield } from '../../actions/shield.js'\nimport { unshield } from '../../actions/unshield.js'\nimport type { BridgeChainClients } from '../../connections/resolve.js'\nimport type { BridgeProgress, BridgeReceipt, BridgeRegistry } from '../../types/protocol.js'\nimport type { CompleteParameters, ExecuteParameters, GetStatusParameters, QuoteParameters, RecoverParameters, ResumeParameters, WaitParameters, BridgeExecution, BridgeQuote } from '../../types/actions.js'\nimport type { AleoPrivacyExecution, ShieldParameters, UnshieldParameters } from '../../types/aleo.js'\n\n/**\n * Carries validated registry and materialized client state into bound actions.\n * @property registry Validated deployment registry.\n * @property clients Materialized chain capabilities keyed by registry chain id.\n * @property fetch Fetch implementation used for protocol HTTP requests.\n */\nexport type BridgeActionsConfig = {\n registry: BridgeRegistry\n clients: BridgeChainClients\n fetch: typeof globalThis.fetch\n}\n\n/**\n * Groups the complete cross-chain transfer lifecycle exposed by a bridge client.\n *\n * Quoting validates the transfer and reads chains or providers where current\n * costs are available. Execution, resumption, completion, shielding, and\n * unshielding can request wallet authorization and move funds.\n */\nexport type BridgeActions = {\n quote: (params: QuoteParameters) => Promise<BridgeQuote>\n execute: (params: ExecuteParameters) => Promise<BridgeExecution>\n getStatus: (params: GetStatusParameters) => Promise<BridgeReceipt>\n complete: (params: CompleteParameters) => Promise<BridgeExecution>\n recover: (params: RecoverParameters) => Promise<BridgeProgress>\n resume: (params: ResumeParameters) => Promise<BridgeExecution>\n wait: (params: WaitParameters) => Promise<BridgeProgress>\n shield: (params: ShieldParameters) => Promise<AleoPrivacyExecution>\n unshield: (params: UnshieldParameters) => Promise<AleoPrivacyExecution>\n}\n\n/**\n * Binds configured chains, wallets, and provider HTTP access to every bridge action.\n *\n * Calling this function only creates closures; it does not contact a chain,\n * request a signature, submit a transaction, move funds, or store state.\n */\nexport function bridgeActions(config: BridgeActionsConfig): BridgeActions {\n return {\n // Every closure injects the same validated route catalog and\n // registry-keyed clients, preventing per-action configuration drift.\n quote: async (params) => quote(config.registry, config.clients, params),\n execute: async (params) => execute(config.registry, config.clients, params),\n getStatus: async (params) => getStatus(config.registry, config.clients, config.fetch, params),\n complete: async (params) => complete(config.registry, config.clients, params),\n recover: async (params) => recover(config.registry, config.clients, config.fetch, params),\n resume: async (params) => resume(config.registry, config.clients, params),\n wait: async (params) => wait(config.registry, config.clients, config.fetch, params),\n shield: async (params) => shield(config.registry, config.clients, params),\n unshield: async (params) => unshield(config.registry, config.clients, params),\n }\n}\n","import type {\n BridgeEnvironment,\n BridgeRegistry,\n ProtocolBridgeAsset,\n ProtocolBridgeChain,\n ProtocolBridgeRoute,\n} from '../types/protocol.js'\nconst EVM_ADDRESS = '^0x[0-9a-fA-F]{40}$'\nconst SOLANA_ADDRESS = '^[1-9A-HJ-NP-Za-km-z]{32,44}$'\nconst ALEO_ADDRESS = '^aleo1[0-9a-z]{58}$'\n\nconst chains: ProtocolBridgeChain[] = [\n { id: 'aleo', displayName: 'Aleo', family: 'aleo', environment: 'mainnet', nativeCurrencySymbol: 'ALEO', protocolDomains: { xreserve: 10002, hyperlane: 1634493807 } },\n { id: 'ethereum', displayName: 'Ethereum', family: 'evm', environment: 'mainnet', nativeCurrencySymbol: 'ETH', protocolDomains: { xreserve: 0, hyperlane: 1 } },\n { id: 'solana', displayName: 'Solana', family: 'solana', environment: 'mainnet', nativeCurrencySymbol: 'SOL', protocolDomains: { hyperlane: 1399811149 } },\n { id: 'base', displayName: 'Base', family: 'evm', environment: 'mainnet', nativeCurrencySymbol: 'ETH' },\n { id: 'hyperevm', displayName: 'HyperEVM', family: 'evm', environment: 'mainnet', nativeCurrencySymbol: 'HYPE' },\n { id: 'aleo-testnet', displayName: 'Aleo Testnet', family: 'aleo', environment: 'testnet', nativeCurrencySymbol: 'ALEO', protocolDomains: { xreserve: 10002, hyperlane: 1617853565 } },\n { id: 'sepolia', displayName: 'Ethereum Sepolia', family: 'evm', environment: 'testnet', nativeCurrencySymbol: 'ETH', protocolDomains: { hyperlane: 11155111 } },\n]\n\nconst assets: ProtocolBridgeAsset[] = [\n { id: 'aleo/aleo', key: 'aleo', chainId: 'aleo', symbol: 'ALEO', name: 'Aleo', decimals: 6, kind: 'native', locator: { kind: 'aleo-program', value: 'credits.aleo' }, addressValidationRegex: ALEO_ADDRESS },\n { id: 'aleo/usdcx', key: 'usdcx', chainId: 'aleo', symbol: 'USDCx', name: 'USDCx', decimals: 6, kind: 'token', locator: { kind: 'aleo-program', value: 'usdcx_stablecoin.aleo' }, addressValidationRegex: ALEO_ADDRESS, privacy: { kind: 'arc22', program: 'usdcx_stablecoin.aleo' } },\n { id: 'aleo/eth', key: 'eth', chainId: 'aleo', symbol: 'ETH', name: 'Hyperlane ETH', decimals: 18, kind: 'token', locator: { kind: 'aleo-program', value: 'hyp_warp_token_eth_v2.aleo', tokenId: 'aleo1t7f29tq9qng2lfvrkpcuvu59jn24hrmzqdyqfn6p0u5p80npfvqqecmkj8' }, addressValidationRegex: ALEO_ADDRESS, privacy: { kind: 'arc20', program: 'arc20_eth.aleo' } },\n { id: 'aleo/wbtc', key: 'wbtc', chainId: 'aleo', symbol: 'WBTC', name: 'Hyperlane WBTC', decimals: 8, kind: 'token', locator: { kind: 'aleo-program', value: 'hyp_warp_token_wbtc_v2.aleo', tokenId: 'aleo1240fsvz2dhmj0cdtt8mc0yc8um9fmu236rqcl2qnlj9703hd2vpsdwyrtf' }, addressValidationRegex: ALEO_ADDRESS, privacy: { kind: 'arc20', program: 'arc20_wbtc.aleo' } },\n { id: 'aleo/usdt', key: 'usdt', chainId: 'aleo', symbol: 'USDT', name: 'Hyperlane USDT', decimals: 6, kind: 'token', locator: { kind: 'aleo-program', value: 'hyp_warp_token_usdt_v2.aleo', tokenId: 'aleo18yynfz0lrfx0tund540vy2z7gju7ekgqsueg5jgu28mpm2z42ufq7qua8y' }, addressValidationRegex: ALEO_ADDRESS, privacy: { kind: 'arc20', program: 'arc20_usdt.aleo' } },\n { id: 'aleo/sol', key: 'sol', chainId: 'aleo', symbol: 'SOL', name: 'Hyperlane SOL', decimals: 9, kind: 'token', locator: { kind: 'aleo-program', value: 'hyp_warp_token_sol_v2.aleo', tokenId: 'aleo1aa0zt0vg9uwknekpqeefkvad55swp7833wc5crp2prv0lm4djuxs5r7k6v' }, addressValidationRegex: ALEO_ADDRESS, privacy: { kind: 'arc20', program: 'arc20_sol.aleo' } },\n { id: 'aleo/usad', key: 'usad', chainId: 'aleo', symbol: 'USAD', name: 'USAD', decimals: 6, kind: 'token', locator: { kind: 'aleo-program', value: 'usad_stablecoin.aleo' }, addressValidationRegex: ALEO_ADDRESS },\n { id: 'ethereum/usdc', key: 'usdc', chainId: 'ethereum', symbol: 'USDC', name: 'USD Coin', decimals: 6, kind: 'token', locator: { kind: 'evm-contract', value: '0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48' }, addressValidationRegex: EVM_ADDRESS },\n { id: 'ethereum/eth', key: 'eth', chainId: 'ethereum', symbol: 'ETH', name: 'Ether', decimals: 18, kind: 'native', locator: { kind: 'native', value: 'ETH' }, addressValidationRegex: EVM_ADDRESS },\n { id: 'ethereum/wbtc', key: 'wbtc', chainId: 'ethereum', symbol: 'WBTC', name: 'Wrapped Bitcoin', decimals: 8, kind: 'token', locator: { kind: 'evm-contract', value: '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599' }, addressValidationRegex: EVM_ADDRESS },\n { id: 'ethereum/usdt', key: 'usdt', chainId: 'ethereum', symbol: 'USDT', name: 'Tether USD', decimals: 6, kind: 'token', locator: { kind: 'evm-contract', value: '0xdAC17F958D2ee523a2206206994597C13D831ec7' }, addressValidationRegex: EVM_ADDRESS },\n { id: 'ethereum/aleo', key: 'aleo', chainId: 'ethereum', symbol: 'ALEO', name: 'Hyperlane ALEO', decimals: 6, kind: 'token', addressValidationRegex: EVM_ADDRESS },\n { id: 'ethereum/usad', key: 'usad', chainId: 'ethereum', symbol: 'USAD', name: 'USAD route collateral', decimals: 6, kind: 'token', addressValidationRegex: EVM_ADDRESS },\n { id: 'solana/sol', key: 'sol', chainId: 'solana', symbol: 'SOL', name: 'Solana', decimals: 9, kind: 'native', locator: { kind: 'native', value: 'SOL' }, addressValidationRegex: SOLANA_ADDRESS },\n { id: 'solana/aleo', key: 'aleo', chainId: 'solana', symbol: 'ALEO', name: 'Hyperlane ALEO', decimals: 6, kind: 'token', addressValidationRegex: SOLANA_ADDRESS },\n { id: 'base/aleo', key: 'aleo', chainId: 'base', symbol: 'ALEO', name: 'Hyperlane ALEO', decimals: 6, kind: 'token', addressValidationRegex: EVM_ADDRESS },\n { id: 'hyperevm/aleo', key: 'aleo', chainId: 'hyperevm', symbol: 'ALEO', name: 'Hyperlane ALEO', decimals: 6, kind: 'token', addressValidationRegex: EVM_ADDRESS },\n { id: 'aleo-testnet/usdcx', key: 'usdcx', chainId: 'aleo-testnet', symbol: 'USDCx', name: 'Testnet USDCx', decimals: 6, kind: 'token', locator: { kind: 'aleo-program', value: 'test_usdcx_stablecoin.aleo' }, addressValidationRegex: ALEO_ADDRESS, privacy: { kind: 'arc22', program: 'test_usdcx_stablecoin.aleo' } },\n { id: 'sepolia/usdc', key: 'usdc', chainId: 'sepolia', symbol: 'USDC', name: 'Testnet USD Coin', decimals: 6, kind: 'token', locator: { kind: 'evm-contract', value: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238' }, addressValidationRegex: EVM_ADDRESS },\n]\n\nconst XRESERVE_SOURCE = 'https://developers.circle.com/xreserve/references/supported-blockchains-and-domains'\nconst HYPERLANE_REGISTRY_COMMIT = '2621c16f2db1ccb46643265c110dac5ca2c7c51a'\nconst HYPERLANE_SOURCE = `https://github.com/hyperlane-xyz/hyperlane-registry/tree/${HYPERLANE_REGISTRY_COMMIT}/deployments/warp_routes`\nconst ALEO_ETH_PROGRAM_SOURCE = 'https://explorer.provable.com/program/hyp_warp_token_eth_v2.aleo'\nconst ALEO_ETH_APP_METADATA_SOURCE = 'https://api.explorer.provable.com/v2/mainnet/program/hyp_warp_token_eth_v2.aleo/mapping/app_metadata/true'\nconst ALEO_ETH_REMOTE_ROUTER_SOURCE = 'https://api.explorer.provable.com/v2/mainnet/program/hyp_warp_token_eth_v2.aleo/mapping/remote_routers/1u32'\nconst ALEO_ETH_SAMPLE_TRANSFER_SOURCE = 'https://explorer.provable.com/transaction/at1vu0yckkms887zkl3qz7plnncd56jtf5zeal4uj2808upsjkusy8q7yp9v8'\nconst ALEO_WBTC_PROGRAM_SOURCE = 'https://explorer.provable.com/program/hyp_warp_token_wbtc_v2.aleo'\nconst ALEO_WBTC_APP_METADATA_SOURCE = 'https://api.explorer.provable.com/v2/mainnet/program/hyp_warp_token_wbtc_v2.aleo/mapping/app_metadata/true'\nconst ALEO_WBTC_REMOTE_ROUTER_SOURCE = 'https://api.explorer.provable.com/v2/mainnet/program/hyp_warp_token_wbtc_v2.aleo/mapping/remote_routers/1u32'\nconst ALEO_USDT_PROGRAM_SOURCE = 'https://explorer.provable.com/program/hyp_warp_token_usdt_v2.aleo'\nconst ALEO_USDT_APP_METADATA_SOURCE = 'https://api.explorer.provable.com/v2/mainnet/program/hyp_warp_token_usdt_v2.aleo/mapping/app_metadata/true'\nconst ALEO_USDT_ETHEREUM_REMOTE_ROUTER_SOURCE = 'https://api.explorer.provable.com/v2/mainnet/program/hyp_warp_token_usdt_v2.aleo/mapping/remote_routers/1u32'\nconst ALEO_USDT_SAMPLE_TRANSFER_SOURCE = 'https://explorer.provable.com/transaction/at19caeeee8v3xc4kfwen4tx89f0tnggrpjp0anrhq2ca3y82xr9q8qyz8a9r'\nconst ALEO_USDT_HYPERLANE_CONFIG_SOURCE = 'https://github.com/hyperlane-xyz/hyperlane-registry/blob/418056e21734d26a7d14692e0ec5e902cc9e86bf/deployments/warp_routes/USDT/aleo-config.yaml'\nconst ALEO_SOL_PROGRAM_SOURCE = 'https://explorer.provable.com/program/hyp_warp_token_sol_v2.aleo'\nconst ALEO_SOL_APP_METADATA_SOURCE = 'https://api.explorer.provable.com/v2/mainnet/program/hyp_warp_token_sol_v2.aleo/mapping/app_metadata/true'\nconst ALEO_SOL_REMOTE_ROUTER_SOURCE = 'https://api.explorer.provable.com/v2/mainnet/program/hyp_warp_token_sol_v2.aleo/mapping/remote_routers/1399811149u32'\nconst ALEO_SOL_HYPERLANE_CONFIG_SOURCE = 'https://github.com/hyperlane-xyz/hyperlane-registry/blob/418056e21734d26a7d14692e0ec5e902cc9e86bf/deployments/warp_routes/SOL/aleo-config.yaml'\nconst ALEO_MAILBOX_PROGRAM_SOURCE = 'https://explorer.provable.com/program/hyp_mailbox.aleo'\nconst ALEO_MAILBOX_METADATA_SOURCE = 'https://api.explorer.provable.com/v2/mainnet/program/hyp_mailbox.aleo/mapping/mailbox/true'\n\nconst ETHEREUM_HYPERLANE_COMMON = {\n sourceChainId: 1,\n destinationDomain: 1634493807,\n mailboxAddress: '0xc005dc82818d67AF737725bD4bf75435d065D239',\n interchainGasPaymaster: '0x9e6B1022bE9BBF5aFd152483DAD9b88911bC8611',\n interchainSecurityModule: '0x0000000000000000000000000000000000000000',\n registryCommit: HYPERLANE_REGISTRY_COMMIT,\n} as const\n\nconst ETH_HYPERLANE_METADATA = {\n ...ETHEREUM_HYPERLANE_COMMON,\n routerAddress: '0x38D447694f5c1f773ae3132cf93bF30B7Ec1Fa5A',\n routerType: 'native',\n destinationRouter: 'hyp_warp_token_eth_v2.aleo/aleo1t7f29tq9qng2lfvrkpcuvu59jn24hrmzqdyqfn6p0u5p80npfvqqecmkj8',\n} as const\n\nconst WBTC_HYPERLANE_METADATA = {\n ...ETHEREUM_HYPERLANE_COMMON,\n routerAddress: '0x20CDC85778b732073F7EecEF3DF25c0d310f8772',\n routerType: 'collateral',\n tokenAddress: '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599',\n destinationRouter: 'hyp_warp_token_wbtc_v2.aleo/aleo1240fsvz2dhmj0cdtt8mc0yc8um9fmu236rqcl2qnlj9703hd2vpsdwyrtf',\n} as const\n\nconst USDT_HYPERLANE_METADATA = {\n ...ETHEREUM_HYPERLANE_COMMON,\n routerAddress: '0x3C2064D78e4578E8F936E3db42aEF044E33FBF31',\n routerType: 'collateral',\n tokenAddress: '0xdAC17F958D2ee523a2206206994597C13D831ec7',\n destinationRouter: 'hyp_warp_token_usdt_v2.aleo/aleo18yynfz0lrfx0tund540vy2z7gju7ekgqsueg5jgu28mpm2z42ufq7qua8y',\n requiresApprovalReset: true,\n} as const\n\n// Intentionally non-live values used only to expose the Aleo transfer_remote ABI.\n// execute refuses these routes while the flag is true.\nconst ALEO_PLACEHOLDER_ADDRESS = 'aleo1kypwp5m7qtk9mwazgcpg0tq8aal23mnrvwfvug65qgcg9xvsrqgspyjm6n'\nconst ALEO_PLACEHOLDER_BYTES32 = `[${Array.from({ length: 32 }, () => '0u8').join(', ')}]`\n\nconst ALEO_MAILBOX_METADATA = {\n aleoMailboxStateVerified: true,\n aleoHookManagerProgram: 'hyp_hook_manager.aleo',\n aleoHookManagerProgramSource: 'https://explorer.provable.com/program/hyp_hook_manager.aleo',\n aleoMailboxProgram: 'hyp_mailbox.aleo',\n aleoMailboxProgramEdition: 0,\n aleoMailboxProgramSource: ALEO_MAILBOX_PROGRAM_SOURCE,\n aleoMailboxMetadataSource: ALEO_MAILBOX_METADATA_SOURCE,\n aleoMailboxMetadataReviewedAt: '2026-08-17',\n aleoMailboxLocalDomain: 1634493807,\n aleoMailboxObservedNonce: 170,\n aleoMailboxObservedProcessCount: 291,\n aleoMailboxDefaultIsm: 'aleo1yvf5kcsdgnescqq2lar83mms79yh3ugvc3y0mdnlgvx4lyh5zugqr9hptk',\n aleoMailboxDefaultHook: 'aleo194tz0jmyq8rd9htvnqppqw4jqerk2p2zd8plzn3sxl06wcgsm5pq9fka74',\n aleoMailboxRequiredHook: 'aleo1yxevh9qgxehej46j7vueplwjcpfdfml2dje3ey4ukzknx7wzasgqnxgq82',\n aleoMailboxDispatchProxy: 'aleo1sge9kmjzs3d8fqrscy4hwn7vf9vw4jcxe877lv0m2w8hay78lsxsqg975s',\n aleoMailboxOwner: 'aleo1ypf8xgvz560ukw25hufj3d77gx69pdcy70nssdfdxd97j80d7cqs98d7x8',\n} as const\n\nfunction aleoHyperlanePlaceholders(program: string, destinationDomain: number) {\n return {\n aleoRouterProgram: program,\n aleoDestinationDomain: destinationDomain,\n aleoPlaceholderConfiguration: true,\n aleoTokenType: '0',\n aleoTokenOwner: ALEO_PLACEHOLDER_ADDRESS,\n aleoIsm: ALEO_PLACEHOLDER_ADDRESS,\n aleoHook: ALEO_PLACEHOLDER_ADDRESS,\n aleoTokenId: '0field',\n aleoRemoteRouterRecipient: ALEO_PLACEHOLDER_BYTES32,\n aleoRemoteRouterGas: '0',\n aleoRecipient: '[0u128, 0u128]',\n aleoAllowanceSpender0: ALEO_PLACEHOLDER_ADDRESS,\n aleoAllowanceAmount0: '0',\n aleoAllowanceSpender1: ALEO_PLACEHOLDER_ADDRESS,\n aleoAllowanceAmount1: '0',\n aleoAllowanceSpender2: ALEO_PLACEHOLDER_ADDRESS,\n aleoAllowanceAmount2: '0',\n aleoAllowanceSpender3: ALEO_PLACEHOLDER_ADDRESS,\n aleoAllowanceAmount3: '0',\n ...ALEO_MAILBOX_METADATA,\n } as const\n}\n\nconst ALEO_WBTC_APP_METADATA = {\n aleoAppMetadataVerified: true,\n aleoProgramSource: ALEO_WBTC_PROGRAM_SOURCE,\n aleoAppMetadataSource: ALEO_WBTC_APP_METADATA_SOURCE,\n aleoAppMetadataReviewedAt: '2026-08-17',\n aleoProgramEdition: 0,\n aleoTokenType: '1',\n aleoTokenOwner: 'aleo14jauje2a5sncm9u5t3mt6qqv3eq2hatkddskccs0dvsy35a0x58q0d6f95',\n aleoIsm: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoHook: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoTokenId: '1505227928464760254508513036497943623956572091841806589002910775534260084309field',\n aleoLocalDecimals: 8,\n aleoRemoteDecimals: 8,\n} as const\n\nconst ALEO_ETH_APP_METADATA = {\n aleoAppMetadataVerified: true,\n aleoProgramSource: ALEO_ETH_PROGRAM_SOURCE,\n aleoAppMetadataSource: ALEO_ETH_APP_METADATA_SOURCE,\n aleoAppMetadataReviewedAt: '2026-08-17',\n aleoProgramEdition: 0,\n aleoTokenType: '1',\n aleoTokenOwner: 'aleo1wq6f6qdqya44avznygz5hae40u3mjg64w0r93a4qfu4utpf8cg9q566f4r',\n aleoIsm: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoHook: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoTokenId: '133188123661477349522757068766864658505569365361420630212878794317749195359field',\n aleoLocalDecimals: 18,\n aleoRemoteDecimals: 18,\n} as const\n\nconst ALEO_USDT_APP_METADATA = {\n aleoAppMetadataVerified: true,\n aleoProgramSource: ALEO_USDT_PROGRAM_SOURCE,\n aleoAppMetadataSource: ALEO_USDT_APP_METADATA_SOURCE,\n aleoAppMetadataReviewedAt: '2026-08-17',\n aleoProgramEdition: 1,\n aleoTokenType: '1',\n aleoTokenOwner: 'aleo1l3gwacmjruxryy9c7c4fn0acyzprf29hucrvthw7f63lpyhd5y9srydq8z',\n aleoIsm: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoHook: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoTokenId: '8295938150000417034830036849466229528602563851235385582732969109393809606969field',\n aleoLocalDecimals: 6,\n aleoRemoteDecimals: 18,\n aleoScale: '1000000000000',\n aleoHyperlaneConfigSource: ALEO_USDT_HYPERLANE_CONFIG_SOURCE,\n} as const\n\nconst ALEO_SOL_APP_METADATA = {\n aleoAppMetadataVerified: true,\n aleoProgramSource: ALEO_SOL_PROGRAM_SOURCE,\n aleoAppMetadataSource: ALEO_SOL_APP_METADATA_SOURCE,\n aleoAppMetadataReviewedAt: '2026-08-17',\n aleoProgramEdition: 0,\n aleoTokenType: '1',\n aleoTokenOwner: 'aleo1wr8rfr4ggedjxtg5e23s38zqkgy2j05uc9l8t4akjp5zcw3levpswkwk45',\n aleoIsm: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoHook: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoTokenId: '6148061383892805373029428966764338809222769879628268522058032128225601478383field',\n aleoLocalDecimals: 9,\n aleoRemoteDecimals: 9,\n aleoHyperlaneConfigSource: ALEO_SOL_HYPERLANE_CONFIG_SOURCE,\n} as const\n\nconst ALEO_ETH_REMOTE_ROUTER = {\n aleoRemoteRouterVerified: true,\n aleoRemoteRouterSource: ALEO_ETH_REMOTE_ROUTER_SOURCE,\n aleoRemoteRouterReviewedAt: '2026-08-17',\n aleoSampleTransferSource: ALEO_ETH_SAMPLE_TRANSFER_SOURCE,\n aleoDestinationDomain: 1,\n aleoRemoteRouterEvmAddress: '0x38D447694f5c1f773ae3132cf93bF30B7Ec1Fa5A',\n aleoRemoteRouterRecipient: '[0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 56u8, 212u8, 71u8, 105u8, 79u8, 92u8, 31u8, 119u8, 58u8, 227u8, 19u8, 44u8, 249u8, 59u8, 243u8, 11u8, 126u8, 193u8, 250u8, 90u8]',\n aleoRemoteRouterGas: '44000',\n aleoAllowanceSpendersVerified: true,\n aleoUnusedAllowancesVerified: true,\n aleoAllowanceSpender0: 'aleo194tz0jmyq8rd9htvnqppqw4jqerk2p2zd8plzn3sxl06wcgsm5pq9fka74',\n aleoAllowanceSpender1: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceSpender2: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceSpender3: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceAmount1: '0',\n aleoAllowanceAmount2: '0',\n aleoAllowanceAmount3: '0',\n} as const\n\nconst ALEO_WBTC_REMOTE_ROUTER = {\n aleoRemoteRouterVerified: true,\n aleoRemoteRouterSource: ALEO_WBTC_REMOTE_ROUTER_SOURCE,\n aleoRemoteRouterReviewedAt: '2026-08-17',\n aleoDestinationDomain: 1,\n aleoRemoteRouterEvmAddress: '0x20CDC85778b732073F7EecEF3DF25c0d310f8772',\n aleoRemoteRouterRecipient: '[0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 32u8, 205u8, 200u8, 87u8, 120u8, 183u8, 50u8, 7u8, 63u8, 126u8, 236u8, 239u8, 61u8, 242u8, 92u8, 13u8, 49u8, 15u8, 135u8, 114u8]',\n aleoRemoteRouterGas: '68000',\n aleoAllowanceSpendersVerified: true,\n aleoUnusedAllowancesVerified: true,\n aleoAllowanceSpender0: 'aleo194tz0jmyq8rd9htvnqppqw4jqerk2p2zd8plzn3sxl06wcgsm5pq9fka74',\n aleoAllowanceSpender1: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceSpender2: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceSpender3: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceAmount1: '0',\n aleoAllowanceAmount2: '0',\n aleoAllowanceAmount3: '0',\n} as const\n\nconst ALEO_USDT_ETHEREUM_REMOTE_ROUTER = {\n aleoRemoteRouterVerified: true,\n aleoRemoteRouterSource: ALEO_USDT_ETHEREUM_REMOTE_ROUTER_SOURCE,\n aleoRemoteRouterReviewedAt: '2026-08-17',\n aleoSampleTransferSource: ALEO_USDT_SAMPLE_TRANSFER_SOURCE,\n aleoSampleTransferDestinationDomain: 56,\n aleoDestinationDomain: 1,\n aleoRemoteRouterEvmAddress: '0x3C2064D78e4578E8F936E3db42aEF044E33FBF31',\n aleoRemoteRouterRecipient: '[0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 0u8, 60u8, 32u8, 100u8, 215u8, 142u8, 69u8, 120u8, 232u8, 249u8, 54u8, 227u8, 219u8, 66u8, 174u8, 240u8, 68u8, 227u8, 63u8, 191u8, 49u8]',\n aleoRemoteRouterGas: '68000',\n aleoAllowanceSpendersVerified: true,\n aleoUnusedAllowancesVerified: true,\n aleoAllowanceSpender0: 'aleo194tz0jmyq8rd9htvnqppqw4jqerk2p2zd8plzn3sxl06wcgsm5pq9fka74',\n aleoAllowanceSpender1: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceSpender2: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceSpender3: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceAmount1: '0',\n aleoAllowanceAmount2: '0',\n aleoAllowanceAmount3: '0',\n} as const\n\nconst ALEO_SOL_REMOTE_ROUTER = {\n aleoRemoteRouterVerified: true,\n aleoRemoteRouterSource: ALEO_SOL_REMOTE_ROUTER_SOURCE,\n aleoRemoteRouterReviewedAt: '2026-08-17',\n aleoSampleTransitionId: 'au15fg39h53h55tkj0nexrme3k6pvgxngxapcyajdhf06jcg3cyeugq5kd7hg',\n aleoDestinationDomain: 1399811149,\n aleoRemoteRouterSolanaAddress: '8YGT2pZwyZe94qBpGzWfY2TMEVcwaQ1bXAE7YAgpUaM7',\n aleoRemoteRouterRecipient: '[112u8, 4u8, 72u8, 22u8, 219u8, 143u8, 68u8, 202u8, 21u8, 197u8, 236u8, 182u8, 198u8, 142u8, 52u8, 96u8, 142u8, 38u8, 51u8, 113u8, 116u8, 143u8, 96u8, 123u8, 104u8, 126u8, 97u8, 73u8, 7u8, 6u8, 211u8, 122u8]',\n aleoRemoteRouterGas: '300000',\n aleoAllowanceSpendersVerified: true,\n aleoUnusedAllowancesVerified: true,\n aleoAllowanceSpender0: 'aleo194tz0jmyq8rd9htvnqppqw4jqerk2p2zd8plzn3sxl06wcgsm5pq9fka74',\n aleoAllowanceSpender1: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceSpender2: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceSpender3: 'aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc',\n aleoAllowanceAmount1: '0',\n aleoAllowanceAmount2: '0',\n aleoAllowanceAmount3: '0',\n} as const\n\nconst ALEO_WITHDRAWAL_ACTIVATION = {\n aleoPlaceholderConfiguration: false,\n aleoWithdrawalReviewedAt: '2026-08-26',\n} as const\n\n// Reviewed Sealevel deployment for the Solana-origin SOL deposit route\n// (`hyperlane:solana/sol->aleo/sol`). Cross-verified against two independent\n// sources per account, per packages/bridge/src/solana/SEALEVEL_NOTES.md §2:\n// the hyperlane-registry snapshot at commit 418056e21734d26a7d14692e0ec5e902cc9e86bf\n// (mailbox and terminal IGP account, from chains/solanamainnet/addresses.yaml;\n// warp program id, from deployments/warp_routes/SOL/aleo-config.yaml,\n// ALEO_SOL_HYPERLANE_CONFIG_SOURCE above) confirms the accounts it carries,\n// and the real mainnet deposit captured in\n// test/fixtures/sealevel-transfer-remote.json (plus\n// test/fixtures/sealevel-igp-account.json for the IGP account) confirms\n// every account, including the program-derived addresses the registry does\n// not itself carry. No discrepancy was found between the two sources for\n// any account.\nconst SOLANA_SOL_DEPOSIT_METADATA = {\n warpProgramAddress: '8YGT2pZwyZe94qBpGzWfY2TMEVcwaQ1bXAE7YAgpUaM7',\n tokenPda: 'JDkpV5CsSbhyGhHhirC5DjGPTcuKWUVHtBZ5MFsgu3ZW',\n nativeCollateralPda: '8HY3hxmnrWwqEmcdwkSnfN9wEQFUkyiwZvU1vMbnXgbC',\n dispatchAuthorityPda: 'ATDttjggAZKyS19kcV6Rn56oMi49gDprZGckRou9vkkY',\n mailboxProgramAddress: 'E588QtVUvresuXq2KoNEwAmoifCzYGpRBdHByN9KQMbi',\n mailboxOutboxPda: 'BvZpTuYLAR77mPhH4GtvwEWUTs53GQqkgBNuXpCePVNk',\n igpProgramAddress: 'BhNcatUDC2D5JTyeaqrdSukiVFsEHK7e3hVmKMztwefv',\n igpProgramDataPda: '8Cv4PHJ6Cf3xY7dse7wYeZKtuQv9SAN6ujt5w22a2uho',\n igpAccount: 'JAvHW21tYXE9dtdG83DReqU2b4LUexFuCbtJT5tF8X6M',\n igpOverheadAccount: 'AkeHBbE5JkwVppujCQQ6WuxsVsJtruBAjUo6fDCFp6fF',\n splNoopProgramAddress: 'noopb9bkMVfRPU8AsbpTUg8AQkHtKwMYZiFUjNRtMmV',\n destinationDomain: 1634493807,\n destinationGasAmount: '464000',\n registryCommit: '418056e21734d26a7d14692e0ec5e902cc9e86bf',\n solanaReviewedAt: '2026-08-31',\n solanaConfigSource: ALEO_SOL_HYPERLANE_CONFIG_SOURCE,\n} as const\n\nfunction route(\n id: string,\n protocol: 'xreserve' | 'hyperlane',\n environment: BridgeEnvironment,\n sourceAssetId: string,\n destinationAssetId: string,\n availability: 'active' | 'metadata-required',\n deploymentId: string,\n metadata?: Readonly<Record<string, string | number | boolean>>,\n): ProtocolBridgeRoute {\n return {\n id,\n protocol,\n environment,\n sourceAssetId,\n destinationAssetId,\n availability,\n deploymentId,\n source: protocol === 'xreserve' ? XRESERVE_SOURCE : HYPERLANE_SOURCE,\n ...(metadata == null ? {} : { metadata }),\n }\n}\n\nfunction pair(\n protocol: 'xreserve' | 'hyperlane',\n environment: BridgeEnvironment,\n left: string,\n right: string,\n availability: 'active' | 'metadata-required',\n deploymentId: string,\n metadata?: Readonly<Record<string, string | number | boolean>>,\n reverseAvailability: 'active' | 'metadata-required' = availability,\n): ProtocolBridgeRoute[] {\n return [\n route(`${protocol}:${left}->${right}`, protocol, environment, left, right, availability, deploymentId, metadata),\n route(`${protocol}:${right}->${left}`, protocol, environment, right, left, reverseAvailability, deploymentId, metadata),\n ]\n}\n\nconst routes: ProtocolBridgeRoute[] = [\n ...pair('xreserve', 'mainnet', 'ethereum/usdc', 'aleo/usdcx', 'active', 'xreserve-usdcx-aleo', {\n xReserveContract: '0x8888888199b2Df864bf678259607d6D5EBb4e3Ce',\n sourceChainId: 1,\n sourceDomain: 0,\n ethereumDestinationDomain: 0,\n arcDestinationDomain: 26,\n remoteDomain: 10002,\n remoteToken: 'usdcx_stablecoin.aleo',\n remoteTokenBytes32: '0x11ea7dab1d29d5f61500582c63e98c42e1165f9ba050ea9d0c6af9f871987711',\n minimumAmountAtomic: '2000000',\n withdrawalFeeAtomic: '2000000',\n maxFeeAtomic: '100000',\n bridgeProgram: 'usdcx_bridge_v2.aleo',\n wrapperProgram: 'shielded_usdcx_wrapper.aleo',\n attestationBaseUrl: 'https://xreserve-api.circle.com/v1/attestations',\n }, 'active'),\n ...pair('xreserve', 'testnet', 'sepolia/usdc', 'aleo-testnet/usdcx', 'active', 'xreserve-usdcx-aleo-testnet', {\n xReserveContract: '0x008888878f94C0d87defdf0B07f46B93C1934442',\n sourceChainId: 11155111,\n sourceDomain: 0,\n ethereumDestinationDomain: 0,\n arcDestinationDomain: 26,\n remoteDomain: 10002,\n remoteToken: 'test_usdcx_stablecoin.aleo',\n remoteTokenBytes32: '0xb143ed52c774cd1d4a519d0e796f15916be5a9e1d45edcd9852dd23f68f53401',\n minimumAmountAtomic: '2000000',\n withdrawalFeeAtomic: '2000000',\n maxFeeAtomic: '100000',\n bridgeProgram: 'test_usdcx_bridge_v2.aleo',\n wrapperProgram: 'shielded_usdcx_wrapper.aleo',\n attestationBaseUrl: 'https://xreserve-api-testnet.circle.com/v1/attestations',\n }, 'active'),\n route('hyperlane:ethereum/eth->aleo/eth', 'hyperlane', 'mainnet', 'ethereum/eth', 'aleo/eth', 'active', 'ETH/aleo', { ...ETH_HYPERLANE_METADATA, ...ALEO_MAILBOX_METADATA }),\n route('hyperlane:aleo/eth->ethereum/eth', 'hyperlane', 'mainnet', 'aleo/eth', 'ethereum/eth', 'active', 'ETH/aleo', { ...ETH_HYPERLANE_METADATA, ...aleoHyperlanePlaceholders('hyp_warp_token_eth_v2.aleo', 1), ...ALEO_ETH_APP_METADATA, ...ALEO_ETH_REMOTE_ROUTER, ...ALEO_WITHDRAWAL_ACTIVATION }),\n route('hyperlane:ethereum/wbtc->aleo/wbtc', 'hyperlane', 'mainnet', 'ethereum/wbtc', 'aleo/wbtc', 'active', 'WBTC/aleo', { ...WBTC_HYPERLANE_METADATA, ...ALEO_MAILBOX_METADATA }),\n route('hyperlane:aleo/wbtc->ethereum/wbtc', 'hyperlane', 'mainnet', 'aleo/wbtc', 'ethereum/wbtc', 'active', 'WBTC/aleo', { ...WBTC_HYPERLANE_METADATA, ...aleoHyperlanePlaceholders('hyp_warp_token_wbtc_v2.aleo', 1), ...ALEO_WBTC_APP_METADATA, ...ALEO_WBTC_REMOTE_ROUTER, ...ALEO_WITHDRAWAL_ACTIVATION }),\n route('hyperlane:ethereum/usdt->aleo/usdt', 'hyperlane', 'mainnet', 'ethereum/usdt', 'aleo/usdt', 'active', 'USDT/aleo', { ...USDT_HYPERLANE_METADATA, ...ALEO_MAILBOX_METADATA }),\n route('hyperlane:aleo/usdt->ethereum/usdt', 'hyperlane', 'mainnet', 'aleo/usdt', 'ethereum/usdt', 'active', 'USDT/aleo', { ...USDT_HYPERLANE_METADATA, ...aleoHyperlanePlaceholders('hyp_warp_token_usdt_v2.aleo', 1), ...ALEO_USDT_APP_METADATA, ...ALEO_USDT_ETHEREUM_REMOTE_ROUTER, ...ALEO_WITHDRAWAL_ACTIVATION }),\n route('hyperlane:solana/sol->aleo/sol', 'hyperlane', 'mainnet', 'solana/sol', 'aleo/sol', 'active', 'SOL/aleo', { ...SOLANA_SOL_DEPOSIT_METADATA, ...ALEO_MAILBOX_METADATA }),\n route('hyperlane:aleo/sol->solana/sol', 'hyperlane', 'mainnet', 'aleo/sol', 'solana/sol', 'active', 'SOL/aleo', { ...aleoHyperlanePlaceholders('hyp_warp_token_sol_v2.aleo', 1399811149), ...ALEO_SOL_APP_METADATA, ...ALEO_SOL_REMOTE_ROUTER, ...ALEO_WITHDRAWAL_ACTIVATION }),\n ...pair('hyperlane', 'mainnet', 'aleo/aleo', 'ethereum/aleo', 'metadata-required', 'ALEO/aleo', ALEO_MAILBOX_METADATA),\n ...pair('hyperlane', 'mainnet', 'aleo/aleo', 'solana/aleo', 'metadata-required', 'ALEO/aleo', ALEO_MAILBOX_METADATA),\n ...pair('hyperlane', 'mainnet', 'aleo/aleo', 'base/aleo', 'metadata-required', 'ALEO/aleo', ALEO_MAILBOX_METADATA),\n ...pair('hyperlane', 'mainnet', 'aleo/aleo', 'hyperevm/aleo', 'metadata-required', 'ALEO/aleo', ALEO_MAILBOX_METADATA),\n route('hyperlane:ethereum/usad->aleo/usad', 'hyperlane', 'mainnet', 'ethereum/usad', 'aleo/usad', 'metadata-required', 'USAD/aleo', ALEO_MAILBOX_METADATA),\n route('hyperlane:aleo/usad->ethereum/usad', 'hyperlane', 'mainnet', 'aleo/usad', 'ethereum/usad', 'metadata-required', 'USAD/aleo', aleoHyperlanePlaceholders('hyp_warp_token_usad_v2.aleo', 1)),\n]\n\n/**\n * Supplies the initial reviewed protocol-route snapshot.\n *\n * xReserve contract identifiers are populated from Circle's published\n * mainnet and testnet tables. Hyperlane routes intentionally remain\n * `metadata-required` until their router, domain, ISM, and token identifiers\n * are pinned from one reviewed registry commit. Reading this snapshot does not\n * contact any chain or bridge provider.\n *\n * @example\n * const bridge = createBridgeClient({ registry: DEFAULT_BRIDGE_REGISTRY })\n */\nexport const DEFAULT_BRIDGE_REGISTRY: BridgeRegistry = Object.freeze({\n version: '2026-08-31.solana-deposits.1',\n chains: Object.freeze(chains),\n assets: Object.freeze(assets),\n routes: Object.freeze(routes),\n sources: Object.freeze([XRESERVE_SOURCE, HYPERLANE_SOURCE]),\n getAssets(this: BridgeRegistry, params = {}) {\n const chains = new Map(this.chains.map((chain) => [chain.id, chain]))\n const chainId = params.chainId?.toLowerCase()\n const symbol = params.symbol?.toLowerCase()\n return this.assets.filter((asset) => {\n const chain = chains.get(asset.chainId)\n return (\n (params.environment == null || chain?.environment === params.environment) &&\n (chainId == null || asset.chainId.toLowerCase() === chainId) &&\n (symbol == null || asset.symbol.toLowerCase() === symbol)\n )\n })\n },\n getRoutes(this: BridgeRegistry, params = {}) {\n const assets = new Map(this.assets.map((asset) => [asset.id, asset]))\n const sourceChainId = params.sourceChainId?.toLowerCase()\n const destinationChainId = params.destinationChainId?.toLowerCase()\n const symbol = params.symbol?.toLowerCase()\n return this.routes.filter((route) => {\n const source = assets.get(route.sourceAssetId)!\n const destination = assets.get(route.destinationAssetId)!\n return (\n (params.includeUnavailable === true || route.availability !== 'disabled') &&\n (params.environment == null || route.environment === params.environment) &&\n (params.protocol == null || route.protocol === params.protocol) &&\n (sourceChainId == null || source.chainId.toLowerCase() === sourceChainId) &&\n (destinationChainId == null || destination.chainId.toLowerCase() === destinationChainId) &&\n (symbol == null || source.symbol.toLowerCase() === symbol || destination.symbol.toLowerCase() === symbol)\n )\n })\n },\n})\n","import { BridgeError } from '../errors/bridgeErrors.js'\nimport type { BridgeRegistry } from '../types/protocol.js'\nimport type { SolanaHyperlaneRouteMetadata } from '../types/solana.js'\n\n// Required `SolanaHyperlaneRouteMetadata` fields an active Solana-source\n// Hyperlane route must carry. `igpOverheadAccount` is intentionally excluded:\n// it is optional on the type, present only when the reviewed deployment\n// wraps its IGP in an `OverheadIgp` layer (see the type's docblock).\nconst REQUIRED_SOLANA_HYPERLANE_METADATA_FIELDS: readonly Exclude<\n keyof SolanaHyperlaneRouteMetadata,\n 'igpOverheadAccount'\n>[] = [\n 'warpProgramAddress',\n 'tokenPda',\n 'nativeCollateralPda',\n 'dispatchAuthorityPda',\n 'mailboxProgramAddress',\n 'mailboxOutboxPda',\n 'igpProgramAddress',\n 'igpProgramDataPda',\n 'igpAccount',\n 'splNoopProgramAddress',\n 'destinationDomain',\n 'destinationGasAmount',\n 'registryCommit',\n 'solanaReviewedAt',\n 'solanaConfigSource',\n]\n\n/**\n * Reports whether route metadata carries every required\n * `SolanaHyperlaneRouteMetadata` field with the expected primitive type.\n *\n * Checks only the supplied field names and primitive types; format-level\n * validation (address charset, digit strings, and commit hash format) is the\n * job of `solanaRouteMetadata` in the Solana Hyperlane protocol module before\n * live reads or submission. It does not contact Solana.\n */\nfunction hasCompleteSolanaHyperlaneMetadata(\n metadata: Readonly<Record<string, string | number | boolean>> | undefined,\n): boolean {\n if (!metadata) return false\n return REQUIRED_SOLANA_HYPERLANE_METADATA_FIELDS.every((field) => {\n const value = metadata[field]\n return field === 'destinationDomain' ? typeof value === 'number' : typeof value === 'string' && value.length > 0\n })\n}\n\n/**\n * Validates the referential integrity of a protocol bridge registry.\n *\n * Duplicate identifiers and dangling asset or chain references throw before a\n * client can describe a misleading transfer. An active Hyperlane route sourced\n * from a Solana-family chain additionally must carry a complete\n * `SolanaHyperlaneRouteMetadata` object, so a route cannot be made active ahead\n * of its metadata being reviewed and filled in. Validation does not contact a\n * chain or bridge provider.\n *\n * @param registry Registry supplied to `createBridgeClient`.\n * @returns The validated registry unchanged.\n * @throws BridgeError When identifiers are duplicated, references are\n * missing, or an active Solana-source Hyperlane route is missing required\n * Sealevel deployment metadata.\n *\n * @example\n * const registry = validateBridgeRegistry(DEFAULT_BRIDGE_REGISTRY)\n */\nexport function validateBridgeRegistry(registry: BridgeRegistry): BridgeRegistry {\n if (!registry.version.trim()) throw new BridgeError('Bridge registry version must not be empty')\n\n // Establish chain identity first because every asset and route ultimately\n // inherits its environment and transaction family from these entries.\n const chainIds = new Set<string>()\n for (const chain of registry.chains) {\n if (chainIds.has(chain.id)) throw new BridgeError(`Duplicate bridge chain id: ${chain.id}`)\n chainIds.add(chain.id)\n }\n\n // Asset ids are globally unique; caller-facing keys are unique only within a\n // chain so the same symbol can represent different contracts or programs.\n const assetIds = new Set<string>()\n const assetKeys = new Set<string>()\n for (const asset of registry.assets) {\n if (assetIds.has(asset.id)) throw new BridgeError(`Duplicate bridge asset id: ${asset.id}`)\n if (!chainIds.has(asset.chainId)) {\n throw new BridgeError(`Bridge asset ${asset.id} references unknown chain ${asset.chainId}`)\n }\n if (!asset.key.trim()) throw new BridgeError(`Bridge asset ${asset.id} has an empty key`)\n const scopedKey = `${asset.chainId}/${asset.key}`\n if (assetKeys.has(scopedKey)) throw new BridgeError(`Duplicate bridge asset key: ${scopedKey}`)\n if (!Number.isInteger(asset.decimals) || asset.decimals < 0) {\n throw new BridgeError(`Bridge asset ${asset.id} has invalid decimals ${asset.decimals}`)\n }\n if (asset.addressValidationRegex) {\n try {\n new RegExp(asset.addressValidationRegex)\n } catch (cause) {\n throw new BridgeError(`Bridge asset ${asset.id} has an invalid address validation regex`, {\n cause,\n })\n }\n }\n if (asset.privacy) {\n const chain = registry.chains.find((entry) => entry.id === asset.chainId)\n if (chain?.family !== 'aleo') {\n throw new BridgeError(`Bridge asset ${asset.id} declares a privacy capability on a non-Aleo chain`)\n }\n if (!asset.privacy.program.trim()) {\n throw new BridgeError(`Bridge asset ${asset.id} has an empty privacy program`)\n }\n if (asset.privacy.kind !== 'arc20' && asset.privacy.kind !== 'arc22') {\n throw new BridgeError(`Bridge asset ${asset.id} has an unsupported privacy capability kind`)\n }\n }\n assetIds.add(asset.id)\n assetKeys.add(scopedKey)\n }\n\n // Validate directional topology after chains and assets. Active Solana-source\n // routes have an additional gate because transaction account ordering depends\n // on reviewed Sealevel deployment metadata.\n const routeIds = new Set<string>()\n for (const route of registry.routes) {\n if (routeIds.has(route.id)) throw new BridgeError(`Duplicate bridge route id: ${route.id}`)\n if (!assetIds.has(route.sourceAssetId)) {\n throw new BridgeError(`Bridge route ${route.id} references unknown source asset ${route.sourceAssetId}`)\n }\n if (!assetIds.has(route.destinationAssetId)) {\n throw new BridgeError(`Bridge route ${route.id} references unknown destination asset ${route.destinationAssetId}`)\n }\n const source = registry.assets.find((asset) => asset.id === route.sourceAssetId)!\n const destination = registry.assets.find((asset) => asset.id === route.destinationAssetId)!\n const sourceChain = registry.chains.find((chain) => chain.id === source.chainId)!\n const destinationChain = registry.chains.find((chain) => chain.id === destination.chainId)!\n if (sourceChain.environment !== route.environment || destinationChain.environment !== route.environment) {\n throw new BridgeError(`Bridge route ${route.id} crosses registry environments`)\n }\n if (\n route.protocol === 'hyperlane'\n && route.availability === 'active'\n && sourceChain.family === 'solana'\n && !hasCompleteSolanaHyperlaneMetadata(route.metadata)\n ) {\n throw new BridgeError(`Bridge route ${route.id} is active but missing required Solana Hyperlane metadata`)\n }\n routeIds.add(route.id)\n }\n\n return registry\n}\n","import { bridgeActions, type BridgeActions } from './decorators/bridge.js'\nimport type { BridgeChainClients } from '../connections/resolve.js'\nimport { DEFAULT_BRIDGE_REGISTRY } from '../registry/default.js'\nimport { validateBridgeRegistry } from '../registry/validate.js'\nimport type { BridgeEnvironment, BridgeRegistry } from '../types/protocol.js'\n\n/**\n * Configures the chains, wallets, providers, and route catalog available to a bridge client.\n *\n * @property environment Default route environment. Defaults to `mainnet`.\n * @property registry Optional replacement catalog of supported assets, routes, and reviewed provider deployments. Defaults to the package catalog.\n * @property clients Network and optional wallet access keyed by the matching chain identifier in the catalog.\n * @property fetch Optional Fetch API implementation used for provider status requests. Defaults to `globalThis.fetch`.\n * @property key Stable client key. Defaults to `bridge`.\n * @property name Display name. Defaults to `Bridge Client`.\n */\nexport type BridgeClientConfig = {\n environment?: BridgeEnvironment | undefined\n registry?: BridgeRegistry | undefined\n clients?: BridgeChainClients | undefined\n fetch?: typeof globalThis.fetch | undefined\n key?: string | undefined\n name?: string | undefined\n}\n\n/**\n * Exposes the actions for discovering, pricing, submitting, following, and recovering cross-chain transfers.\n *\n * @property key Stable client key.\n * @property name Client display name.\n * @property environment Default route environment.\n * @property registry Validated catalog of supported assets, routes, and provider deployments.\n */\nexport type BridgeClient = BridgeActions & {\n key: string\n name: string\n environment: BridgeEnvironment\n registry: BridgeRegistry\n}\n\n/**\n * Creates a client for discovering, pricing, submitting, following, and recovering cross-chain transfers.\n *\n * Construction validates the configured catalog and stores the supplied network\n * and wallet clients. It does not contact a chain or provider, request a\n * signature, submit a transaction, move funds, or manage application storage.\n *\n * @param config Networks, wallets, provider HTTP access, and optional replacement route catalog.\n * @returns Bridge actions bound to the configured chains, wallets, providers, and environment.\n * @throws BridgeError When the route catalog contains duplicate, missing, or incompatible references.\n * @example\n * const bridge = createBridgeClient({ environment: 'mainnet' })\n */\nexport function createBridgeClient(config: BridgeClientConfig = {}): BridgeClient {\n // Select all defaults before validation so every bound action observes one\n // immutable configuration decision for the lifetime of this client.\n const environment = config.environment ?? 'mainnet'\n // Fail catalog topology and reviewed-metadata errors during construction,\n // before any later action can read a chain or involve a wallet.\n const registry = validateBridgeRegistry(config.registry ?? DEFAULT_BRIDGE_REGISTRY)\n const fetch = config.fetch ?? globalThis.fetch\n const clients = config.clients ?? {}\n return {\n key: config.key ?? 'bridge',\n name: config.name ?? 'Bridge Client',\n environment,\n registry,\n ...bridgeActions({ registry, clients, fetch }),\n }\n}\n","import {\n createPublicClient,\n createWalletClient,\n custom,\n defineChain,\n getAddress,\n http,\n type Address,\n type Hash,\n type Hex,\n type LocalAccount,\n type PublicClient,\n type WalletClient,\n} from 'viem'\nimport { privateKeyToAccount } from 'viem/accounts'\nimport { BridgeError } from '../errors/bridgeErrors.js'\n\n/**\n * Sends one EIP-1193-compatible request.\n *\n * @param args JSON-RPC method and parameters.\n * @returns The provider's decoded JSON-RPC result.\n */\nexport type EvmRequest = (args: {\n method: string\n params?: readonly unknown[] | Record<string, unknown> | undefined\n}) => Promise<unknown>\n\n/**\n * Configures Fetch API behavior for an EVM HTTP transport.\n *\n * @property fetch Optional Fetch API implementation used instead of the client-level transport.\n */\nexport type EvmHttpOptions = { fetch?: typeof globalThis.fetch | undefined }\n\n/** Stores either an HTTP endpoint or custom EIP-1193 request function without contacting Ethereum. */\nexport type EvmTransport =\n | { type: 'http'; url: string; fetch?: typeof globalThis.fetch | undefined }\n | { type: 'custom'; request: EvmRequest }\n\n/** Selects whether an injected provider or application-held viem account authorizes transactions. */\nexport type EvmAccount =\n | { type: 'provider'; provider: { request: EvmRequest }; account?: Address | undefined }\n | { type: 'local'; account: LocalAccount }\n\n/**\n * Configures EVM network and optional wallet access for one named bridge chain.\n *\n * @property transport Lazy public JSON-RPC transport.\n * @property publicClient Existing viem public client used directly.\n * @property account Injected-provider or local signing authority.\n * @property walletClient Existing viem wallet client used directly.\n */\nexport type EvmClientConfig = {\n transport?: EvmTransport | undefined\n publicClient?: PublicClient | undefined\n account?: EvmAccount | undefined\n walletClient?: WalletClient | undefined\n}\n\n/**\n * Describes an EVM call used by bridge protocol actions.\n *\n * @property to Contract address.\n * @property data ABI-encoded calldata.\n * @property account Optional call sender.\n */\nexport type EvmCallParameters = { to: Address; data: Hex; account?: Address | undefined }\n\n/**\n * Describes an EVM transaction used by bridge protocol actions.\n *\n * @property chainId Expected EIP-155 chain id, checked immediately before submission.\n * @property from Optional expected sender, checked against the connected account.\n * @property to Transaction destination.\n * @property data ABI-encoded calldata.\n * @property value Optional native-token value in wei.\n */\nexport type EvmTransactionParameters = {\n chainId: number\n from?: Address | undefined\n to: Address\n data: Hex\n value?: bigint | undefined\n}\n\n/**\n * Represents normalized EVM receipt fields consumed by bridge actions.\n *\n * @property status Viem-normalized execution result.\n * @property transactionHash Canonical transaction hash when returned by the client.\n * @property blockNumber Block containing the transaction when available.\n * @property logs Receipt-log envelopes used to verify protocol events.\n */\nexport type EvmReceipt = {\n status: 'success' | 'reverted'\n transactionHash: Hash\n blockNumber?: bigint | undefined\n logs: readonly {\n address?: Address | undefined\n data: Hex\n topics: readonly Hex[]\n logIndex?: number | undefined\n }[]\n}\n\n/**\n * Represents one finalized EVM log used to recover a source bridge submission.\n *\n * @property address Contract that emitted the event.\n * @property blockNumber Block containing the event.\n * @property transactionHash Transaction that emitted the event.\n * @property logIndex Event position used by protocols such as xReserve.\n * @property data ABI-encoded non-indexed event values.\n * @property topics ABI event signature and indexed values.\n */\nexport type EvmLog = {\n address: Address\n blockNumber: bigint\n transactionHash: Hash\n logIndex: number\n data: Hex\n topics: readonly Hex[]\n}\n\n/**\n * Represents the source transaction fields needed to identify a recovered bridge submission.\n *\n * @property hash Canonical transaction identifier.\n * @property blockNumber Block containing the transaction, or `null` while pending.\n * @property from Account that authorized the transaction.\n * @property to Destination contract, or `null` for contract creation.\n * @property input ABI-encoded call data.\n */\nexport type EvmTransaction = {\n hash: Hash\n blockNumber: bigint | null\n from: Address\n to: Address | null\n input: Hex\n}\n\n/**\n * Selects one contract and inclusive block range for a recovery event scan.\n *\n * @property address Contract whose events should be returned.\n * @property fromBlock First block included in the scan.\n * @property toBlock Last block included in the scan. Defaults to the latest block.\n */\nexport type EvmGetLogsParameters = {\n address: Address\n fromBlock: bigint\n toBlock?: bigint | undefined\n}\n\n/**\n * Exposes account-free EVM operations used by bridge actions.\n *\n * @property getChainId Reads the current EIP-155 chain id.\n * @property getBalance Reads one account's native-currency balance in atomic units.\n * @property call Executes a read-only EVM call.\n * @property getTransactionReceipt Reads a receipt or returns `null` while unavailable.\n * @property getLogs Reads finalized contract events within an inclusive block range.\n * @property getTransaction Reads a transaction or returns `null` while unavailable.\n */\nexport type EvmPublicClient = {\n getChainId: () => Promise<number>\n getBalance: (address: Address) => Promise<bigint>\n call: (params: EvmCallParameters) => Promise<Hex>\n getTransactionReceipt: (hash: Hash) => Promise<EvmReceipt | null>\n getLogs: (params: EvmGetLogsParameters) => Promise<readonly EvmLog[]>\n getTransaction: (hash: Hash) => Promise<EvmTransaction | null>\n}\n\n/**\n * Exposes account-authorized EVM operations used by bridge actions.\n *\n * @property getAddress Resolves the active account.\n * @property sendTransaction Validates chain and sender, then signs and broadcasts.\n */\nexport type EvmWalletClient = {\n getAddress: () => Promise<Address>\n sendTransaction: (params: EvmTransactionParameters) => Promise<Hash>\n}\n\n/**\n * Holds materialized EVM public and wallet capabilities.\n *\n * @property family Prevents this client from being used for a Solana or Aleo route stored under the wrong chain identifier.\n * @property publicClient Required read capability.\n * @property walletClient Optional signing capability.\n */\nexport type EvmClient = {\n family: 'evm'\n publicClient: EvmPublicClient\n walletClient?: EvmWalletClient | undefined\n}\n\n/**\n * Defines the EVM JSON-RPC endpoint used when a bridge action reads or submits.\n *\n * Creating the transport does not contact the endpoint.\n *\n * @param url EVM JSON-RPC endpoint contacted by the resulting client.\n * @param options Optional Fetch API implementation. Defaults to `globalThis.fetch` when the client is created.\n * @returns Deferred HTTP configuration accepted by `createEvmClient`.\n * @example const transport = evmHttp('https://rpc.example')\n */\nexport function evmHttp(url: string, options: EvmHttpOptions = {}): EvmTransport {\n return { type: 'http', url, fetch: options.fetch }\n}\n\n/**\n * Defines EVM network access through an application-supplied EIP-1193 request function.\n *\n * Creating the transport does not call the request function.\n *\n * @param request Function that sends JSON-RPC methods when a bridge action needs network access.\n * @returns Deferred custom transport configuration accepted by `createEvmClient`.\n * @example const transport = evmCustom(window.ethereum.request.bind(window.ethereum))\n */\nexport function evmCustom(request: EvmRequest): EvmTransport {\n return { type: 'custom', request }\n}\n\n/**\n * Selects an injected EIP-1193 wallet to authorize EVM bridge transactions.\n *\n * The provider retains custody of the account and controls every signature\n * request. This helper does not connect to the wallet or request a signature.\n *\n * @param provider Browser or application wallet exposing an EIP-1193 `request` function.\n * @param options Optional account that MUST authorize transactions. Defaults to the first account returned by `eth_accounts` at submission time.\n * @returns Deferred wallet configuration accepted by `createEvmClient`.\n * @example const account = evmProvider(window.ethereum)\n */\nexport function evmProvider(\n provider: { request: EvmRequest },\n options: { account?: Address | undefined } = {},\n): EvmAccount {\n return { type: 'provider', provider, account: options.account }\n}\n\n/**\n * Selects an application-held EVM private key for unattended bridge transactions.\n *\n * The key is converted to a viem account that signs on the caller's device or\n * server. This helper does not contact a chain or submit a transaction; the\n * application remains responsible for keeping the key secret.\n *\n * @param privateKey Secret 32-byte hexadecimal key held by the application.\n * @returns Deferred local signing configuration accepted by `createEvmClient`.\n * @example const account = evmPrivateKey(process.env.EVM_PRIVATE_KEY as Hex)\n */\nexport function evmPrivateKey(privateKey: Hex): EvmAccount {\n return { type: 'local', account: privateKeyToAccount(privateKey) }\n}\n\n/**\n * Selects an existing viem local account for unattended bridge transactions.\n *\n * The account signs on the caller's device or server. This helper does not\n * contact a chain, request an external wallet approval, or submit a transaction.\n *\n * @param account Viem account whose signer and address remain owned by the application.\n * @returns Deferred local signing configuration accepted by `createEvmClient`.\n * @example const account = evmLocalAccount(privateKeyToAccount(privateKey))\n */\nexport function evmLocalAccount(account: LocalAccount): EvmAccount {\n return { type: 'local', account }\n}\n\n/**\n * Creates the EVM client used to read bridge state and optionally authorize transactions.\n *\n * Construction wires together existing clients or deferred transports without\n * making an RPC request. Read-only actions need only a transport or public\n * client; fund-moving actions also require an account or wallet client.\n *\n * @param config EVM network access and optional wallet authorization supplied by the application.\n * @returns EVM read and optional wallet capabilities used by bridge actions.\n * @throws BridgeError When multiple alternatives are supplied for one capability, no capability is supplied, or a local signer has no network access.\n * @example const client = createEvmClient({ transport: evmHttp(rpcUrl), account: evmPrivateKey(key) })\n */\nexport function createEvmClient(\n config: EvmClientConfig,\n): EvmClient {\n if (config.transport && config.publicClient) {\n throw new BridgeError('EVM client accepts either transport or publicClient, not both')\n }\n if (config.account && config.walletClient) {\n throw new BridgeError('EVM client accepts either account or walletClient, not both')\n }\n if (!config.transport && !config.publicClient && !config.account && !config.walletClient) {\n throw new BridgeError('EVM client requires a public or wallet capability')\n }\n if (config.account?.type === 'local' && !config.transport && !config.publicClient) {\n throw new BridgeError('Local EVM accounts require an EVM transport or public client')\n }\n return materializeEvmClient(config, globalThis.fetch)\n}\n\nfunction transportFor(transport: EvmTransport, defaultFetch: typeof globalThis.fetch) {\n if (transport.type === 'custom') return custom({ request: transport.request })\n return http(transport.url, { fetchFn: transport.fetch ?? defaultFetch })\n}\n\nfunction normalizePublicClient(client: PublicClient): EvmPublicClient {\n return {\n getChainId: () => client.getChainId(),\n getBalance: (address) => client.getBalance({ address }),\n call: async (params) => (await client.call(params)).data ?? '0x',\n getTransactionReceipt: async (hash) => {\n try {\n return await client.getTransactionReceipt({ hash }) as unknown as EvmReceipt\n } catch (error) {\n if (error instanceof Error && error.name === 'TransactionReceiptNotFoundError') return null\n throw error\n }\n },\n getLogs: async (params) => client.getLogs(params) as unknown as EvmLog[],\n getTransaction: async (hash) => {\n try {\n return await client.getTransaction({ hash }) as unknown as EvmTransaction\n } catch (error) {\n if (error instanceof Error && error.name === 'TransactionNotFoundError') return null\n throw error\n }\n },\n }\n}\n\nfunction normalizeWalletClient(client: WalletClient): EvmWalletClient {\n // A viem WalletClient may carry a local account or obtain accounts from an\n // injected provider. Resolve either form only when authorization is needed.\n const resolveAddress = async (): Promise<Address> => {\n if (client.account) return client.account.address\n const [address] = await client.getAddresses()\n if (!address) throw new BridgeError('EVM wallet has no connected account')\n return address\n }\n return {\n getAddress: resolveAddress,\n sendTransaction: async ({ chainId, from, ...transaction }) => {\n // Public reads and wallet submissions can be backed by different viem\n // clients. Bind the wallet itself to the intended chain before broadcast.\n const currentChainId = await client.getChainId()\n if (currentChainId !== chainId) {\n throw new BridgeError(`EVM wallet is connected to chain ${currentChainId}; expected ${chainId}`)\n }\n const account = await resolveAddress()\n // Passing the resolved account supports accountless injected clients;\n // passing the local account object preserves its local signing behavior.\n if (from && getAddress(from) !== getAddress(account)) {\n throw new BridgeError(`EVM transaction sender ${from} does not match connected account ${account}`)\n }\n return client.sendTransaction({\n ...transaction,\n account: client.account ?? account,\n // Viem treats an omitted chain as a request to validate against a\n // configured chain and throws when an account-only client has none.\n // The adapter already compared getChainId() with the requested id.\n chain: client.chain ?? null,\n } as never)\n },\n }\n}\n\n/** Normalizes viem, EIP-1193, and local-account inputs behind the bridge's EVM capabilities. */\nfunction materializeEvmClient(\n config: EvmClientConfig,\n defaultFetch: typeof globalThis.fetch,\n): EvmClient {\n const transport = config.transport ? transportFor(config.transport, defaultFetch) : undefined\n // Prefer caller-owned viem clients. A deferred transport is materialized only\n // when the corresponding public capability was not supplied directly.\n const viemPublic = config.publicClient ?? (transport ? createPublicClient({ transport }) : undefined)\n let publicClient = viemPublic ? normalizePublicClient(viemPublic) : undefined\n let walletClient = config.walletClient ? normalizeWalletClient(config.walletClient) : undefined\n\n if (!publicClient && config.walletClient) {\n // A viem wallet transport can answer read-only JSON-RPC calls. Expose that\n // capability when no separate public transport was configured.\n const request = config.walletClient.request as EvmRequest\n publicClient = normalizePublicClient(createPublicClient({ transport: custom({ request }) }))\n }\n\n if (config.account?.type === 'provider') {\n const provider = config.account.provider\n if (!publicClient) publicClient = normalizePublicClient(createPublicClient({ transport: custom(provider) }))\n const account = config.account.account\n walletClient = {\n getAddress: async () => {\n if (account) return account\n const addresses = await provider.request({ method: 'eth_accounts' })\n const address = Array.isArray(addresses) ? addresses[0] : undefined\n if (typeof address !== 'string') throw new BridgeError('EVM wallet has no connected account')\n return address as Address\n },\n sendTransaction: async ({ chainId, from, to, data, value }) => {\n // EIP-1193 providers own chain selection. Refuse to request a signature\n // on a different chain instead of silently switching or misdirecting funds.\n const current = await provider.request({ method: 'eth_chainId' })\n if (typeof current !== 'string' || Number.parseInt(current, 16) !== chainId) {\n throw new BridgeError(`EVM wallet is connected to chain ${String(current)}; expected ${chainId}`)\n }\n const sender = from ?? await walletClient!.getAddress()\n const hash = await provider.request({\n method: 'eth_sendTransaction',\n params: [{ from: sender, to, data, ...(value === undefined ? {} : { value: `0x${value.toString(16)}` }) }],\n })\n if (typeof hash !== 'string') throw new BridgeError('EVM wallet returned an invalid transaction hash')\n return hash as Hash\n },\n }\n } else if (config.account?.type === 'local') {\n if (!viemPublic) throw new BridgeError('Local EVM accounts require an EVM transport or public client')\n const localAccount = config.account.account\n walletClient = {\n getAddress: async () => localAccount.address,\n sendTransaction: async ({ chainId, from, ...transaction }) => {\n // Local signing still derives nonce, gas, and broadcast behavior from\n // the public transport, so bind that transport to the requested chain.\n const currentChainId = await viemPublic.getChainId()\n if (currentChainId !== chainId) {\n throw new BridgeError(`EVM transport is connected to chain ${currentChainId}; expected ${chainId}`)\n }\n if (from && getAddress(from) !== getAddress(localAccount.address)) {\n throw new BridgeError(`EVM transaction sender ${from} does not match local account ${localAccount.address}`)\n }\n const chain = viemPublic.chain ?? defineChain({\n id: chainId,\n name: `EVM chain ${chainId}`,\n nativeCurrency: { name: 'Native token', symbol: 'ETH', decimals: 18 },\n rpcUrls: { default: { http: [] } },\n })\n // Reuse the caller's public-client request path for submission. This\n // keeps custom transports, batching, and authentication consistent.\n const localWallet = createWalletClient({\n account: localAccount,\n chain,\n transport: custom({ request: viemPublic.request }, { retryCount: 0 }),\n })\n return localWallet.sendTransaction({ ...transaction, account: localAccount, chain } as never)\n },\n }\n }\n\n if (!publicClient) throw new BridgeError('EVM client could not materialize a public client')\n return { family: 'evm', publicClient, walletClient }\n}\n","import type { Client } from '@provablehq/veil-core'\nimport { BridgeError } from '../errors/bridgeErrors.js'\nimport type { AleoWalletClient } from '../types/aleo.js'\n\n/**\n * Configures Aleo network and optional wallet access for one named bridge chain.\n * @property publicClient Required Veil public client used for chain reads.\n * @property account Optional Veil-compatible wallet client used for execution.\n */\nexport type AleoClientConfig = {\n publicClient: Client\n account?: AleoWalletClient | undefined\n}\n\n/**\n * Holds materialized Aleo public and wallet capabilities.\n * @property family Prevents this client from being used for an EVM or Solana route stored under the wrong chain identifier.\n * @property publicClient Required Veil public client.\n * @property walletClient Optional Veil-compatible execution client.\n */\nexport type AleoClient = {\n family: 'aleo'\n publicClient: Client\n walletClient?: AleoWalletClient | undefined\n}\n\n/**\n * Selects the Aleo wallet that may authorize bridge and privacy transactions.\n *\n * The wallet retains custody of its account and proving configuration. This\n * helper does not connect to Aleo, request approval, or move funds.\n *\n * @param client Veil wallet client or compatible wallet adapter supplied by the application.\n * @returns The same wallet with only its transaction-execution capability exposed to the bridge.\n * @example const account = aleoWallet(aleoWalletClient)\n */\nexport function aleoWallet(client: AleoWalletClient): AleoWalletClient {\n return client\n}\n\n/**\n * Creates the Aleo client used to read bridge state and optionally authorize transactions.\n *\n * Construction stores the supplied clients without contacting Aleo or prompting\n * the wallet. Read-only actions need only `publicClient`; fund-moving actions\n * also require `account`.\n *\n * @param config Aleo network access and optional wallet authorization supplied by the application.\n * @returns Aleo read and optional wallet capabilities used by bridge actions.\n * @throws BridgeError When the public client is absent.\n * @example const client = createAleoClient({ publicClient, account: walletClient })\n */\nexport function createAleoClient(\n config: AleoClientConfig,\n): AleoClient {\n if (!config.publicClient) throw new BridgeError('Aleo client requires a public client')\n return { family: 'aleo', publicClient: config.publicClient, walletClient: config.account }\n}\n","import type { Client } from '@provablehq/veil-core'\nimport type { EvmClient, EvmWalletClient } from '../connections/evm.js'\nimport type { SolanaClient, SolanaWalletClient } from '../connections/solana.js'\nimport { DEFAULT_BRIDGE_REGISTRY } from '../registry/default.js'\nimport type {\n AleoWalletClient,\n ExecuteAleoHyperlaneTransferRemoteParameters,\n ExecuteXReserveBurnParameters,\n ExecuteXReservePrivateMintParameters,\n QuoteAleoHyperlaneGasPaymentParameters,\n} from '../types/aleo.js'\nimport type { BridgeRegistry } from '../types/protocol.js'\nimport type {\n ExecuteEvmHyperlaneTransferParameters,\n QuoteEvmHyperlaneTransferParameters,\n} from '../types/evm.js'\nimport type {\n ExecuteSolanaHyperlaneTransferParameters,\n QuoteSolanaHyperlaneTransferParameters,\n} from '../types/solana.js'\nimport type {\n ExecuteEvmXReserveTransferParameters,\n GetXReserveAttestationParameters,\n QuoteEvmXReserveTransferParameters,\n XReserveHttpTransport,\n} from '../types/xreserve.js'\nimport * as aleoHyperlane from './hyperlane/aleo.js'\nimport * as evmHyperlane from './hyperlane/evm.js'\nimport * as solanaHyperlane from './hyperlane/solana.js'\nimport * as aleoToEvmXReserve from './xreserve/aleoToEvm.js'\nimport * as evmToAleoXReserve from './xreserve/evmToAleo.js'\n\n/**\n * Selects a custom registry for a direct protocol helper.\n *\n * @property registry Reviewed registry snapshot. Defaults to the package registry.\n */\nexport type ProtocolHelperRegistry = {\n registry?: BridgeRegistry | undefined\n}\n\nfunction splitRegistry<Params extends object>(\n params: Params & ProtocolHelperRegistry,\n): [BridgeRegistry, Params] {\n const { registry = DEFAULT_BRIDGE_REGISTRY, ...rest } = params\n return [registry, rest as unknown as Params]\n}\n\n/**\n * Exposes chain-specific Hyperlane helpers for direct protocol integrations.\n *\n * Helpers use the default reviewed registry unless `params.registry` supplies\n * a custom snapshot. Most applications should use the protocol-neutral bridge\n * client actions instead.\n *\n * @example const result = await hyperlane.evm.quote(client, { plan, recipientBytes32 })\n */\nexport const hyperlane = {\n aleo: {\n /**\n * Calculates the Hyperlane relayer payment for a transfer leaving Aleo.\n *\n * Reads the current gas oracle on Aleo without requesting a signature or\n * moving funds. The payment can change before the transfer is submitted.\n *\n * @param client Aleo network access used to read the current gas price and exchange rate.\n * @param params Route selected for the transfer and optional replacement bridge deployments.\n * @returns Destination gas requirements and the exact payment in Aleo microcredits.\n * @throws BridgeError When the route is unavailable or its gas configuration is invalid.\n * @example const result = await hyperlane.aleo.quote(client, { routeId })\n */\n quote(client: Client, params: QuoteAleoHyperlaneGasPaymentParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<QuoteAleoHyperlaneGasPaymentParameters>(params)\n return aleoHyperlane.quote(registry, client, actionParams)\n },\n /**\n * Begins an Aleo-to-Ethereum or Aleo-to-Solana transfer through Hyperlane.\n *\n * The Aleo wallet proves, signs, and submits the source transaction, which\n * commits the asset and incurs an Aleo network fee.\n *\n * @param client Aleo wallet that authorizes and submits the source transaction.\n * @param params Route, assets, amount, recipient, gas payment, and optional replacement bridge deployments.\n * @returns The Aleo transaction identifier and state needed to follow delivery.\n * @throws BridgeError When the transfer is unavailable, its payment is invalid, or wallet submission fails.\n * @example const result = await hyperlane.aleo.execute(client, { plan, gasPaymentMicrocredits })\n */\n execute(client: AleoWalletClient, params: ExecuteAleoHyperlaneTransferRemoteParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<ExecuteAleoHyperlaneTransferRemoteParameters>(params)\n return aleoHyperlane.execute(registry, client, actionParams)\n },\n },\n evm: {\n /**\n * Calculates the funds required for a Hyperlane transfer leaving an EVM chain.\n *\n * Reads the deployed router without requesting a wallet signature or moving\n * funds. The quoted network payment can change before submission.\n *\n * @param client EVM network access used to read the selected Hyperlane router.\n * @param params Route, assets, amount, encoded Aleo recipient, and optional replacement bridge deployments.\n * @returns Source token amount and native network payment required by the router.\n * @throws BridgeError When the route is unavailable or the router returns invalid values.\n * @example const result = await hyperlane.evm.quote(client, { plan, recipientBytes32 })\n */\n quote(client: EvmClient, params: QuoteEvmHyperlaneTransferParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<QuoteEvmHyperlaneTransferParameters>(params)\n return evmHyperlane.quote(registry, client, actionParams)\n },\n /**\n * Begins an EVM-to-Aleo transfer through Hyperlane.\n *\n * An ERC-20 transfer may first request token approval. The wallet then\n * submits the source dispatch, which commits funds and incurs network fees.\n *\n * @param client EVM network and wallet access used to authorize and submit the transfer.\n * @param params Route, assets, amount, encoded Aleo recipient, confirmation controls, and optional replacement bridge deployments.\n * @returns Submitted approval identifiers and state needed to follow delivery.\n * @throws BridgeError When the transfer is unavailable, wallet authorization fails, funds are insufficient, or submission fails.\n * @example const result = await hyperlane.evm.execute(client, { plan, recipientBytes32 })\n */\n execute(client: EvmClient & { walletClient: EvmWalletClient }, params: ExecuteEvmHyperlaneTransferParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<ExecuteEvmHyperlaneTransferParameters>(params)\n return evmHyperlane.execute(registry, client, actionParams)\n },\n },\n solana: {\n /**\n * Calculates the SOL required for a Solana-to-Aleo Hyperlane transfer.\n *\n * Reads current gas, transaction fee, and rent requirements without\n * requesting a wallet signature or moving funds.\n *\n * @param client Solana network access used to read account, fee, and rent values.\n * @param params Route, amount, recipient, and optional replacement bridge deployments.\n * @returns Transfer amount, relayer payment, network fee, rent, and total required lamports.\n * @throws BridgeError When the route is unavailable or Solana returns invalid account or fee data.\n * @example const result = await hyperlane.solana.quote(client, { plan })\n */\n quote(client: SolanaClient, params: QuoteSolanaHyperlaneTransferParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<QuoteSolanaHyperlaneTransferParameters>(params)\n return solanaHyperlane.quote(registry, client, actionParams)\n },\n /**\n * Begins a Solana-to-Aleo transfer through Hyperlane.\n *\n * The Solana wallet signs and submits the source transaction, which commits\n * SOL and incurs the relayer payment, network fee, and account rent.\n *\n * @param client Solana network and wallet access used to authorize and submit the transfer.\n * @param params Route, amount, recipient, confirmation controls, and optional replacement bridge deployments.\n * @returns The Solana signature and state needed to follow delivery.\n * @throws BridgeError When the route is unavailable, funds are insufficient, wallet authorization fails, or submission fails.\n * @example const result = await hyperlane.solana.execute(client, { plan })\n */\n execute(client: SolanaClient & { walletClient: SolanaWalletClient }, params: ExecuteSolanaHyperlaneTransferParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<ExecuteSolanaHyperlaneTransferParameters>(params)\n return solanaHyperlane.execute(registry, client, actionParams)\n },\n },\n} as const\n\n/**\n * Exposes directional Circle xReserve helpers for direct protocol integrations.\n *\n * Helpers use the default reviewed registry unless `params.registry` supplies\n * a custom snapshot. Most applications should use the protocol-neutral bridge\n * client actions instead.\n *\n * @example const result = await xreserve.evmToAleo.quote(client, { plan })\n */\nexport const xreserve = {\n evmToAleo: {\n /**\n * Calculates the USDC and token approval required for an xReserve transfer to Aleo.\n *\n * Reads the prepared sender's USDC balance and existing xReserve allowance\n * without requesting a signature or moving funds. When the plan omits a\n * sender, the client resolves it from its optional wallet capability.\n *\n * @param client Ethereum network access, plus a wallet when the plan does not identify the source account.\n * @param params Route, amount, Aleo recipient, privacy preference, and optional replacement bridge deployments.\n * @returns Deposit amount, maximum provider fee, balance, allowance, and whether approval is required.\n * @throws BridgeError When the route is unavailable, the account lacks funds, or Ethereum returns invalid state.\n * @example const result = await xreserve.evmToAleo.quote(client, { plan })\n */\n quote(client: EvmClient, params: QuoteEvmXReserveTransferParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<QuoteEvmXReserveTransferParameters>(params)\n return evmToAleoXReserve.quote(registry, client, actionParams)\n },\n /**\n * Begins a USDC-to-USDCx transfer from Ethereum to Aleo through xReserve.\n *\n * The wallet may first approve USDC spending, then submits the reserve\n * deposit that commits funds and incurs Ethereum network fees.\n *\n * @param client Ethereum network and wallet access used to authorize and submit the deposit.\n * @param params Route, amount, Aleo recipient, privacy preference, confirmation controls, and optional replacement bridge deployments.\n * @returns Submitted approval identifiers and state needed to obtain Circle's attestation and follow delivery.\n * @throws BridgeError When the route is unavailable, funds are insufficient, wallet authorization fails, or submission fails.\n * @example const result = await xreserve.evmToAleo.execute(client, { plan })\n */\n execute(client: EvmClient & { walletClient: EvmWalletClient }, params: ExecuteEvmXReserveTransferParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<ExecuteEvmXReserveTransferParameters>(params)\n return evmToAleoXReserve.execute(registry, client, actionParams)\n },\n /**\n * Checks whether Circle has attested one confirmed xReserve deposit.\n *\n * Contacts Circle once and does not request a wallet signature, submit a\n * transaction, or move funds.\n *\n * @param client HTTP access used to contact Circle's attestation service.\n * @param params Deposit message hash, route, cancellation signal, and optional replacement bridge deployments.\n * @returns Whether the attestation is pending or the signed attestation is ready.\n * @throws BridgeError When Circle returns an invalid response.\n * @example const result = await xreserve.evmToAleo.getAttestation(fetch, { routeId, messageHash })\n */\n getAttestation(client: XReserveHttpTransport, params: GetXReserveAttestationParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<GetXReserveAttestationParameters>(params)\n return evmToAleoXReserve.getAttestation(registry, client, actionParams)\n },\n /**\n * Delivers a private USDCx record after Circle attests an Ethereum deposit.\n *\n * The Aleo wallet proves, signs, and submits the private mint, which incurs\n * an Aleo network fee. The source deposit is not repeated.\n *\n * @param client Aleo wallet that authorizes and submits the private mint.\n * @param params Transfer details, attested deposit, private mint secret, recovery callback, and optional replacement bridge deployments.\n * @returns The Aleo transaction identifier and state needed to confirm private delivery.\n * @throws BridgeError When the attestation or private mint secret is invalid, wallet authorization fails, or submission fails.\n * @example const result = await xreserve.evmToAleo.complete(client, { plan, deposit, attestation })\n */\n complete(client: AleoWalletClient, params: ExecuteXReservePrivateMintParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<ExecuteXReservePrivateMintParameters>(params)\n return evmToAleoXReserve.complete(registry, client, actionParams)\n },\n },\n aleoToEvm: {\n /**\n * Begins a USDCx-to-USDC transfer from Aleo to Ethereum through xReserve.\n *\n * The Aleo wallet proves, signs, and submits a burn that commits USDCx and\n * incurs an Aleo network fee. The provider completes Ethereum delivery\n * without another wallet authorization.\n *\n * @param client Aleo wallet that authorizes and submits the USDCx burn.\n * @param params Route, amount, Ethereum recipient, public or private funding preference, and optional replacement bridge deployments.\n * @returns The Aleo transaction identifier and state needed to follow provider-managed delivery.\n * @throws BridgeError When the route or private funding inputs are invalid, wallet authorization fails, or submission fails.\n * @example const result = await xreserve.aleoToEvm.execute(client, { plan, mode: 'public' })\n */\n execute(client: AleoWalletClient, params: ExecuteXReserveBurnParameters & ProtocolHelperRegistry) {\n const [registry, actionParams] = splitRegistry<ExecuteXReserveBurnParameters>(params)\n return aleoToEvmXReserve.execute(registry, client, actionParams)\n },\n },\n} as const\n","import type { BridgeRegistry } from '../types/protocol.js'\nimport type { ExecuteXReserveBurnParameters, XReserveBurnCall } from '../types/aleo.js'\nimport { buildBurnCall } from '../protocols/xreserve/aleoToEvm.js'\n\n/**\n * Builds an Aleo xReserve burn call without prompting a wallet.\n *\n * Selects the reviewed entrypoint and validates mode-specific inputs without\n * contacting Aleo or prompting a wallet.\n *\n * @param registry Supported assets and reviewed xReserve deployments.\n * @param params Route, amount, Ethereum recipient, funding mode, and private inputs when applicable.\n * @returns Aleo program, transition, ordered inputs, atomic amount, destination domain, and encoded recipient.\n * @throws BridgeError When the route is unavailable, the amount cannot cover the withdrawal fee, the recipient is invalid, or private funding inputs are missing.\n * @example const call = buildXReserveBurnCall(registry, { plan, mode: 'public' })\n */\nexport function buildXReserveBurnCall(\n registry: BridgeRegistry,\n params: ExecuteXReserveBurnParameters,\n): XReserveBurnCall {\n return buildBurnCall(registry, params)\n}\n","import type { BridgeRegistry } from '../types/protocol.js'\nimport type { AleoHyperlaneTransferRemoteCall, ExecuteAleoHyperlaneTransferRemoteParameters } from '../types/aleo.js'\nimport { buildTransferRemoteCall as buildTransferCall } from '../protocols/hyperlane/aleo.js'\n\n/**\n * Builds an Aleo Hyperlane `transfer_remote` call without prompting a wallet.\n *\n * Validates the transfer details against reviewed route metadata without\n * contacting Aleo or prompting a wallet.\n *\n * @param registry Supported assets and reviewed Hyperlane deployments.\n * @param params Route, amount, recipient, authorization mode, and optional current relayer payment.\n * @returns Aleo program, transition, ordered inputs, atomic amount, and any configuration that is not ready for submission.\n * @throws BridgeError When the transfer conflicts with the deployment or the relayer payment is invalid.\n * @example const call = buildAleoHyperlaneTransferRemoteCall(registry, { plan, gasPaymentMicrocredits })\n */\nexport function buildAleoHyperlaneTransferRemoteCall(\n registry: BridgeRegistry,\n params: ExecuteAleoHyperlaneTransferRemoteParameters,\n): AleoHyperlaneTransferRemoteCall {\n return buildTransferCall(registry, params)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAS,QACP,UACA,SACA,SACA,QACmB;AAGnB,QAAM,QAAQ,SAAS,OAAO,KAAK,CAAC,UAAU,MAAM,OAAO,OAAO;AAClE,MAAI,CAAC,MAAO,OAAM,IAAI,YAAY,0BAA0B,OAAO,GAAG;AACtE,QAAM,SAAS,QAAQ,OAAO;AAC9B,MAAI,CAAC,OAAQ,OAAM,IAAI,YAAY,sCAAsC,OAAO,GAAG;AACnF,MAAI,OAAO,WAAW,MAAM,UAAU,OAAO,WAAW,QAAQ;AAC9D,UAAM,IAAI,YAAY,WAAW,OAAO,iBAAiB,OAAO,MAAM,6BAA6B,MAAM,MAAM,GAAG;AAAA,EACpH;AACA,SAAO;AACT;AAGO,SAAS,iBAAiB,UAA0B,SAA6B,SAA4B;AAClH,SAAO,QAAQ,UAAU,SAAS,SAAS,KAAK;AAClD;AAGO,SAAS,2BAA2B,UAA0B,SAA6B,SAAiB,QAA+D;AAChL,QAAM,SAAS,iBAAiB,UAAU,SAAS,OAAO;AAC1D,MAAI,CAAC,OAAO,aAAc,OAAM,IAAI,YAAY,oCAAoC,MAAM,cAAc,OAAO,GAAG;AAClH,SAA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G,YAAM,CAAC,UAAU,YAAY,IAAI,cAAgD,MAAM;AACvF,aAAyB,eAAe,UAAU,QAAQ,YAAY;AAAA,IACxE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAaA,SAAS,QAA0B,QAAuE;AACxG,YAAM,CAAC,UAAU,YAAY,IAAI,cAAoD,MAAM;AAC3F,aAAyB,SAAS,UAAU,QAAQ,YAAY;AAAA,IAClE;AAAA,EACF;AAAA,EACA,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAcT,QAAQ,QAA0B,QAAgE;AAChG,YAAM,CAAC,UAAU,YAAY,IAAI,cAA6C,MAAM;AACpF,aAAyBA,SAAQ,UAAU,QAAQ,YAAY;AAAA,IACjE;AAAA,EACF;AACF;;;AClPO,SAAS,sBACd,UACA,QACkB;AAClB,SAAO,cAAc,UAAU,MAAM;AACvC;;;ACLO,SAAS,qCACd,UACA,QACiC;AACjC,SAAO,wBAAkB,UAAU,MAAM;AAC3C;","names":["route","getAddress","isAddress","route","metadata","isAddress","getAddress","account","resolve","quote","pending","execute","sourceTxId","sourceReceipt","messageId","allowance","checkpoint","route","metadata","account","quote","metadata","resolve","getSourceStatus","execute","signature","message","validatedRoute","route","execute","decodeEventLog","decodeFunctionResult","encodeFunctionData","getAddress","isAddress","isHash","parseAbi","ERC20_ABI","parseAbi","route","isAddress","getAddress","assertChain","decodeFunctionResult","isHash","resolve","quote","encodeFunctionData","decodeEventLog","approvalScanBlock","getSourceStatus","recoverSourceCheckpoint","pending","execute","sourceTxId","receipt","data","submitted","route","decodeFunctionResult","encodeFunctionData","getAddress","parseAbi","parseAbi","getAddress","encodeFunctionData","decodeFunctionResult","execute","route","routes","quote","isHash","isHex","complete","route","isHex","isHash","_nextAction","isHash","readContract","decodeFunctionResult","encodeFunctionData","getAddress","hexToBytes","isAddress","isHash","parseAbi","parseAbi","littleEndianU128","hexToBytes","isHash","readContract","isAddress","getAddress","encodeFunctionData","decodeFunctionResult","readContract","isHash","isHash","readContract","route","isHash","getSourceStatus","route","recoverSourceCheckpoint","classifyBroadcastError","DuplicateTransactionError","route","classifyBroadcastError","DuplicateTransactionError","execute","wait","resolve","quote","execute","complete","wait","metadata","chains","assets","route","metadata","route","getAddress","account","getAddress","quote","execute"]}