{"version":3,"sources":["../src/chains/avalanche/AvalancheClient.ts"],"sourcesContent":["/**\n * Veridex Protocol SDK — Avalanche Chain Client\n *\n * Extends the standard EVMClient with Avalanche-native capabilities:\n * - ACP-204 precompile detection (native secp256r1 at 0x0100, 6,900 gas)\n * - ICM / Teleporter routing awareness for intra-Avalanche L1 messaging\n * - Chainlink AVAX/USD price feeds for USD-denominated session limits\n *\n * @example\n * ```typescript\n * import { AvalancheClient } from '@veridex/sdk/chains/avalanche';\n *\n * const client = new AvalancheClient({\n *   chainId: 43113,\n *   wormholeChainId: 6,\n *   rpcUrl: 'https://api.avax-test.network/ext/bc/C/rpc',\n *   hubContractAddress: '0x...',\n *   wormholeCoreBridge: '0x7bbcE28e64B3F8b84d876Ab298393c38ad7aac4C',\n * });\n *\n * // Check ACP-204 precompile\n * const available = await client.isACP204Available();\n *\n * // Get AVAX price for budget calculations\n * const price = await client.getAvaxPriceUSD();\n * ```\n */\n\nimport { ethers } from 'ethers';\nimport { EVMClient, type EVMClientConfig } from '../evm/EVMClient.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface AvalancheClientConfig extends EVMClientConfig {\n  /** ACP-204 P256 verifier wrapper contract address */\n  p256VerifierAddress?: string;\n  /** ICM Spoke contract address for cross-L1 session bridging */\n  icmSpokeAddress?: string;\n  /** Chainlink AVAX/USD price feed address */\n  chainlinkAvaxUsdFeed?: string;\n  /** Chainlink USDC/USD price feed address */\n  chainlinkUsdcUsdFeed?: string;\n  /** Chainlink USDT/USD price feed address */\n  chainlinkUsdtUsdFeed?: string;\n}\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/** ACP-204 precompile address on Avalanche C-Chain */\nconst ACP204_PRECOMPILE = '0x0000000000000000000000000000000000000100';\n\n/** Minimal Chainlink AggregatorV3 ABI */\nconst CHAINLINK_AGGREGATOR_ABI = [\n  'function latestRoundData() view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)',\n  'function decimals() view returns (uint8)',\n];\n\n/** Minimal ICM Spoke ABI for session/identity queries */\nconst ICM_SPOKE_ABI = [\n  'function verifySession(bytes32 sessionKeyHash, uint256 amount) view returns (bool valid, uint256 remainingBudget)',\n  'function getSession(bytes32 sessionKeyHash) view returns (bytes32 userKeyHash, uint256 expiry, uint256 maxValue, uint256 totalBudget, uint256 spent, bool active)',\n  'function getStatus() view returns (bool paused, uint256 totalMessages, uint256 totalSessions, uint256 totalPayments)',\n  'function isKeyAuthorized(bytes32 identityKeyHash, bytes32 keyHash) view returns (bool)',\n];\n\n/** Minimal AvalancheP256Verifier ABI */\nconst P256_VERIFIER_ABI = [\n  'function isPrecompileAvailable() view returns (bool available)',\n  'function computeKeyHash(uint256 x, uint256 y) view returns (bytes32)',\n];\n\n// ============================================================================\n// AvalancheClient\n// ============================================================================\n\n/**\n * Avalanche-specific SDK chain client.\n *\n * Wraps the standard EVMClient and adds:\n * - ACP-204 precompile availability checks\n * - Chainlink AVAX/USD price queries (for USD-denominated budgets)\n * - ICM Spoke queries (cross-L1 session verification)\n * - ICM-aware message routing (Teleporter for intra-Avalanche, Wormhole for cross-ecosystem)\n */\nexport class AvalancheClient extends EVMClient {\n  private avaxProvider: ethers.JsonRpcProvider;\n  private p256VerifierAddress: string;\n  private icmSpokeAddress: string;\n  private chainlinkAvaxUsdFeed: string;\n  private chainlinkUsdcUsdFeed: string;\n  private chainlinkUsdtUsdFeed: string;\n\n  // Price cache (avoid excessive RPC calls)\n  private priceCache: Map<string, { price: number; timestamp: number }> = new Map();\n  private readonly CACHE_TTL_MS = 30_000; // 30 seconds\n\n  constructor(config: AvalancheClientConfig) {\n    super(config);\n    this.avaxProvider = new ethers.JsonRpcProvider(config.rpcUrl);\n    this.p256VerifierAddress = config.p256VerifierAddress || '';\n    this.icmSpokeAddress = config.icmSpokeAddress || '';\n    this.chainlinkAvaxUsdFeed = config.chainlinkAvaxUsdFeed || '';\n    this.chainlinkUsdcUsdFeed = config.chainlinkUsdcUsdFeed || '';\n    this.chainlinkUsdtUsdFeed = config.chainlinkUsdtUsdFeed || '';\n  }\n\n  // ========================================================================\n  // ACP-204 Precompile Utilities\n  // ========================================================================\n\n  /**\n   * Check if the ACP-204 secp256r1 precompile is live on this chain.\n   * Returns true on Avalanche C-Chain (mainnet + Fuji), false elsewhere.\n   */\n  async isACP204Available(): Promise<boolean> {\n    // Try via wrapper contract first (more reliable answer)\n    if (this.p256VerifierAddress) {\n      try {\n        const verifier = new ethers.Contract(\n          this.p256VerifierAddress,\n          P256_VERIFIER_ABI,\n          this.avaxProvider,\n        );\n        return await verifier.isPrecompileAvailable();\n      } catch {\n        // Fall through to raw check\n      }\n    }\n\n    // Direct precompile probe\n    try {\n      const zeroInput = new Uint8Array(160);\n      const result = await this.avaxProvider.call({\n        to: ACP204_PRECOMPILE,\n        data: ethers.hexlify(zeroInput),\n      });\n      return result.length === 66; // 32 bytes = 0x + 64 hex chars\n    } catch {\n      return false;\n    }\n  }\n\n  /**\n   * Get the estimated gas cost (in wei) for a single P-256 verification.\n   * Deterministic on Avalanche: 6,900 gas for precompile + ~300 staticcall overhead.\n   */\n  async estimatePasskeyVerificationGas(): Promise<bigint> {\n    const feeData = await this.avaxProvider.getFeeData();\n    const gasPrice = feeData.gasPrice || ethers.parseUnits('25', 'gwei');\n    return 7_200n * gasPrice;\n  }\n\n  /**\n   * Get estimated USD cost for a passkey verification.\n   */\n  async estimatePasskeyVerificationCostUSD(): Promise<number> {\n    const gasCostWei = await this.estimatePasskeyVerificationGas();\n    return this.convertAvaxToUsd(gasCostWei);\n  }\n\n  // ========================================================================\n  // Chainlink Price Feeds\n  // ========================================================================\n\n  /**\n   * Get current AVAX/USD price from Chainlink.\n   * Cached for 30 seconds to avoid excessive RPC calls.\n   */\n  async getAvaxPriceUSD(): Promise<number> {\n    return this._getChainlinkPrice(this.chainlinkAvaxUsdFeed, 'avax-usd');\n  }\n\n  /**\n   * Get USDC/USD price (for stablecoin verification).\n   */\n  async getUsdcPriceUSD(): Promise<number> {\n    if (!this.chainlinkUsdcUsdFeed) return 1.0;\n    return this._getChainlinkPrice(this.chainlinkUsdcUsdFeed, 'usdc-usd');\n  }\n\n  /**\n   * Get USDT/USD price.\n   */\n  async getUsdtPriceUSD(): Promise<number> {\n    if (!this.chainlinkUsdtUsdFeed) return 1.0;\n    return this._getChainlinkPrice(this.chainlinkUsdtUsdFeed, 'usdt-usd');\n  }\n\n  /**\n   * Convert a USD amount to AVAX wei using live Chainlink prices.\n   */\n  async convertUsdToAvax(usdAmount: number): Promise<bigint> {\n    const avaxPrice = await this.getAvaxPriceUSD();\n    if (avaxPrice <= 0) throw new Error('Invalid AVAX price from Chainlink');\n    const avaxAmount = usdAmount / avaxPrice;\n    return ethers.parseEther(avaxAmount.toFixed(18));\n  }\n\n  /**\n   * Convert AVAX wei to USD using live Chainlink prices.\n   */\n  async convertAvaxToUsd(avaxWei: bigint): Promise<number> {\n    const avaxPrice = await this.getAvaxPriceUSD();\n    return Number(ethers.formatEther(avaxWei)) * avaxPrice;\n  }\n\n  // ========================================================================\n  // ICM Spoke Queries\n  // ========================================================================\n\n  /**\n   * Verify a session is valid on the ICM Spoke (cross-L1 verification).\n   */\n  async verifyICMSession(\n    sessionKeyHash: string,\n    amount: bigint,\n  ): Promise<{ valid: boolean; remainingBudget: bigint }> {\n    if (!this.icmSpokeAddress) {\n      throw new Error('ICM Spoke address not configured');\n    }\n    const spoke = new ethers.Contract(this.icmSpokeAddress, ICM_SPOKE_ABI, this.avaxProvider);\n    const [valid, remainingBudget] = await spoke.verifySession(sessionKeyHash, amount);\n    return { valid, remainingBudget: BigInt(remainingBudget) };\n  }\n\n  /**\n   * Get status of the ICM Spoke (paused, message count, session count).\n   */\n  async getICMSpokeStatus(): Promise<{\n    paused: boolean;\n    totalMessages: bigint;\n    totalSessions: bigint;\n    totalPayments: bigint;\n  }> {\n    if (!this.icmSpokeAddress) {\n      throw new Error('ICM Spoke address not configured');\n    }\n    const spoke = new ethers.Contract(this.icmSpokeAddress, ICM_SPOKE_ABI, this.avaxProvider);\n    const [paused, totalMessages, totalSessions, totalPayments] = await spoke.getStatus();\n    return {\n      paused,\n      totalMessages: BigInt(totalMessages),\n      totalSessions: BigInt(totalSessions),\n      totalPayments: BigInt(totalPayments),\n    };\n  }\n\n  /**\n   * Check if a key is authorized for an identity on the ICM Spoke.\n   */\n  async isKeyAuthorizedOnSpoke(identityKeyHash: string, keyHash: string): Promise<boolean> {\n    if (!this.icmSpokeAddress) return false;\n    const spoke = new ethers.Contract(this.icmSpokeAddress, ICM_SPOKE_ABI, this.avaxProvider);\n    return spoke.isKeyAuthorized(identityKeyHash, keyHash);\n  }\n\n  // ========================================================================\n  // ICM-Aware Routing\n  // ========================================================================\n\n  /**\n   * Determine whether a cross-chain message should use Teleporter (ICM) or Wormhole.\n   *\n   * Rule: If the target chain is within the Avalanche ecosystem (C-Chain ID or\n   * an Avalanche L1), use ICM/Teleporter for lower latency and no guardian overhead.\n   * Otherwise, fall back to Wormhole VAAs for cross-ecosystem messaging.\n   *\n   * @param targetWormholeChainId Wormhole chain ID of the destination\n   * @returns 'icm' | 'wormhole'\n   */\n  getRoutingStrategy(targetWormholeChainId: number): 'icm' | 'wormhole' {\n    // Avalanche C-Chain Wormhole chain ID is 6 on both mainnet and testnet.\n    // For Avalanche L1s routed over Teleporter, they share the same ecosystem.\n    // Currently only the C-Chain (6) is a known ICM target.\n    const avalancheEcosystemChainIds = new Set([6]);\n    return avalancheEcosystemChainIds.has(targetWormholeChainId) ? 'icm' : 'wormhole';\n  }\n\n  // ========================================================================\n  // Accessors\n  // ========================================================================\n\n  getP256VerifierAddress(): string {\n    return this.p256VerifierAddress;\n  }\n\n  getICMSpokeAddress(): string {\n    return this.icmSpokeAddress;\n  }\n\n  getChainlinkAvaxUsdFeed(): string {\n    return this.chainlinkAvaxUsdFeed;\n  }\n\n  // ========================================================================\n  // Private Helpers\n  // ========================================================================\n\n  private async _getChainlinkPrice(feedAddress: string, cacheKey: string): Promise<number> {\n    if (!feedAddress) throw new Error(`Chainlink feed not configured for ${cacheKey}`);\n\n    const cached = this.priceCache.get(cacheKey);\n    if (cached && Date.now() - cached.timestamp < this.CACHE_TTL_MS) {\n      return cached.price;\n    }\n\n    const aggregator = new ethers.Contract(feedAddress, CHAINLINK_AGGREGATOR_ABI, this.avaxProvider);\n    const [, answer] = await aggregator.latestRoundData();\n    const decimals = await aggregator.decimals();\n    const price = Number(answer) / 10 ** Number(decimals);\n\n    this.priceCache.set(cacheKey, { price, timestamp: Date.now() });\n    return price;\n  }\n}\n"],"mappings":";;;;;AA4BA,SAAS,cAAc;AAyBvB,IAAM,oBAAoB;AAG1B,IAAM,2BAA2B;AAAA,EAC/B;AAAA,EACA;AACF;AAGA,IAAM,gBAAgB;AAAA,EACpB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,IAAM,oBAAoB;AAAA,EACxB;AAAA,EACA;AACF;AAeO,IAAM,kBAAN,cAA8B,UAAU;AAAA,EACrC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAGA,aAAgE,oBAAI,IAAI;AAAA,EAC/D,eAAe;AAAA;AAAA,EAEhC,YAAY,QAA+B;AACzC,UAAM,MAAM;AACZ,SAAK,eAAe,IAAI,OAAO,gBAAgB,OAAO,MAAM;AAC5D,SAAK,sBAAsB,OAAO,uBAAuB;AACzD,SAAK,kBAAkB,OAAO,mBAAmB;AACjD,SAAK,uBAAuB,OAAO,wBAAwB;AAC3D,SAAK,uBAAuB,OAAO,wBAAwB;AAC3D,SAAK,uBAAuB,OAAO,wBAAwB;AAAA,EAC7D;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,MAAM,oBAAsC;AAE1C,QAAI,KAAK,qBAAqB;AAC5B,UAAI;AACF,cAAM,WAAW,IAAI,OAAO;AAAA,UAC1B,KAAK;AAAA,UACL;AAAA,UACA,KAAK;AAAA,QACP;AACA,eAAO,MAAM,SAAS,sBAAsB;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