@gvnrdao/dh-lit-actions 0.0.331 → 0.0.333

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.
Files changed (44) hide show
  1. package/dist/a_dev_address-probe-signer.meta.json +1 -1
  2. package/dist/a_dev_address-probe.meta.json +1 -1
  3. package/dist/a_dev_always-signer.meta.json +1 -1
  4. package/dist/a_dev_authorization-dummy-b.meta.json +1 -1
  5. package/dist/a_dev_authorization-dummy.meta.json +1 -1
  6. package/dist/a_dev_ethers-version-probe.meta.json +1 -1
  7. package/dist/a_dev_process-payment-sign-only.meta.json +1 -1
  8. package/dist/agent-module-executor.meta.json +1 -1
  9. package/dist/backing-attestation.meta.json +3 -3
  10. package/dist/btc-address-balance.meta.json +1 -1
  11. package/dist/btc-provider-probe.meta.json +1 -1
  12. package/dist/btc-transaction-signer.meta.json +1 -1
  13. package/dist/btc-utxo-invalidator.meta.json +1 -1
  14. package/dist/btc-withdrawal.meta.json +1 -1
  15. package/dist/carry-collateral-attestation.action.js +1 -1
  16. package/dist/carry-collateral-attestation.hash +1 -1
  17. package/dist/carry-collateral-attestation.meta.json +5 -5
  18. package/dist/carry-repay-validator.action.js +1 -0
  19. package/dist/carry-repay-validator.hash +1 -0
  20. package/dist/carry-repay-validator.meta.json +9 -0
  21. package/dist/encrypt-parameter.meta.json +1 -1
  22. package/dist/extend-position-validator.meta.json +1 -1
  23. package/dist/liquidation-validator.meta.json +1 -1
  24. package/dist/loan-vault-btc-balance.meta.json +1 -1
  25. package/dist/pkp-validator.meta.json +1 -1
  26. package/dist/price-oracle.meta.json +1 -1
  27. package/dist/process-payment-validator.meta.json +1 -1
  28. package/dist/stale-spend-recovery-validator.meta.json +1 -1
  29. package/dist/ucd-mint-validator.meta.json +1 -1
  30. package/package.json +1 -1
  31. package/pkg-dist/pkg-src/constants/chunks/lit-actions-registry.d.ts.map +1 -1
  32. package/pkg-dist/pkg-src/index.js +34 -21
  33. package/pkg-dist/pkg-src/index.js.map +3 -3
  34. package/pkg-dist/pkg-src/interfaces/chunks/diamond-hands-lit-actions.i.d.ts +2 -2
  35. package/pkg-dist/pkg-src/interfaces/chunks/diamond-hands-lit-actions.i.d.ts.map +1 -1
  36. package/pkg-dist/src/constants/chunks/carry.d.ts +5 -21
  37. package/pkg-dist/src/constants/chunks/carry.d.ts.map +1 -1
  38. package/pkg-dist/src/modules/carry-attestation.module.d.ts +73 -50
  39. package/pkg-dist/src/modules/carry-attestation.module.d.ts.map +1 -1
  40. package/pkg-dist/src/modules/carry-repay.module.d.ts +59 -0
  41. package/pkg-dist/src/modules/carry-repay.module.d.ts.map +1 -0
  42. package/dist/carry-funding-attestation.action.js +0 -1
  43. package/dist/carry-funding-attestation.hash +0 -1
  44. package/dist/carry-funding-attestation.meta.json +0 -9
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../../pkg-src/utils/chunks/debug-logger.ts", "../../pkg-src/utils/chunks/session-signature-cache.ts", "../../pkg-src/index.ts", "../../../../diamond-hands/lit-actions/node_modules/base-x/src/esm/index.js", "../../../../diamond-hands/lit-actions/node_modules/bs58/src/esm/index.js", "../../pkg-src/utils/chunks/cid-utils.ts", "../../pkg-src/constants/chunks/lit-actions-registry.ts", "../../pkg-src/utils/chunks/lit-action-helpers.ts", "../../pkg-src/utils/chunks/pkp-setup.ts", "../../pkg-src/utils/chunks/connection-helpers.ts", "../../pkg-src/utils/chunks/error-classification.ts", "../../pkg-src/utils/index.ts", "../../pkg-src/executors/chunks/vault-snapshot-executor.ts", "../../src/constants/chunks/liquidation.ts", "../../src/constants/chunks/decimals.ts", "../../src/constants/chunks/bitcoin.ts", "../../src/constants/chunks/quantum-time.ts", "../../src/constants/chunks/time.ts", "../../src/constants/chunks/lit-action-runtime.ts", "../../src/constants/chunks/deployment-addresses.ts", "../../src/constants/message-hash-domains.ts", "../../src/constants/borrower-authorization-types.ts", "../../src/constants/chunks/bitcoin-network-config.ts", "../../src/modules/business-rules-math.module.ts", "../../src/modules/evm-rpc.ts", "../../src/modules/protocol-parameters.module.ts", "../../src/modules/vault-address.ts", "../../src/modules/vault-snapshot.ts", "../../src/modules/lit-action-debug.ts", "../../src/modules/lit-action-logger.module.ts", "../../src/modules/lit-global-bootstrap.ts", "../../src/modules/bitcoin-provider-auth.ts", "../../src/modules/bitcoin-data-provider.module.ts", "../../src/modules/price-oracle.module.ts", "../../src/modules/vault-balance-consensus.module.ts", "../../src/modules/vault-balance.module.ts", "../../src/modules/chain-policy.ts", "../../pkg-src/executors/chunks/price-oracle-executor.ts", "../../pkg-src/executors/index.ts", "../../src/constants/btc-spend-request-types.ts"],
4
- "sourcesContent": ["/**\n * Enhanced Debug Logger for LIT Protocol Operations\n * Provides detailed logging for debugging network and protocol issues\n */\n\nexport enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3,\n TRACE = 4\n}\n\nexport interface DebugConfig {\n level: LogLevel;\n enableTimestamps: boolean;\n enablePerformanceMetrics: boolean;\n enableRequestLogging: boolean;\n enableNetworkMetrics: boolean;\n}\n\nexport const DEFAULT_DEBUG_CONFIG: DebugConfig = {\n level: LogLevel.INFO,\n enableTimestamps: true,\n enablePerformanceMetrics: true,\n enableRequestLogging: true,\n enableNetworkMetrics: true\n};\n\nlet debugConfig: DebugConfig = { ...DEFAULT_DEBUG_CONFIG };\n\n/**\n * Configure debug logging\n */\nexport function configureDebugLogging(config: Partial<DebugConfig>): void {\n debugConfig = { ...debugConfig, ...config };\n}\n\n/**\n * Get current timestamp string\n */\nfunction getTimestamp(): string {\n return new Date().toISOString();\n}\n\n/**\n * Format log message with metadata\n */\nfunction formatMessage(level: string, component: string, message: string, metadata?: any): string {\n const timestamp = debugConfig.enableTimestamps ? `[${getTimestamp()}] ` : '';\n const metadataStr = metadata ? ` ${JSON.stringify(metadata)}` : '';\n return `${timestamp}[${level}] [${component}] ${message}${metadataStr}`;\n}\n\n/**\n * Performance metrics tracker\n */\nexport class PerformanceTracker {\n private startTime: number;\n private markers: Map<string, number> = new Map();\n\n constructor(private operationName: string) {\n this.startTime = Date.now();\n this.log('PERF', `Started: ${operationName}`);\n }\n\n mark(label: string): void {\n const elapsed = Date.now() - this.startTime;\n this.markers.set(label, elapsed);\n this.log('PERF', `${this.operationName} - ${label}: ${elapsed}ms`);\n }\n\n end(success: boolean = true): number {\n const totalTime = Date.now() - this.startTime;\n const status = success ? 'SUCCESS' : 'FAILED';\n this.log('PERF', `${this.operationName} - ${status}: ${totalTime}ms`);\n\n if (debugConfig.enablePerformanceMetrics && this.markers.size > 0) {\n console.log(`\uD83D\uDCCA Performance Breakdown for ${this.operationName}:`);\n for (const [label, time] of this.markers) {\n console.log(` ${label}: ${time}ms`);\n }\n console.log(` Total: ${totalTime}ms`);\n }\n\n return totalTime;\n }\n\n private log(level: string, message: string): void {\n if (debugConfig.enablePerformanceMetrics) {\n console.log(formatMessage(level, 'PERFORMANCE', message));\n }\n }\n}\n\n/**\n * Network metrics collector\n */\nexport interface NetworkMetrics {\n requestCount: number;\n successCount: number;\n failureCount: number;\n averageLatency: number;\n lastError?: string;\n startTime: number;\n}\n\nclass NetworkMetricsCollector {\n private metrics: Map<string, NetworkMetrics> = new Map();\n\n getMetrics(operation: string): NetworkMetrics {\n if (!this.metrics.has(operation)) {\n this.metrics.set(operation, {\n requestCount: 0,\n successCount: 0,\n failureCount: 0,\n averageLatency: 0,\n startTime: Date.now()\n });\n }\n return this.metrics.get(operation)!;\n }\n\n recordRequest(operation: string, success: boolean, latency: number, error?: string): void {\n const metrics = this.getMetrics(operation);\n metrics.requestCount++;\n\n if (success) {\n metrics.successCount++;\n // Update average latency\n metrics.averageLatency = (metrics.averageLatency * (metrics.successCount - 1) + latency) / metrics.successCount;\n } else {\n metrics.failureCount++;\n if (error) metrics.lastError = error;\n }\n\n if (debugConfig.enableNetworkMetrics) {\n const successRate = ((metrics.successCount / metrics.requestCount) * 100).toFixed(1);\n debugLog('NETWORK', `${operation} - Success: ${success}, Latency: ${latency}ms, Success Rate: ${successRate}%`);\n }\n }\n\n printSummary(): void {\n if (!debugConfig.enableNetworkMetrics) return;\n\n console.log('\\n\uD83D\uDCC8 Network Metrics Summary:');\n for (const [operation, metrics] of this.metrics) {\n const successRate = ((metrics.successCount / metrics.requestCount) * 100).toFixed(1);\n const runtime = Date.now() - metrics.startTime;\n console.log(` ${operation}:`);\n console.log(` Requests: ${metrics.requestCount}`);\n console.log(` Success Rate: ${successRate}%`);\n console.log(` Avg Latency: ${metrics.averageLatency.toFixed(0)}ms`);\n console.log(` Runtime: ${runtime}ms`);\n if (metrics.lastError) {\n console.log(` Last Error: ${metrics.lastError}`);\n }\n }\n }\n}\n\nexport const networkMetrics = new NetworkMetricsCollector();\n\n/**\n * Debug logging functions\n */\nexport function debugError(component: string, message: string, metadata?: any): void {\n if (debugConfig.level >= LogLevel.ERROR) {\n console.error(formatMessage('ERROR', component, message, metadata));\n }\n}\n\nexport function debugWarn(component: string, message: string, metadata?: any): void {\n if (debugConfig.level >= LogLevel.WARN) {\n console.warn(formatMessage('WARN', component, message, metadata));\n }\n}\n\nexport function debugInfo(component: string, message: string, metadata?: any): void {\n if (debugConfig.level >= LogLevel.INFO) {\n console.log(formatMessage('INFO', component, message, metadata));\n }\n}\n\nexport function debugLog(component: string, message: string, metadata?: any): void {\n if (debugConfig.level >= LogLevel.DEBUG) {\n console.log(formatMessage('DEBUG', component, message, metadata));\n }\n}\n\nexport function debugTrace(component: string, message: string, metadata?: any): void {\n if (debugConfig.level >= LogLevel.TRACE) {\n console.log(formatMessage('TRACE', component, message, metadata));\n }\n}\n\n/**\n * Request/Response logger for LIT Protocol operations\n */\nexport function logRequest(component: string, operation: string, params: any): void {\n if (!debugConfig.enableRequestLogging) return;\n\n debugLog(component, `\uD83D\uDD04 Request: ${operation}`, {\n operation,\n params: JSON.stringify(params, null, 2)\n });\n}\n\nexport function logResponse(component: string, operation: string, response: any, duration: number): void {\n if (!debugConfig.enableRequestLogging) return;\n\n debugLog(component, `\u2705 Response: ${operation} (${duration}ms)`, {\n operation,\n duration,\n response: typeof response === 'object' ? JSON.stringify(response, null, 2) : response\n });\n}\n\nexport function logError(component: string, operation: string, error: any, duration?: number): void {\n const durationStr = duration ? ` (${duration}ms)` : '';\n debugError(component, `\u274C Error: ${operation}${durationStr}`, {\n operation,\n duration,\n error: error?.message || error?.toString() || 'Unknown error',\n stack: error?.stack\n });\n}\n\n/**\n * Network connection logger\n */\nexport function logConnectionAttempt(network: string, attempt: number, maxAttempts: number): void {\n debugInfo('CONNECTION', `\uD83D\uDD17 Connecting to ${network} (attempt ${attempt}/${maxAttempts})`);\n}\n\nexport function logConnectionSuccess(network: string, latency: number): void {\n debugInfo('CONNECTION', `\u2705 Connected to ${network} (${latency}ms)`);\n networkMetrics.recordRequest(`connection-${network}`, true, latency);\n}\n\nexport function logConnectionFailure(network: string, error: string, attempt: number): void {\n debugError('CONNECTION', `\u274C Connection failed to ${network} (attempt ${attempt})`, { error });\n networkMetrics.recordRequest(`connection-${network}`, false, 0, error);\n}\n\n/**\n * PKP operation logger\n */\nexport function logPkpOperation(operation: string, pkpId?: string, details?: any): void {\n const pkpStr = pkpId ? ` (PKP: ${pkpId.slice(0, 8)}...)` : '';\n debugInfo('PKP', `\uD83D\uDD11 ${operation}${pkpStr}`, details);\n}\n\n/**\n * Session signature logger\n */\nexport function logSessionSignatures(count: number, expiration: string): void {\n debugInfo('SESSION', `\uD83D\uDD10 Generated ${count} session signatures (expires: ${expiration})`);\n}\n\n/**\n * LIT Action execution logger\n */\nexport function logLitActionExecution(cid: string, params: any): void {\n debugInfo('LIT_ACTION', `\u26A1 Executing LIT Action: ${cid}`, {\n cid,\n params\n });\n}\n\nexport function logLitActionResult(cid: string, success: boolean, duration: number, result?: any): void {\n const status = success ? '\u2705' : '\u274C';\n debugInfo('LIT_ACTION', `${status} LIT Action completed: ${cid} (${duration}ms)`, {\n cid,\n success,\n duration,\n result: success && result ? JSON.stringify(result, null, 2) : undefined\n });\n}\n\n/**\n * Test lifecycle logger\n */\nexport function logTestStart(testName: string): PerformanceTracker {\n debugInfo('TEST', `\uD83E\uDDEA Starting test: ${testName}`);\n return new PerformanceTracker(testName);\n}\n\nexport function logTestEnd(testName: string, success: boolean, duration: number): void {\n const status = success ? '\u2705' : '\u274C';\n debugInfo('TEST', `${status} Test completed: ${testName} (${duration}ms)`);\n networkMetrics.printSummary();\n}", "/**\n * Session Signature Cache for PKP Operations\n * Provides intelligent caching of session signatures to avoid regeneration\n */\n\nimport { debugInfo, debugWarn, debugLog } from './debug-logger';\n\n/**\n * Cache entry for session signatures\n */\ninterface SessionSignatureCacheEntry {\n sessionSigs: any;\n expiration: Date;\n pkpTokenId: string;\n litActionCid: string;\n signerAddress: string;\n network: string;\n createdAt: Date;\n}\n\n/**\n * Session signature cache configuration\n */\nexport interface SessionSignatureCacheConfig {\n maxEntries: number;\n bufferTimeMs: number; // Time before expiration to consider entry stale\n enableLogging: boolean;\n}\n\nexport const DEFAULT_CACHE_CONFIG: SessionSignatureCacheConfig = {\n maxEntries: 50,\n bufferTimeMs: 60000, // 1 minute buffer before expiration\n enableLogging: true\n};\n\n/**\n * In-memory session signature cache\n */\nclass SessionSignatureCache {\n private cache = new Map<string, SessionSignatureCacheEntry>();\n private config: SessionSignatureCacheConfig;\n\n constructor(config: Partial<SessionSignatureCacheConfig> = {}) {\n this.config = { ...DEFAULT_CACHE_CONFIG, ...config };\n }\n\n /**\n * Generate cache key from PKP and context\n */\n private generateCacheKey(\n pkpTokenId: string,\n litActionCid: string,\n signerAddress: string,\n network: string\n ): string {\n return `${signerAddress}-${network}-${pkpTokenId}-${litActionCid}`;\n }\n\n /**\n * Check if cache entry is still valid\n */\n private isEntryValid(entry: SessionSignatureCacheEntry): boolean {\n const now = new Date();\n const expirationWithBuffer = new Date(\n entry.expiration.getTime() - this.config.bufferTimeMs\n );\n\n return now < expirationWithBuffer;\n }\n\n /**\n * Clean expired entries from cache\n */\n private cleanExpiredEntries(): void {\n const now = new Date();\n let cleanedCount = 0;\n\n for (const [key, entry] of this.cache.entries()) {\n if (now >= entry.expiration) {\n this.cache.delete(key);\n cleanedCount++;\n }\n }\n\n if (cleanedCount > 0 && this.config.enableLogging) {\n debugInfo('CACHE', `\uD83E\uDDF9 Cleaned ${cleanedCount} expired session signature entries`);\n }\n }\n\n /**\n * Enforce cache size limits\n */\n private enforceCacheSize(): void {\n if (this.cache.size <= this.config.maxEntries) {\n return;\n }\n\n // Sort entries by creation time and remove oldest\n const entries = Array.from(this.cache.entries())\n .sort(([, a], [, b]) => a.createdAt.getTime() - b.createdAt.getTime());\n\n const toRemove = entries.slice(0, this.cache.size - this.config.maxEntries);\n\n for (const [key] of toRemove) {\n this.cache.delete(key);\n }\n\n if (this.config.enableLogging) {\n debugInfo('CACHE', `\uD83D\uDCE6 Removed ${toRemove.length} oldest cache entries to maintain size limit`);\n }\n }\n\n /**\n * Get cached session signatures if valid\n */\n get(\n pkpTokenId: string,\n litActionCid: string,\n signerAddress: string,\n network: string\n ): any | null {\n this.cleanExpiredEntries();\n\n const cacheKey = this.generateCacheKey(pkpTokenId, litActionCid, signerAddress, network);\n const entry = this.cache.get(cacheKey);\n\n if (!entry) {\n if (this.config.enableLogging) {\n debugLog('CACHE', `\u274C Session signatures cache miss: ${cacheKey}`);\n }\n return null;\n }\n\n if (!this.isEntryValid(entry)) {\n this.cache.delete(cacheKey);\n if (this.config.enableLogging) {\n debugWarn('CACHE', `\u23F0 Session signatures expired: ${cacheKey}`);\n }\n return null;\n }\n\n if (this.config.enableLogging) {\n const timeUntilExpiry = entry.expiration.getTime() - Date.now();\n debugInfo('CACHE', `\u2705 Session signatures cache hit: ${cacheKey} (expires in ${Math.round(timeUntilExpiry/1000)}s)`);\n }\n\n return entry.sessionSigs;\n }\n\n /**\n * Cache session signatures\n */\n set(\n pkpTokenId: string,\n litActionCid: string,\n signerAddress: string,\n network: string,\n sessionSigs: any,\n expiration: Date\n ): void {\n const cacheKey = this.generateCacheKey(pkpTokenId, litActionCid, signerAddress, network);\n\n const entry: SessionSignatureCacheEntry = {\n sessionSigs,\n expiration,\n pkpTokenId,\n litActionCid,\n signerAddress,\n network,\n createdAt: new Date()\n };\n\n this.cache.set(cacheKey, entry);\n\n if (this.config.enableLogging) {\n const timeUntilExpiry = expiration.getTime() - Date.now();\n debugInfo('CACHE', `\uD83D\uDCBE Cached session signatures: ${cacheKey} (expires in ${Math.round(timeUntilExpiry/1000)}s)`);\n }\n\n this.enforceCacheSize();\n }\n\n /**\n * Clear all cached session signatures\n */\n clear(): void {\n const size = this.cache.size;\n this.cache.clear();\n\n if (this.config.enableLogging) {\n debugInfo('CACHE', `\uD83D\uDDD1\uFE0F Cleared ${size} cached session signature entries`);\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats() {\n this.cleanExpiredEntries();\n\n return {\n size: this.cache.size,\n maxEntries: this.config.maxEntries,\n utilizationPercent: Math.round((this.cache.size / this.config.maxEntries) * 100)\n };\n }\n\n /**\n * Remove specific cache entry\n */\n delete(\n pkpTokenId: string,\n litActionCid: string,\n signerAddress: string,\n network: string\n ): boolean {\n const cacheKey = this.generateCacheKey(pkpTokenId, litActionCid, signerAddress, network);\n const deleted = this.cache.delete(cacheKey);\n\n if (deleted && this.config.enableLogging) {\n debugInfo('CACHE', `\uD83D\uDDD1\uFE0F Removed session signatures from cache: ${cacheKey}`);\n }\n\n return deleted;\n }\n}\n\n// Global session signature cache instance\nexport const sessionSignatureCache = new SessionSignatureCache();\n\n/**\n * Enhanced session signature generator with caching\n */\nexport async function generateSessionSignaturesWithCache(\n litNodeClient: any,\n sessionConfig: any,\n pkpTokenId: string,\n litActionCid: string,\n signerAddress: string,\n network: string = 'chipotle'\n): Promise<any> {\n // Check cache first\n const cached = sessionSignatureCache.get(pkpTokenId, litActionCid, signerAddress, network);\n if (cached) {\n return cached;\n }\n\n // Generate new session signatures\n debugInfo('CACHE', '\uD83D\uDD10 Generating new session signatures (cache miss)...');\n const sessionSigs = await litNodeClient.getSessionSigs(sessionConfig);\n\n // Extract expiration from config\n const expiration = new Date(sessionConfig.expiration);\n\n // Cache the result\n sessionSignatureCache.set(pkpTokenId, litActionCid, signerAddress, network, sessionSigs, expiration);\n\n const sigCount = Object.keys(sessionSigs).length;\n debugInfo('CACHE', `\u2705 Generated and cached ${sigCount} session signatures`);\n\n return sessionSigs;\n}\n\n/**\n * Configure the global session signature cache\n */\nexport function configureSessionSignatureCache(config: Partial<SessionSignatureCacheConfig>): void {\n Object.assign(sessionSignatureCache['config'], config);\n}\n\n/**\n * Clear the global session signature cache\n */\nexport function clearSessionSignatureCache(): void {\n sessionSignatureCache.clear();\n}\n\n/**\n * Get session signature cache statistics\n */\nexport function getSessionSignatureCacheStats() {\n return sessionSignatureCache.getStats();\n}", "/**\n * dh-lit-actions Package\n * Diamond Hands Protocol LIT Actions Registry\n *\n * This package exports deployed LIT Action CIDs and metadata\n * for consumption by the Diamond Hands SDK and other applications.\n */\n\n// Export interfaces\nexport * from \"./interfaces\";\n\n// Export constants from registry\nexport * from \"./constants/chunks/lit-actions-registry\";\n\n// Export utilities\nexport * from \"./utils\";\n\n// Export NOLA executors\nexport * from \"./executors\";\n\n/**\n * Borrower authorization EIP-712 types \u2014 the ONE definition the SDK and the\n * LIT Actions share.\n *\n * Exported from `src/` rather than re-declared here: the SDK signs these\n * messages and `modules/authorization.module.ts` verifies them, so a second\n * copy would be a second digest waiting to disagree. `tsconfig.pkg.json`\n * already compiles `src/constants/**`, and the module is plain constants with\n * no LIT-runtime dependency, so bundling it into the package costs nothing.\n *\n * Named exports, not `export *`: the sibling `message-hash-domains` module is\n * NOT re-exported, because its action tags are LIT-internal and would widen\n * this package's public surface for no consumer.\n */\nexport {\n type BorrowerAuthorizationField,\n type BorrowerAuthorizationDomain,\n type BorrowerAuthorizationPrimaryType,\n BORROWER_AUTHORIZATION_PRIMARY_TYPES,\n BORROWER_AUTHORIZATION_FIELDS,\n BORROWER_AUTHORIZATION_ENCODE_TYPES,\n borrowerAuthorizationTypes,\n buildBorrowerAuthorizationDomain,\n} from \"../src/constants/borrower-authorization-types\";\n\n/**\n * EIP-712 types for the BTC-custody owner authorizations (execute and\n * invalidate; `contracts/docs/EIP712_DOMAIN_SPEC.md` \u00A73.8). Same named-export\n * rule as above.\n */\nexport {\n type BtcSpendRequestField,\n type BtcSpendRequestDomain,\n type BtcSpendRequestPrimaryType,\n BTC_SPEND_REQUEST_PRIMARY_TYPES,\n BTC_SPEND_REQUEST_FIELDS,\n BTC_SPEND_REQUEST_ENCODE_TYPES,\n btcSpendRequestTypes,\n buildBtcSpendRequestDomain,\n canonicalBtcTxid,\n} from \"../src/constants/btc-spend-request-types\";\n\n// Default export\nexport { DH_LIT_ACTIONS_CHIPOTLE, CHIPOTLE_DEPLOYMENTS } from \"./constants/chunks/lit-actions-registry\";\n", "// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n const BASE_MAP = new Uint8Array(256)\n for (let j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (let i = 0; i < ALPHABET.length; i++) {\n const x = ALPHABET.charAt(i)\n const xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n const BASE = ALPHABET.length\n const LEADER = ALPHABET.charAt(0)\n const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n // eslint-disable-next-line no-empty\n if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n let zeroes = 0\n let length = 0\n let pbegin = 0\n const pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n const b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n let carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n let i = 0\n for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n let it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n let str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n let psz = 0\n // Skip and count leading '1's.\n let zeroes = 0\n let length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n const b256 = new Uint8Array(size)\n // Process the characters.\n while (psz < source.length) {\n // Find code of next character\n const charCode = source.charCodeAt(psz)\n // Base map can not be indexed using char code\n if (charCode > 255) { return }\n // Decode character\n let carry = BASE_MAP[charCode]\n // Invalid character\n if (carry === 255) { return }\n let i = 0\n for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n let it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n const vch = new Uint8Array(zeroes + (size - it4))\n let j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n const buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode,\n decodeUnsafe,\n decode\n }\n}\nexport default base\n", "import basex from 'base-x';\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport default basex(ALPHABET);\n", "import bs58 from \"bs58\";\n\n/**\n * Convert IPFS CID from base58 to hex format for contract authorization\n * This matches the format expected by LIT Protocol smart contracts\n */\nexport function cidToHex(cid: string): string {\n try {\n if (cid.startsWith(\"Qm\")) {\n // v0 CID - convert base58 to hex\n const bytes = bs58.decode(cid);\n return \"0x\" + Buffer.from(bytes).toString(\"hex\");\n } else if (cid.startsWith(\"0x\")) {\n // Already in hex format\n return cid;\n } else {\n // Unknown format - FAIL FAST\n throw new Error(`Unsupported CID format: ${cid}. Only CIDv0 (Qm...) and hex (0x...) formats are supported.`);\n }\n } catch (error) {\n if (error instanceof Error && error.message.includes('Unsupported CID format')) {\n // Re-throw our own errors\n throw error;\n }\n // bs58 decode or other conversion errors\n throw new Error(`Failed to convert CID ${cid} to hex: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n", "import { DiamondHandsLitActions } from \"../../interfaces\";\nimport { cidToHex } from \"../../utils/chunks/cid-utils\";\n\nexport type SupportedLitNetwork = \"chipotle\";\n\n/**\n * Diamond Hands LIT Actions Registry \u2014 Chipotle (new REST API)\n * Contains all deployed LIT Actions with their IPFS CIDs and PKP metadata\n */\nexport const DH_LIT_ACTIONS_CHIPOTLE: Partial<DiamondHandsLitActions> = {\n authorizationDummy: {\n cid: \"QmeeYQ3zfDPKJQg3JG5p4TpxKHEnDRLXZbT79KxzwC3xjc\",\n authorizedCidHex: cidToHex(\n \"QmeeYQ3zfDPKJQg3JG5p4TpxKHEnDRLXZbT79KxzwC3xjc\",\n ),\n name: \"Authorization Dummy\",\n description: \"Production Authorization Dummy\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1780400482915,\n size: 2216,\n hash: \"5f862b4635f2e04b033c4ff652addc017c3c0a325f81309a24d701c90e0bc950\",\n },\n authorizationDummyB: {\n cid: \"QmQHKDp5GDBp2XoStcm3SE6EvdJpK5RJ5ij4ZkQFn6dcMU\",\n authorizedCidHex: cidToHex(\n \"QmQHKDp5GDBp2XoStcm3SE6EvdJpK5RJ5ij4ZkQFn6dcMU\",\n ),\n name: \"Authorization Dummy B\",\n description: \"Production Authorization Dummy B\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1780400494581,\n size: 1885,\n hash: \"d6eb8665fa4f1fe19b6a2bc81fbf729af68a1daf30117f40e37705381978a7ce\",\n },\n pkpValidator: {\n cid: \"QmRfPvd7R7MoEnShds28Y4ovdV8RoDCGkYWTcF1JHZVTQa\",\n authorizedCidHex: cidToHex(\n \"QmRfPvd7R7MoEnShds28Y4ovdV8RoDCGkYWTcF1JHZVTQa\",\n ),\n name: \"Pkp Validator\",\n description: \"Production Pkp Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1784569687492,\n size: 4140,\n hash: \"4c0d65bf1f33cdac22a78fd8c4764319cc3fe00650e0fe7fa8a6090d9a318a7b\",\n validatorWalletAddress: \"0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c\",\n pkp: {\n publicKey:\n \"0x04ec0e3acc40884e3f366ca469d08899eb640ad5259fa196b0238075086208a9f8732a3175704f35f0bcc28e07406cfb24c254efd1e7355640577330f0d2dd755f\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n btcTransactionSigner: {\n cid: \"QmUR2dSs4H6ajpk577PiDYA2cW6pucrEufWCrxhoKBajxi\",\n authorizedCidHex: cidToHex(\n \"QmUR2dSs4H6ajpk577PiDYA2cW6pucrEufWCrxhoKBajxi\",\n ),\n name: \"Btc Transaction Signer\",\n description: \"Production Btc Transaction Signer\",\n version: \"1.3.2\",\n deployed: true,\n deployedAt: 1793188476723,\n size: 78341,\n hash: \"a8ebd6426c4e34c0d67457ce7e6b682ebb6619f75067a3a1895f6028a4fede34\",\n },\n ucdMintValidator: {\n cid: \"QmXr4PBqadVon2HrkmSrHwdXGvx1kaNNdVJGqBZ5wjmYFw\",\n authorizedCidHex: cidToHex(\n \"QmXr4PBqadVon2HrkmSrHwdXGvx1kaNNdVJGqBZ5wjmYFw\",\n ),\n name: \"Ucd Mint Validator\",\n description: \"Production Ucd Mint Validator\",\n version: \"1.4.5\",\n deployed: true,\n deployedAt: 1793188485424,\n size: 92150,\n hash: \"91b74714f71acf01875ffb81b829ada1fe0a3b3a94d3ad9cd6ea37c17a2c6193\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x041ab17cd91fc5c0b761eea6092d032807561b621b82c488826776e04a9158d61ba64d809a4729f0501289d980732cb06d8dfd06999dd9c8efd2f495dad78b31bb\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n processPaymentValidator: {\n cid: \"QmcJcjahQStMB4Ggy5d47HoCG1X2HUFcRfMRbcU33Pc4bz\",\n authorizedCidHex: cidToHex(\n \"QmcJcjahQStMB4Ggy5d47HoCG1X2HUFcRfMRbcU33Pc4bz\",\n ),\n name: \"Process Payment Validator\",\n description: \"Production Process Payment Validator\",\n version: \"1.3.5\",\n deployed: true,\n deployedAt: 1793188494032,\n size: 87803,\n hash: \"7e6989fc31fdb53d343ac6a5372844d7b58ada2ded780c5d01ffa5e2163cba6c\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x04cfccb9b6c7addc79469c0e9fafebef4c70801302c62cdb26b610723a9b8527d23f98a40158c7340d83fd0e62d02b5ec74c12f7a86d98e8c6973b4811110f19ad\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n extendPositionValidator: {\n cid: \"QmTS9C7UjAEi1JvZu5tQHy7McRUmverXyw8v8gNjidroSg\",\n authorizedCidHex: cidToHex(\n \"QmTS9C7UjAEi1JvZu5tQHy7McRUmverXyw8v8gNjidroSg\",\n ),\n name: \"Extend Position Validator\",\n description: \"Production Extend Position Validator\",\n version: \"1.3.5\",\n deployed: true,\n deployedAt: 1793188503339,\n size: 85079,\n hash: \"384a232d8ec6605ce5404ea0737931f102dc2740b1c6dbf3230940e6159b1ca2\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x04e52338f6a0c3362800f1a94c4c8f08be5030dde0fa217388c53d1c1a4790f4443c9f2886b2d2d8f4b75a9a156e9b028011b1a1cf7648da0e556aa980ec692836\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n btcWithdrawal: {\n cid: \"QmPeTMPk8j4pYSrDPKwjUUUNXUWA4uxn2X4CKUGDMYJnFx\",\n authorizedCidHex: cidToHex(\n \"QmPeTMPk8j4pYSrDPKwjUUUNXUWA4uxn2X4CKUGDMYJnFx\",\n ),\n name: \"Btc Withdrawal\",\n description: \"Production Btc Withdrawal\",\n version: \"1.3.5\",\n deployed: true,\n deployedAt: 1793188512221,\n size: 103479,\n hash: \"1cb77be2c3999f45d609d50ec1dcd262770c01b19c4d911f4a0698a3f400e3c6\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n liquidationValidator: {\n cid: \"QmfPdvyBjKCffCmpSPg19mReBUTV7jbLyvavBNh4TrDiuA\",\n authorizedCidHex: cidToHex(\n \"QmfPdvyBjKCffCmpSPg19mReBUTV7jbLyvavBNh4TrDiuA\",\n ),\n name: \"Liquidation Validator\",\n description: \"Production Liquidation Validator\",\n version: \"1.3.5\",\n deployed: true,\n deployedAt: 1793188520927,\n size: 72776,\n hash: \"6ab50f3087181fe61a02c515a738835f76492a3557995982b5e5642150e8e391\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x041a241de58976c13e3d7ca5a18e494f7330151e3818706135d50176e78ffb673e58b11f0b67a87c73fade6c6b27d6e7a7377ea9f4c10bf31880f1d725f18cc6f8\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n priceOracle: {\n cid: \"QmZwH2JzXpLPdtUiM52PLyfuCGphz82CCs54Y6fCbzxpri\",\n authorizedCidHex: cidToHex(\n \"QmZwH2JzXpLPdtUiM52PLyfuCGphz82CCs54Y6fCbzxpri\",\n ),\n name: \"Price Oracle\",\n description: \"Production Price Oracle (Chipotle main+getPrivateKey)\",\n version: \"1.1.0\",\n deployed: true,\n deployedAt: 1781116663270,\n size: 8695,\n hash: \"ba20ade60a7fa5acd80dadfafa179c507388cfe6ce48a22a672d70b317ffcc74\",\n validatorWalletAddress: \"0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c\",\n pkp: {\n publicKey:\n \"0x043beaa1da47875601a8d6f430b1438ee2d4732eefd06e5c63a474bbdaf9e7df1797b1b951e041b627c2bf839788164825324c9cbd1e2d6f740fdd4bff69b1900b\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n loanVaultBtcBalance: {\n cid: \"QmZJQ5yKXkPc6azGg6AhXe4cyTmd617m12VMLao6KtL38T\",\n authorizedCidHex: cidToHex(\n \"QmZJQ5yKXkPc6azGg6AhXe4cyTmd617m12VMLao6KtL38T\",\n ),\n name: \"Loan Vault Btc Balance\",\n description: \"Production Loan Vault Btc Balance\",\n version: \"1.3.5\",\n deployed: true,\n deployedAt: 1793188529377,\n size: 62511,\n hash: \"225ea242dfbf74a2cd15ef83da4ecd63f0284e101f4a5182afeab731dca588d6\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n // btc-address-balance (Option B) \u2014 address-only signed total balance via\n // BitcoinProviderRegistry consensus (no positionId, no price). The deploy\n // step (deploy:chipotle:action) fills cid/authorizedCidHex/deployedAt/size/\n // hash + a DEDICATED validatorWalletAddress + pkp and flips deployed:true.\n // Requires BitcoinProviderRegistry.addAllowedCid(chainId, keccak256(utf8(cid)))\n // on each target chain (the action decrypts registry slots). No OAR entry.\n btcAddressBalance: {\n cid: \"QmbwCiwE3KjK8LZ8uML9HMjibbNtGonQGvueDEGq7NSZix\",\n authorizedCidHex: cidToHex(\n \"QmbwCiwE3KjK8LZ8uML9HMjibbNtGonQGvueDEGq7NSZix\",\n ),\n name: \"Btc Address Balance\",\n description: \"Address-only signed total BTC balance via registry consensus (no positionId, no price)\",\n version: \"0.3.3\",\n deployed: true,\n deployedAt: 1793188537801,\n size: 32072,\n hash: \"bdd1356d959916d427094b77877c6337477ae84d6a7a54e600b93e66c01b5ae5\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x0498cbb31facfa26e3ec83ccdabfe4fe341ca0282e0c3cb81da7113723b9726e1e49efa92165cc3faa66ced4454cea56dbab12267852d6525a55d7c4f128b912cd\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n alwaysSigner: {\n cid: \"Qmbf27pDimUe5GAdTYYd7poV7rHqUgctxtWd7HTui3Amig\",\n authorizedCidHex: cidToHex(\n \"Qmbf27pDimUe5GAdTYYd7poV7rHqUgctxtWd7HTui3Amig\",\n ),\n name: \"Always Signer\",\n description: \"Production Always Signer\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1780400578692,\n size: 4333,\n hash: \"1a7101c026a638f2f7cbdce02c6b8b0a55e44cc5cfc7e9440fe029b5c5be693e\",\n },\n\n ethersVersionProbe: {\n cid: \"QmYEfBWgTYc1pPH6vqazNGfnShfMKCVeiwcXGrWgehqK5A\",\n authorizedCidHex: cidToHex(\n \"QmYEfBWgTYc1pPH6vqazNGfnShfMKCVeiwcXGrWgehqK5A\",\n ),\n name: \"Ethers Version Probe\",\n description: \"Diagnostic: reports which ethers version the Chipotle runtime injects\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1778509493396,\n size: 1046,\n hash: \"03ee5be239c91c735d2c95db89a0d1b77e602cfc18af8eb64b3281fddcd90a72\",\n },\n agentModuleExecutor: {\n cid: \"QmPTQm5CtKnN3PLAitDRNQCuAeegATMWVWQbRrKiMCTz6V\",\n authorizedCidHex: cidToHex(\n \"QmPTQm5CtKnN3PLAitDRNQCuAeegATMWVWQbRrKiMCTz6V\",\n ),\n name: \"Agent Module Executor\",\n description: \"Production Agent Module Executor\",\n version: \"1.3.0\",\n deployed: true,\n deployedAt: 1792419196606,\n size: 17562,\n hash: \"a10d463ffd48f2392401efe3dde566faa1869e5e089db830632873a5b9528ee0\",\n },\n\n staleSpendRecoveryValidator: {\n cid: \"QmRxk2qJL64wy1wgJynR3aL9hzTXdPBBw8ZZK177EdVHp4\",\n authorizedCidHex: cidToHex(\n \"QmRxk2qJL64wy1wgJynR3aL9hzTXdPBBw8ZZK177EdVHp4\",\n ),\n name: \"Stale Spend Recovery Validator\",\n description: \"Production Stale Spend Recovery Validator\",\n version: \"1.2.4\",\n deployed: true,\n deployedAt: 1793188544264,\n size: 50029,\n hash: \"6d68c574bf1af2bcb0c4afb51fdd9151f920827b81477ab762eec08332c77de3\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x046da0ad6da7dd4a0063cbeac6f2bdb6a9889c2178b23470833356a8ee5630f7f0eee0db348d9d9aaaadd23eccf0063c8f68ee5e446abe30b882bf1de4c932bc21\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n\n btcUtxoInvalidator: {\n cid: \"QmSGjgPuNgw2EB6yLZ9PmDtKWCCC6ELyUZie5ksSm8dE5E\",\n authorizedCidHex: cidToHex(\n \"QmSGjgPuNgw2EB6yLZ9PmDtKWCCC6ELyUZie5ksSm8dE5E\",\n ),\n name: \"Btc Utxo Invalidator\",\n description: \"Production Btc Utxo Invalidator\",\n version: \"1.2.2\",\n deployed: true,\n deployedAt: 1793188552704,\n size: 73530,\n hash: \"d58b17d36cd133b353ce79d3c6caca57989a5a3ab15e8256f297013aaa34d5b3\",\n },\n\n carryCollateralAttestation: {\n cid: \"Qmd6tYkim469tCyf4gPPmpV9qML4REAgjXM4upyP7XmUC6\",\n authorizedCidHex: cidToHex(\n \"Qmd6tYkim469tCyf4gPPmpV9qML4REAgjXM4upyP7XmUC6\",\n ),\n name: \"Carry Collateral Attestation\",\n description: \"LoanCarryVault collateral attestation (borrower, BTC vault, confirmed BTC)\",\n version: \"1.1.5\",\n deployed: true,\n deployedAt: 1793188558802,\n size: 23267,\n hash: \"41104a0511cdf3a7e46334153cd7d5a4a5125c597524b419271a5334ed42cfc1\",\n },\n\n carryFundingAttestation: {\n cid: \"QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W\",\n authorizedCidHex: cidToHex(\n \"QmWhox3xUZMNR5NpPZ9WLSPC5GoW4ms88GanVRKr8uuS3W\",\n ),\n name: \"Carry Funding Attestation\",\n description: \"LoanCarryVault funding attestation (Hyperliquid BTC windowed hourly average)\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1790925699980,\n size: 7193,\n hash: \"4944ada61610cf64b32e33b5be62087088dcf5e821040c69e67942e643ce74c9\",\n },\n\n backingAttestation: {\n cid: \"QmRkWKprbhP865uALCjfp8gC34JJtZZuD5UFZxqB2jJ8Hi\",\n authorizedCidHex: cidToHex(\n \"QmRkWKprbhP865uALCjfp8gC34JJtZZuD5UFZxqB2jJ8Hi\",\n ),\n name: \"Backing Attestation\",\n description: \"BackingOracle report: BTC collateral over loan UCD at a pinned block, from a keeper snapshot the action verifies\",\n version: \"1.0.2\",\n deployed: true,\n deployedAt: 1793955517792,\n size: 20733,\n hash: \"9b87800369aa37b12496cfaf8247e5e52eb82ad292519e75e799274046cf214a\",\n },\n};\n\nexport function getDeploymentsForNetwork(\n network: SupportedLitNetwork,\n): Partial<DiamondHandsLitActions> {\n if (network === \"chipotle\") return DH_LIT_ACTIONS_CHIPOTLE;\n throw new Error(`Unsupported LIT network: ${network}`);\n}\n\nexport const CHIPOTLE_DEPLOYMENTS = DH_LIT_ACTIONS_CHIPOTLE;\n", "import { LitActionConfig, LitActionName } from \"../../interfaces\";\nimport {\n getDeploymentsForNetwork,\n SupportedLitNetwork,\n} from \"../../constants/chunks/lit-actions-registry\";\n\n/**\n * Get LIT Action CID by name\n * @param actionName - Name of the LIT Action\n * @returns IPFS CID of the deployed action\n * @throws Error if action is not deployed\n */\nexport function getLitActionCID(\n litNetwork: SupportedLitNetwork = \"chipotle\",\n actionName: LitActionName,\n): string {\n const deployments = getDeploymentsForNetwork(litNetwork);\n const action = deployments[actionName];\n\n if (!action || !action.deployed || !action.cid) {\n throw new Error(\n `LIT Action '${actionName}' not deployed on network '${litNetwork}'. Check deployment status.`,\n );\n }\n return action.cid;\n}\n\n/**\n * Get LIT Action configuration by name\n * @param actionName - Name of the LIT Action\n * @returns Complete LIT Action configuration\n */\nexport function getLitActionConfig(\n actionName: LitActionName,\n litNetwork: SupportedLitNetwork = \"chipotle\",\n): LitActionConfig {\n const deployments = getDeploymentsForNetwork(litNetwork);\n const action = deployments[actionName];\n if (!action) {\n throw new Error(\n `LIT Action '${actionName}' not found in registry for network '${litNetwork}'.`,\n );\n }\n return action;\n}\n\n/**\n * Check if a LIT Action is deployed and ready to use\n * @param actionName - Name of the LIT Action\n * @returns True if deployed, false otherwise\n */\nexport function isLitActionDeployed(\n actionName: LitActionName,\n litNetwork: SupportedLitNetwork = \"chipotle\",\n): boolean {\n const deployments = getDeploymentsForNetwork(litNetwork);\n const action = deployments[actionName];\n return !!(action && action.deployed && action.cid);\n}\n\n/**\n * Validate that all required actions are deployed\n * @param requiredActions - Array of required action names\n * @returns True if all actions are deployed\n */\nexport function validateDeployedActions(\n requiredActions: LitActionName[],\n litNetwork: SupportedLitNetwork = \"chipotle\",\n): boolean {\n return requiredActions.every((actionName) =>\n isLitActionDeployed(actionName, litNetwork),\n );\n}\n\n/**\n * Get all deployed LIT Actions\n * @returns Array of deployed LIT Action configurations\n */\nexport function getDeployedActions(\n litNetwork: SupportedLitNetwork = \"chipotle\",\n): LitActionConfig[] {\n const deployments = getDeploymentsForNetwork(litNetwork);\n return Object.values(deployments).filter(\n (action) => action && action.deployed,\n );\n}\n", "import {\n getDeploymentsForNetwork,\n SupportedLitNetwork,\n} from \"../../constants/chunks/lit-actions-registry\";\n/**\n * Get the complete setup for PKP Validator testing\n * Returns both the LIT Action config and its associated PKP\n */\nexport function getPKPValidatorSetup(\n litNetwork: SupportedLitNetwork = \"chipotle\"\n) {\n const deployments = getDeploymentsForNetwork(litNetwork);\n const litAction = deployments.pkpValidator;\n\n if (!litAction || !litAction.pkp) {\n throw new Error(\n `PKP validator setup is not available for litNetwork='${litNetwork}'. ` +\n `Ensure the pkpValidator action (with pkp attached) is defined in the registry.`\n );\n }\n\n return {\n litAction,\n pkp: litAction.pkp!,\n };\n}\n", "/**\n * LIT Protocol Connection Helpers\n * Provides retry logic, error handling, and connection validation utilities\n * for robust LIT Protocol operations\n */\n\nimport {\n debugInfo,\n debugWarn,\n debugError,\n logConnectionAttempt,\n logConnectionSuccess,\n logConnectionFailure,\n logRequest,\n logResponse,\n logError,\n logPkpOperation,\n logLitActionExecution,\n logLitActionResult,\n networkMetrics,\n PerformanceTracker\n} from './debug-logger';\nimport {\n classifyError,\n getRetryConfigFromClassification,\n createErrorReport,\n litProtocolErrors\n} from './error-classification';\n\n/**\n * Retry configuration options\n */\nexport interface RetryConfig {\n maxAttempts: number;\n initialDelayMs: number;\n maxDelayMs: number;\n backoffMultiplier: number;\n retryableErrors: string[];\n}\n\n/**\n * Default retry configuration optimized for LIT Protocol operations\n */\nexport const DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxAttempts: 5, // Increased from 3 for PKP operations\n initialDelayMs: 2000, // Increased from 1000ms for PKP operations\n maxDelayMs: 60000, // Increased from 30000ms for PKP operations\n backoffMultiplier: 2,\n retryableErrors: [\n 'request_timeout',\n 'network error',\n 'connection failed',\n 'ENOTFOUND',\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'socket hang up',\n 'timeout',\n // PKP-specific errors\n 'signing shares',\n 'There was an error getting the signing shares',\n 'PKP validation',\n 'pkp validation failed',\n 'resource validation',\n 'ipfs propagation',\n 'session.*expired',\n 'NodeError',\n 'Response from the nodes',\n 'consensus',\n 'threshold'\n ]\n};\n\n/**\n * Connection validation result\n */\nexport interface ConnectionValidationResult {\n isValid: boolean;\n error?: string;\n latencyMs?: number;\n}\n\n/**\n * Sleep utility for retry delays\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Check if an error is retryable using enhanced classification system\n */\nexport function isRetryableError(error: any, retryableErrors: string[] = DEFAULT_RETRY_CONFIG.retryableErrors): boolean {\n if (!error) return false;\n\n // Use enhanced error classification for LIT Protocol specific errors\n const classification = classifyError(error);\n\n // If classification determined retryability, use that\n if (classification.isRetryable !== undefined) {\n debugInfo('ERROR_CLASSIFICATION', `Error classified as: ${classification.category} (retryable: ${classification.isRetryable})`);\n return classification.isRetryable;\n }\n\n // Fallback to legacy pattern matching\n const errorMessage = error.message || error.toString() || '';\n const errorLower = errorMessage.toLowerCase();\n\n return retryableErrors.some(pattern =>\n errorLower.includes(pattern.toLowerCase())\n );\n}\n\n/**\n * Calculate exponential backoff delay with jitter\n */\nexport function calculateDelay(attempt: number, config: RetryConfig): number {\n const exponentialDelay = Math.min(\n config.initialDelayMs * Math.pow(config.backoffMultiplier, attempt - 1),\n config.maxDelayMs\n );\n\n // Add jitter (\u00B125%) to avoid thundering herd\n const jitter = exponentialDelay * 0.25 * (Math.random() - 0.5);\n return Math.max(100, exponentialDelay + jitter);\n}\n\n/**\n * Enhanced retry wrapper with intelligent error classification\n */\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n config: Partial<RetryConfig> = {},\n operationName: string = 'operation'\n): Promise<T> {\n let finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };\n const tracker = new PerformanceTracker(`Retry ${operationName}`);\n let lastError: any;\n let errorClassification: any = null;\n\n for (let attempt = 1; attempt <= finalConfig.maxAttempts; attempt++) {\n try {\n debugInfo('RETRY', `\uD83D\uDD04 [${operationName}] Attempt ${attempt}/${finalConfig.maxAttempts}`);\n const startTime = Date.now();\n const result = await operation();\n const duration = Date.now() - startTime;\n\n debugInfo('RETRY', `\u2705 [${operationName}] Success after ${duration}ms (attempt ${attempt})`);\n networkMetrics.recordRequest(operationName, true, duration);\n tracker.end(true);\n return result;\n } catch (error) {\n lastError = error;\n const errorMessage = (error as any)?.message || (error as any)?.toString() || 'Unknown error';\n\n // Classify error and potentially adjust retry strategy\n errorClassification = classifyError(error);\n\n // Update config with intelligent retry settings if this is the first error\n if (attempt === 1 && errorClassification) {\n const intelligentConfig = getRetryConfigFromClassification(errorClassification);\n finalConfig = {\n ...finalConfig,\n ...intelligentConfig,\n maxAttempts: Math.min(finalConfig.maxAttempts, intelligentConfig.maxAttempts)\n };\n\n debugInfo('RETRY', `\uD83E\uDDE0 Intelligent retry strategy applied: ${errorClassification.category} (${errorClassification.retryStrategy})`);\n debugInfo('RETRY', `\uD83D\uDCCA Adjusted config: max=${finalConfig.maxAttempts}, delay=${finalConfig.initialDelayMs}ms`);\n }\n\n debugWarn('RETRY', `\u26A0\uFE0F [${operationName}] Attempt ${attempt} failed:`, {\n error: errorMessage,\n attempt,\n category: errorClassification.category,\n retryable: errorClassification.isRetryable\n });\n networkMetrics.recordRequest(operationName, false, 0, errorMessage);\n\n // Check if we've exceeded the (possibly adjusted) max attempts\n if (attempt >= finalConfig.maxAttempts) {\n debugError('RETRY', `\u274C [${operationName}] All attempts failed. Last error:`, { error: errorMessage });\n\n // Generate detailed error report\n if (errorClassification) {\n const errorReport = createErrorReport(error);\n debugError('RETRY', `\uD83D\uDCCB Error Analysis Report:\\n${errorReport}`);\n }\n\n tracker.end(false);\n break;\n }\n\n if (!errorClassification.isRetryable) {\n debugError('RETRY', `\uD83D\uDEAB [${operationName}] Non-retryable error (${errorClassification.category}):`, { error: errorMessage });\n\n // Show troubleshooting tips for non-retryable errors\n if (errorClassification.troubleshooting) {\n debugInfo('RETRY', `\uD83D\uDCA1 Troubleshooting suggestions:\\n ${errorClassification.troubleshooting.join('\\n ')}`);\n }\n\n tracker.end(false);\n break;\n }\n\n const delayMs = calculateDelay(attempt, finalConfig);\n debugInfo('RETRY', `\u23F3 [${operationName}] Waiting ${delayMs}ms before retry... (${errorClassification.retryStrategy} strategy)`);\n await sleep(delayMs);\n }\n }\n\n throw lastError;\n}\n\n/**\n * Enhanced LIT Node Client connector with retry logic and readiness validation\n */\nexport async function connectLitNodeClient(\n litNodeClient: any,\n config: Partial<RetryConfig> = {}\n): Promise<void> {\n const network = litNodeClient?.config?.litNetwork || 'unknown';\n\n return withRetry(\n async () => {\n if (!litNodeClient) {\n throw new Error('LIT Node Client is null or undefined');\n }\n\n const startTime = Date.now();\n logConnectionAttempt(network, 1, config.maxAttempts || DEFAULT_RETRY_CONFIG.maxAttempts);\n\n // First connect to the network\n await litNodeClient.connect();\n\n // Wait for client to be ready\n debugInfo('CONNECTION', `\u23F3 Waiting for LIT Node Client to be ready...`);\n const readyTimeout = 30000; // 30 seconds timeout for readiness\n const readyStartTime = Date.now();\n\n while (!litNodeClient.ready && (Date.now() - readyStartTime) < readyTimeout) {\n await sleep(500); // Check every 500ms\n }\n\n if (!litNodeClient.ready) {\n throw new Error(`LIT Node Client failed to become ready within ${readyTimeout}ms`);\n }\n\n const latency = Date.now() - startTime;\n debugInfo('CONNECTION', `\u2705 LIT Node Client is ready (${litNodeClient.ready})`);\n logConnectionSuccess(network, latency);\n },\n config,\n 'LIT Node Client Connection'\n );\n}\n\n/**\n * Enhanced LIT Contracts connector with retry logic\n */\nexport async function connectLitContracts(\n litContracts: any,\n config: Partial<RetryConfig> = {}\n): Promise<void> {\n return withRetry(\n async () => {\n if (!litContracts) {\n throw new Error('LIT Contracts is null or undefined');\n }\n\n console.log(`\uD83D\uDD17 Connecting to LIT Contracts: ${litContracts.network || 'unknown'}`);\n await litContracts.connect();\n console.log('\u2705 LIT Contracts connected successfully');\n },\n config,\n 'LIT Contracts Connection'\n );\n}\n\n/**\n * Validate LIT Node Client connection health\n */\nexport async function validateLitNodeConnection(litNodeClient: any): Promise<ConnectionValidationResult> {\n try {\n const startTime = Date.now();\n\n if (!litNodeClient) {\n return { isValid: false, error: 'LIT Node Client is null or undefined' };\n }\n\n // Try to get the latest block hash as a health check\n await litNodeClient.getLatestBlockhash();\n\n const latencyMs = Date.now() - startTime;\n return { isValid: true, latencyMs };\n } catch (error) {\n return {\n isValid: false,\n error: (error as any)?.message || (error as any)?.toString() || 'Unknown validation error'\n };\n }\n}\n\n/**\n * Enhanced session signature generator with retry logic and caching\n */\nexport async function generateSessionSignatures(\n litNodeClient: any,\n sessionConfig: any,\n config: Partial<RetryConfig> = {},\n pkpTokenId?: string,\n litActionCid?: string,\n signerAddress?: string,\n network: string = 'chipotle'\n): Promise<any> {\n // If caching parameters are provided, try cache first\n if (pkpTokenId && litActionCid && signerAddress) {\n const { sessionSignatureCache } = await import('./session-signature-cache');\n\n const cached = sessionSignatureCache.get(pkpTokenId, litActionCid, signerAddress, network);\n if (cached) {\n const sigCount = Object.keys(cached).length;\n debugInfo('SESSION', `\uD83D\uDD04 Using cached session signatures (${sigCount} sigs)`);\n return cached;\n }\n }\n\n return withRetry(\n async () => {\n debugInfo('SESSION', '\uD83D\uDD10 Generating new session signatures...');\n const sessionSigs = await litNodeClient.getSessionSigs(sessionConfig);\n const sigCount = Object.keys(sessionSigs).length;\n\n // Cache if parameters provided\n if (pkpTokenId && litActionCid && signerAddress) {\n const { sessionSignatureCache } = await import('./session-signature-cache');\n const expiration = new Date(sessionConfig.expiration);\n sessionSignatureCache.set(pkpTokenId, litActionCid, signerAddress, network, sessionSigs, expiration);\n }\n\n debugInfo('SESSION', `\u2705 Generated ${sigCount} session signatures`);\n return sessionSigs;\n },\n config,\n 'Session Signature Generation'\n );\n}\n\n/**\n * Validate LIT Node Client readiness before operations\n */\nexport async function validateLitNodeReadiness(litNodeClient: any): Promise<void> {\n if (!litNodeClient) {\n throw new Error('LIT Node Client is null or undefined');\n }\n\n // Check if client is connected\n if (!litNodeClient.ready) {\n debugWarn('CONNECTION', '\u26A0\uFE0F LIT Node Client not ready, attempting to reconnect...');\n await litNodeClient.connect();\n\n // Wait for readiness with timeout\n const readyTimeout = 15000; // 15 seconds\n const startTime = Date.now();\n\n while (!litNodeClient.ready && (Date.now() - startTime) < readyTimeout) {\n await sleep(500);\n }\n\n if (!litNodeClient.ready) {\n throw new Error('LIT Node Client is not ready for operations');\n }\n }\n\n debugInfo('CONNECTION', '\u2705 LIT Node Client readiness validated');\n}\n\n/**\n * Enhanced LIT Action executor with retry logic and readiness validation\n */\nexport async function executeLitAction(\n litNodeClient: any,\n executionConfig: any,\n config: Partial<RetryConfig> = {}\n): Promise<any> {\n const cid = executionConfig.ipfsId;\n\n return withRetry(\n async () => {\n const startTime = Date.now();\n\n // Validate client readiness before execution\n await validateLitNodeReadiness(litNodeClient);\n\n logLitActionExecution(cid, executionConfig.jsParams);\n logRequest('LIT_ACTION', 'executeJs', executionConfig);\n\n const result = await litNodeClient.executeJs(executionConfig);\n const duration = Date.now() - startTime;\n\n if (!result.response) {\n logError('LIT_ACTION', 'executeJs', new Error('No response from LIT Action'), duration);\n throw new Error('No response from LIT Action');\n }\n\n logResponse('LIT_ACTION', 'executeJs', result, duration);\n logLitActionResult(cid, true, duration, result);\n return result;\n },\n config,\n 'LIT Action Execution'\n );\n}\n\n/**\n * PKP operation wrapper with enhanced error handling\n */\nexport async function executePkpOperation<T>(\n operation: () => Promise<T>,\n operationName: string,\n config: Partial<RetryConfig> = {}\n): Promise<T> {\n const pkpConfig = {\n ...DEFAULT_RETRY_CONFIG,\n ...config,\n retryableErrors: [\n ...DEFAULT_RETRY_CONFIG.retryableErrors,\n 'pkp validation',\n 'signing shares',\n 'resource validation',\n 'ipfs propagation'\n ]\n };\n\n return withRetry(operation, pkpConfig, `PKP ${operationName}`);\n}\n\n/**\n * Network-specific timeout configurations\n */\nexport const NETWORK_TIMEOUTS = {\n chipotle: {\n connection: 60000,\n operation: 120000,\n pkpValidation: 180000,\n },\n} as const;\n\nexport function getNetworkTimeouts(network: string) {\n return NETWORK_TIMEOUTS[network as keyof typeof NETWORK_TIMEOUTS] || NETWORK_TIMEOUTS['chipotle'];\n}", "/**\n * Enhanced Error Classification for LIT Protocol Operations\n * Provides detailed error categorization and specific retry strategies\n */\n\n/**\n * Error categories for different types of failures\n */\nexport enum ErrorCategory {\n NETWORK = 'network',\n PROTOCOL = 'protocol',\n AUTHENTICATION = 'authentication',\n RESOURCE = 'resource',\n VALIDATION = 'validation',\n TIMEOUT = 'timeout',\n RATE_LIMIT = 'rate_limit',\n CONFIGURATION = 'configuration',\n UNKNOWN = 'unknown'\n}\n\n/**\n * Retry strategy types\n */\nexport enum RetryStrategy {\n AGGRESSIVE = 'aggressive', // Fast retries for transient issues\n CONSERVATIVE = 'conservative', // Slower retries for resource issues\n EXPONENTIAL = 'exponential', // Standard exponential backoff\n LINEAR = 'linear', // Linear delay increase\n NONE = 'none' // No retries\n}\n\n/**\n * Error classification result\n */\nexport interface ErrorClassification {\n category: ErrorCategory;\n retryStrategy: RetryStrategy;\n isRetryable: boolean;\n maxAttempts: number;\n baseDelayMs: number;\n maxDelayMs: number;\n description: string;\n troubleshooting?: string[];\n}\n\n/**\n * LIT Protocol specific error patterns\n */\nconst LIT_ERROR_PATTERNS = {\n // Network and connection errors\n network: [\n /network error/i,\n /connection failed/i,\n /connection refused/i,\n /connection timeout/i,\n /socket hang up/i,\n /enotfound/i,\n /econnrefused/i,\n /etimedout/i,\n /dns resolution failed/i,\n /request failed/i\n ],\n\n // Protocol specific errors\n protocol: [\n /lit protocol/i,\n /lit node/i,\n /signing shares/i,\n /node communication/i,\n /consensus/i,\n /threshold/i,\n /decryption/i,\n /signature verification/i,\n /There was an error getting the signing shares/i,\n /Response from the nodes/i,\n /NodeError/i,\n /PKP validation/i,\n /pkp validation failed/i\n ],\n\n // Authentication and authorization errors\n authentication: [\n /authentication/i,\n /authorization/i,\n /session.*expired/i,\n /invalid.*signature/i,\n /unauthorized/i,\n /access.*denied/i,\n /permission/i,\n /auth.*failed/i,\n /siwe/i,\n /session.*sig/i\n ],\n\n // Resource and validation errors\n resource: [\n /resource.*not.*found/i,\n /ipfs.*not.*found/i,\n /cid.*invalid/i,\n /pkp.*not.*found/i,\n /pkp.*validation/i,\n /resource.*validation/i,\n /action.*not.*permitted/i,\n /lit.*action.*not.*found/i\n ],\n\n // Validation errors\n validation: [\n /validation.*failed/i,\n /invalid.*input/i,\n /invalid.*parameter/i,\n /malformed/i,\n /schema.*validation/i,\n /type.*error/i,\n /missing.*required/i\n ],\n\n // Timeout specific errors\n timeout: [\n /timeout/i,\n /request.*timed.*out/i,\n /operation.*timed.*out/i,\n /deadline.*exceeded/i,\n /time.*limit.*exceeded/i\n ],\n\n // Rate limiting errors\n rateLimit: [\n /rate.*limit/i,\n /too.*many.*requests/i,\n /quota.*exceeded/i,\n /throttled/i,\n /429/,\n /rate.*exceeded/i\n ],\n\n // Configuration errors\n configuration: [\n /configuration/i,\n /config.*error/i,\n /environment/i,\n /missing.*env/i,\n /invalid.*config/i,\n /setup.*error/i\n ]\n};\n\n/**\n * Predefined retry strategies\n */\nconst RETRY_STRATEGIES = {\n [RetryStrategy.AGGRESSIVE]: {\n maxAttempts: 5,\n baseDelayMs: 500,\n maxDelayMs: 5000,\n multiplier: 1.5\n },\n [RetryStrategy.CONSERVATIVE]: {\n maxAttempts: 3,\n baseDelayMs: 3000,\n maxDelayMs: 30000,\n multiplier: 2.5\n },\n [RetryStrategy.EXPONENTIAL]: {\n maxAttempts: 4,\n baseDelayMs: 1000,\n maxDelayMs: 15000,\n multiplier: 2.0\n },\n [RetryStrategy.LINEAR]: {\n maxAttempts: 3,\n baseDelayMs: 2000,\n maxDelayMs: 10000,\n multiplier: 1.0\n },\n [RetryStrategy.NONE]: {\n maxAttempts: 1,\n baseDelayMs: 0,\n maxDelayMs: 0,\n multiplier: 1.0\n }\n};\n\n/**\n * Error classification rules\n */\nconst CLASSIFICATION_RULES: Record<ErrorCategory, ErrorClassification> = {\n [ErrorCategory.NETWORK]: {\n category: ErrorCategory.NETWORK,\n retryStrategy: RetryStrategy.AGGRESSIVE,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.AGGRESSIVE],\n description: 'Network connectivity or communication error',\n troubleshooting: [\n 'Check internet connection',\n 'Verify LIT Protocol network status',\n 'Check firewall and proxy settings',\n 'Try connecting to different node endpoints'\n ]\n },\n\n [ErrorCategory.PROTOCOL]: {\n category: ErrorCategory.PROTOCOL,\n retryStrategy: RetryStrategy.CONSERVATIVE,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.CONSERVATIVE],\n description: 'LIT Protocol specific operational error',\n troubleshooting: [\n 'Check LIT Protocol network status',\n 'Verify PKP configuration',\n 'Check signing shares availability',\n 'Wait for network consensus'\n ]\n },\n\n [ErrorCategory.AUTHENTICATION]: {\n category: ErrorCategory.AUTHENTICATION,\n retryStrategy: RetryStrategy.EXPONENTIAL,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.EXPONENTIAL],\n maxAttempts: 2, // Override: limited retries for auth issues\n description: 'Authentication or authorization error',\n troubleshooting: [\n 'Check session signatures validity',\n 'Regenerate authentication tokens',\n 'Verify wallet permissions',\n 'Check PKP authorization status'\n ]\n },\n\n [ErrorCategory.RESOURCE]: {\n category: ErrorCategory.RESOURCE,\n retryStrategy: RetryStrategy.LINEAR,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.LINEAR],\n maxAttempts: 2, // Override: limited retries for resource issues\n description: 'Resource not found or validation error',\n troubleshooting: [\n 'Verify resource CIDs are correct',\n 'Check IPFS availability',\n 'Confirm PKP exists and is accessible',\n 'Wait for resource propagation'\n ]\n },\n\n [ErrorCategory.VALIDATION]: {\n category: ErrorCategory.VALIDATION,\n retryStrategy: RetryStrategy.NONE,\n isRetryable: false,\n ...RETRY_STRATEGIES[RetryStrategy.NONE],\n description: 'Input validation or schema error',\n troubleshooting: [\n 'Check input parameters format',\n 'Verify required fields are provided',\n 'Validate data types and ranges',\n 'Review API documentation'\n ]\n },\n\n [ErrorCategory.TIMEOUT]: {\n category: ErrorCategory.TIMEOUT,\n retryStrategy: RetryStrategy.CONSERVATIVE,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.CONSERVATIVE],\n description: 'Operation timeout error',\n troubleshooting: [\n 'Increase timeout values',\n 'Check network latency',\n 'Verify system resources',\n 'Split operations into smaller chunks'\n ]\n },\n\n [ErrorCategory.RATE_LIMIT]: {\n category: ErrorCategory.RATE_LIMIT,\n retryStrategy: RetryStrategy.CONSERVATIVE,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.CONSERVATIVE],\n maxAttempts: 2, // Override: limited retries to avoid further rate limiting\n baseDelayMs: 5000, // Override: longer delays for rate limits\n description: 'Rate limit or quota exceeded',\n troubleshooting: [\n 'Reduce request frequency',\n 'Implement request batching',\n 'Check rate limit headers',\n 'Wait for quota reset'\n ]\n },\n\n [ErrorCategory.CONFIGURATION]: {\n category: ErrorCategory.CONFIGURATION,\n retryStrategy: RetryStrategy.NONE,\n isRetryable: false,\n ...RETRY_STRATEGIES[RetryStrategy.NONE],\n description: 'Configuration or setup error',\n troubleshooting: [\n 'Check environment variables',\n 'Verify configuration files',\n 'Review setup documentation',\n 'Check required dependencies'\n ]\n },\n\n [ErrorCategory.UNKNOWN]: {\n category: ErrorCategory.UNKNOWN,\n retryStrategy: RetryStrategy.EXPONENTIAL,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.EXPONENTIAL],\n maxAttempts: 2, // Override: conservative retries for unknown errors\n description: 'Unknown or unclassified error',\n troubleshooting: [\n 'Check logs for more details',\n 'Verify system status',\n 'Try again with debug logging',\n 'Contact support if persists'\n ]\n }\n};\n\n/**\n * Classify an error and determine retry strategy\n */\nexport function classifyError(error: any): ErrorClassification {\n const errorMessage = error?.message || error?.toString() || '';\n const errorLower = errorMessage.toLowerCase();\n\n // Check each error category\n for (const [category, patterns] of Object.entries(LIT_ERROR_PATTERNS)) {\n for (const pattern of patterns) {\n if (pattern.test(errorMessage) || pattern.test(errorLower)) {\n const classification = CLASSIFICATION_RULES[category as ErrorCategory];\n return {\n ...classification,\n description: `${classification.description}: ${errorMessage.slice(0, 100)}`\n };\n }\n }\n }\n\n // Default to unknown category\n const unknownClassification = CLASSIFICATION_RULES[ErrorCategory.UNKNOWN];\n return {\n ...unknownClassification,\n description: `${unknownClassification.description}: ${errorMessage.slice(0, 100)}`\n };\n}\n\n/**\n * Get retry configuration from error classification\n */\nexport function getRetryConfigFromClassification(classification: ErrorClassification) {\n return {\n maxAttempts: classification.maxAttempts,\n initialDelayMs: classification.baseDelayMs,\n maxDelayMs: classification.maxDelayMs,\n backoffMultiplier: RETRY_STRATEGIES[classification.retryStrategy].multiplier,\n retryableErrors: ['*'] // Classification already determined retryability\n };\n}\n\n/**\n * Enhanced error analyzer for detailed error information\n */\nexport function analyzeError(error: any) {\n const classification = classifyError(error);\n\n return {\n ...classification,\n originalError: error,\n errorMessage: error?.message || error?.toString() || 'Unknown error',\n errorStack: error?.stack,\n timestamp: new Date().toISOString(),\n retryConfig: getRetryConfigFromClassification(classification)\n };\n}\n\n/**\n * Create a human-readable error report\n */\nexport function createErrorReport(error: any) {\n const analysis = analyzeError(error);\n\n const report = [\n `\uD83D\uDD0D Error Analysis Report`,\n `=====================================`,\n `Category: ${analysis.category.toUpperCase()}`,\n `Retryable: ${analysis.isRetryable ? '\u2705 Yes' : '\u274C No'}`,\n `Strategy: ${analysis.retryStrategy}`,\n `Max Attempts: ${analysis.maxAttempts}`,\n `Description: ${analysis.description}`,\n `Timestamp: ${analysis.timestamp}`,\n ``,\n `Original Error: ${analysis.errorMessage}`,\n ``\n ];\n\n if (analysis.troubleshooting && analysis.troubleshooting.length > 0) {\n report.push(`\uD83D\uDEE0\uFE0F Troubleshooting Steps:`);\n analysis.troubleshooting.forEach((step, index) => {\n report.push(` ${index + 1}. ${step}`);\n });\n report.push('');\n }\n\n return report.join('\\n');\n}\n\n/**\n * LIT Protocol specific error matchers\n */\nexport const litProtocolErrors = {\n isNetworkError: (error: any) => classifyError(error).category === ErrorCategory.NETWORK,\n isProtocolError: (error: any) => classifyError(error).category === ErrorCategory.PROTOCOL,\n isAuthenticationError: (error: any) => classifyError(error).category === ErrorCategory.AUTHENTICATION,\n isResourceError: (error: any) => classifyError(error).category === ErrorCategory.RESOURCE,\n isTimeoutError: (error: any) => classifyError(error).category === ErrorCategory.TIMEOUT,\n isRateLimitError: (error: any) => classifyError(error).category === ErrorCategory.RATE_LIMIT,\n isConfigurationError: (error: any) => classifyError(error).category === ErrorCategory.CONFIGURATION,\n isRetryable: (error: any) => classifyError(error).isRetryable\n};", "/**\n * Diamond Hands LIT Actions Utilities\n * All utility functions for working with deployed LIT Actions\n */\n\nexport * from \"./chunks/lit-action-helpers\";\nexport * from \"./chunks/pkp-setup\";\nexport * from \"./chunks/cid-utils\";\nexport * from \"./chunks/connection-helpers\";\nexport * from \"./chunks/debug-logger\";\nexport * from \"./chunks/error-classification\";\nexport * from \"./chunks/session-signature-cache\";\n", "/**\n * Vault Snapshot Executor - NOLA (No LIT Action)\n *\n * Standalone executor that wraps VaultSnapshotModule for Node.js execution.\n * Reuses the same pattern as tests/helpers/setup-lit-env.ts.\n *\n * Purpose: FREE data access without paying for LIT Action execution.\n * Use case: Position listing, collateral ratio display, mint preview.\n *\n * Architecture:\n * - Same vault-snapshot.ts code (zero changes)\n * - Inject Node.js providers (ethers, axios) instead of Lit.Actions.*\n * - Returns identical VaultSnapshot data structure\n */\n\nimport { ethers } from \"ethers\";\nimport { createVaultSnapshotModule } from \"../../../src/modules/vault-snapshot\";\nimport { BitcoinDataProvider } from \"../../../src/modules/bitcoin-data-provider.module\";\nimport { PriceOracleModule } from \"../../../src/modules/price-oracle.module\";\nimport { createVaultBalanceModule } from \"../../../src/modules/vault-balance.module\";\nimport { getChainPolicy } from \"../../../src/modules/chain-policy\";\nimport { VaultSnapshot } from \"../../../src/interfaces/chunks/vault-snapshot.i\";\n\n/**\n * Parameters for vault snapshot execution\n */\nexport interface VaultSnapshotExecutorParams {\n positionId: string;\n contractAddress: string; // PositionManager address\n termManagerAddress: string;\n loanOpsManagerAddress: string;\n liquidationManagerAddress: string;\n chain: string; // 'sepolia', 'ethereum', etc.\n chainId?: number;\n rpcUrl: string; // Ethereum RPC URL\n bitcoinProviderUrl: string; // Bitcoin Esplora API URL\n /**\n * Balance-confirmation threshold override. Defaults to the chain policy's\n * `minBitcoinBalanceConfirmations` (mainnet 6, dev chains 1).\n */\n minConfirmations?: number;\n}\n\n/**\n * Execute vault snapshot in Node.js (NOLA - No LIT Action)\n *\n * This function wraps VaultSnapshotModule with Node.js providers,\n * allowing the same code to run outside LIT Actions runtime.\n *\n * @param params - Execution parameters\n * @returns Complete VaultSnapshot\n */\nexport async function executeVaultSnapshot(\n params: VaultSnapshotExecutorParams\n): Promise<VaultSnapshot> {\n // No mainnet default (same rule as VaultSnapshotModule): refuse before touching globals.\n const chainId = params.chainId;\n if (chainId === undefined || !Number.isInteger(chainId) || chainId <= 0) {\n throw new Error(`executeVaultSnapshot requires a positive integer chainId, got ${String(chainId)}`);\n }\n\n // Setup global ethers with v5 compatibility shim for modules\n // Ethers v6 changed API: providers.StaticJsonRpcProvider \u2192 JsonRpcProvider\n (global as any).ethers = {\n ...ethers,\n providers: {\n StaticJsonRpcProvider: ethers.JsonRpcProvider,\n },\n Contract: ethers.Contract,\n utils: ethers, // v6 moved utils to top level\n };\n\n // Setup Lit.Actions mock (same pattern as tests)\n (global as any).Lit = {\n Actions: {\n /**\n * Get RPC URL - returns provided URL\n */\n getRpcUrl: async ({ chain }: { chain: string }): Promise<string> => {\n return params.rpcUrl;\n },\n\n /**\n * Set response (not used in vault-snapshot, but needed for compatibility)\n */\n setResponse: ({ response }: { response: string }): void => {\n // No-op in executor\n },\n\n /**\n * Broadcast and collect (NOLA mode: single node, just return value)\n * In LIT Actions environment, this would collect values from all nodes.\n * In NOLA executor, we're running on a single trusted node, so return single value.\n */\n broadcastAndCollect: async ({ name, value }: { name: string; value: string }): Promise<string[]> => {\n // NOLA: Single node execution, return array with single value\n return [value];\n },\n },\n };\n\n // Initialize Bitcoin data provider\n const bitcoinProvider = new BitcoinDataProvider({\n providerUrl: params.bitcoinProviderUrl,\n });\n\n // Initialize price oracle\n // Note: vault-snapshot-executor doesn't receive priceProviders in params, so uses defaults\n const priceOracle = new PriceOracleModule();\n\n // Initialize vault balance module\n const vaultBalance = createVaultBalanceModule({\n contractAddress: params.loanOpsManagerAddress,\n chain: params.chain,\n chainId,\n rpcUrl: params.rpcUrl,\n bitcoinProvider,\n minConfirmations:\n params.minConfirmations ??\n getChainPolicy(params.chain).minBitcoinBalanceConfirmations,\n });\n\n // Initialize vault snapshot module\n const vaultSnapshot = createVaultSnapshotModule({\n contractAddress: params.contractAddress,\n termManagerAddress: params.termManagerAddress,\n loanOpsManagerAddress: params.loanOpsManagerAddress,\n liquidationManagerAddress: params.liquidationManagerAddress,\n chain: params.chain,\n chainId,\n rpcUrl: params.rpcUrl,\n vaultBalance,\n priceOracle,\n });\n\n // Execute - returns identical VaultSnapshot as LIT Action would\n const snapshot = await vaultSnapshot.getVaultSnapshot(params.positionId);\n\n // Cleanup globals\n delete (global as any).ethers;\n delete (global as any).Lit;\n\n return snapshot;\n}\n", "/**\n * Liquidation Protocol Constants\n *\n * These constants define the liquidation thresholds and grace period escalation\n * for the Diamond Hands Protocol. They are governance-adjustable parameters.\n *\n * CRITICAL: Changes to these values affect protocol security and user positions.\n */\n\n/**\n * Active Loan Liquidation Threshold\n *\n * Minimum collateral ratio required for active (non-expired) loans.\n * Value: 110% (11000 basis points)\n *\n * Canonical source: LoanOperationsManager.liquidationThreshold() on-chain.\n * This constant reflects the protocol-configured value; always prefer fetching\n * from the contract at runtime rather than relying on this constant.\n *\n * Governance-adjustable: YES\n */\nexport const ACTIVE_LOAN_LIQUIDATION_THRESHOLD_BPS = 11000;\n\n/**\n * Expired Loan Minimum Liquidation Threshold\n *\n * Liquidation threshold from expiry through the on-chain grace period, and the seed\n * of the compound escalation after it. Mirrors `ExpiredLoanCalculator.BASE_LIQUIDATION_THRESHOLD`.\n * Value: 110% (11000 basis points)\n *\n * Governance-adjustable: NO (contract constant)\n */\nexport const EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11000;\n\n/**\n * Expired-loan escalation iteration cap\n *\n * Mirrors `ExpiredLoanCalculator.MAX_ESCALATION_ITERATIONS`: once a loan is this many\n * escalation days past its grace period it is unconditionally at the max escalated\n * threshold. The grace period and daily increment themselves are read on-chain from\n * LiquidationManager (`expiredLoanGracePeriodDays`, `expiryLiquidationIncrementBps`).\n *\n * Governance-adjustable: NO (contract constant)\n */\nexport const EXPIRED_LOAN_MAX_ESCALATION_ITERATIONS = 365;\n\n/**\n * Basis-points denominator (100% = 10 000 bps). Mirrors `ExpiredLoanCalculator.BASIS_POINTS`.\n */\nexport const BASIS_POINTS_DENOMINATOR = 10000;\n", "/**\n * Decimal Precision Constants\n *\n * These constants define the decimal precision for various assets and calculations\n * in the Diamond Hands Protocol. They ensure consistent precision across all modules.\n *\n * CRITICAL: These values MUST match contract implementations.\n */\n\n/**\n * Satoshis per Bitcoin\n *\n * Bitcoin's smallest unit is a satoshi (sat).\n * 1 BTC = 100,000,000 satoshis\n *\n * This constant is used for BTC <-> satoshi conversions.\n *\n * Governance-adjustable: NO (Bitcoin protocol constant)\n */\nexport const SATOSHIS_PER_BITCOIN = 100_000_000n;\n\n/**\n * Price Oracle Decimal Precision\n *\n * BTC/USD price is stored with 8 decimal places.\n * Example: $100,000.00 = 10000000000000n (100000 * 10^8)\n *\n * This matches Bitcoin's satoshi precision and allows for sub-cent pricing.\n *\n * Governance-adjustable: NO (System design constant)\n */\nexport const PRICE_ORACLE_DECIMALS = 100_000_000n;\n\n/**\n * UCD Token Decimal Precision\n *\n * UCD is an ERC20 token with 18 decimals (standard for stablecoins).\n * 1 UCD = 10^18 wei\n *\n * This constant is used for all UCD amount calculations.\n *\n * CRITICAL: Must match UCD token contract decimals.\n *\n * Governance-adjustable: NO (Contract constant)\n */\nexport const UCD_TOKEN_DECIMALS = 1_000_000_000_000_000_000n;\n", "/**\n * Bitcoin Network Protocol Constants\n *\n * These constants define Bitcoin network parameters used by the protocol\n * for UTXO validation and security.\n *\n * CRITICAL: Changes to these values affect Bitcoin security guarantees.\n */\n\n/**\n * Maximum BTC Amount Validation\n *\n * Maximum reasonable BTC amount in satoshis.\n * Value: 25,000,000 BTC * 1e8 satoshis = 2.5e15 satoshis\n *\n * Bitcoin total supply is 21M BTC. Setting to 25M provides safety margin\n * to account for future protocol needs while preventing overflow attacks.\n *\n * This validation prevents:\n * - Malicious/corrupted data from oracle manipulation\n * - Integer overflow attacks\n * - Unrealistic balance claims\n *\n * Governance-adjustable: YES (requires contract upgrade)\n */\nexport const MAX_BTC_AMOUNT = 25_000_000 * 1e8; // 2.5e15 satoshis\n\n/**\n * BTC/USD Price Validation Bounds\n *\n * Acceptable range for BTC price in oracle 8-decimal format.\n * Values outside this range indicate oracle manipulation or stale data.\n *\n * MIN: $10,000 (protective floor \u2014 BTC has never traded below this in protocol's lifetime)\n * MAX: $1,000,000 (protective ceiling \u2014 safeguard against oracle inflation attacks)\n *\n * Governance-adjustable: YES (requires review of oracle security model)\n */\nexport const BTC_PRICE_MIN_USD = 10_000_00000000n; // $10k (8 decimals)\nexport const BTC_PRICE_MAX_USD = 1_000_000_00000000n; // $1M (8 decimals)\n\n/**\n * Bitcoin Dust Limit (satoshis)\n *\n * Standard dust threshold for P2PKH outputs (546 satoshis).\n * Outputs below this amount are non-standard and may be rejected by the Bitcoin network.\n *\n * Governance-adjustable: NO (Bitcoin network protocol rule)\n */\nexport const BITCOIN_DUST_LIMIT_SATS = 546n;\n\n/**\n * Bitcoin Transaction Fee Bounds (satoshis)\n *\n * MIN is the floor for any protocol Bitcoin transaction. MAX_BTC_FEE_SATS is a\n * FLAT absolute ceiling still used by the fixed-size single-purpose actions\n * (btc-utxo-invalidator, stale-spend-recovery-validator). The variable-size\n * WITHDRAWAL path does NOT use MAX_BTC_FEE_SATS \u2014 a flat cap is an implicit\n * fee-rate ceiling that shrinks as inputs grow, blocking large consolidations;\n * it uses the size-aware bound in `modules/bitcoin/fee.ts` instead.\n *\n * Adjustability: these are Lit Action constants \u2014 changing a value requires a\n * bundle rebundle + CID rotation ceremony (NOT a runtime/governance toggle).\n */\nexport const MIN_BTC_FEE_SATS = 100; // Minimum viable Bitcoin fee\nexport const MAX_BTC_FEE_SATS = 100_000; // 0.001 BTC \u2014 flat cap for fixed-size (non-withdrawal) actions\n\n/**\n * UTXO Query Retry Parameters\n *\n * Number of attempts and delay between retries when querying UTXOs from\n * the Bitcoin data provider. Applied uniformly across all retry loops.\n *\n * Governance-adjustable: NO (operational tuning constant)\n */\nexport const UTXO_QUERY_MAX_RETRIES = 3;\nexport const UTXO_QUERY_RETRY_DELAY_MS = 500; // 500ms between retries\n", "/**\n * Quantum Time Window Protocol Constants\n *\n * These constants define the quantum time window system used for temporal\n * validation of signed operations across the protocol.\n *\n * CRITICAL: Changes to these values affect replay attack protection and\n * validator synchronization. All validators must use identical values.\n */\n\n/**\n * Quantum Window Duration (seconds)\n *\n * Each quantum window is 60 seconds long.\n * Quantum timestamps always end in :00 seconds: 0, 60, 120, 180...\n *\n * Value: 60 seconds \u2014 MUST match `OperationAuthorizationRegistry.QUANTUM_WINDOW_SECONDS`\n * on every chain. Drift here causes spurious `QuantumOutsideWindow()` reverts because\n * the Lit Action signs a `quantumTimestamp` aligned to its window while the contract\n * floors it to its own window. A bad merge briefly bumped this to 100 \u2014 never again.\n *\n * Purpose:\n * - Improved UX with immediate signing (no waiting)\n * - 3-quantum validation window (past, current, next) = 180s total validity\n * - Prevents replay attacks across quantum boundaries\n * - Users can operate once per 60 seconds per position\n *\n * Security guarantee: Signatures valid across 3 quantums with replay prevention.\n *\n * Governance-adjustable: NO (protocol-level constant)\n */\nexport const QUANTUM_WINDOW_SECONDS = 60;\n\n/**\n * Dead Zone Duration (seconds)\n *\n * The dead zone spans the quantum boundary: 8 seconds before + 8 seconds after.\n * During this period, LIT Actions WAIT and Smart Contracts REJECT.\n *\n * Dead zone structure:\n * - Seconds 92-99: Last 8 seconds of quantum (before boundary)\n * - Seconds 0-7: First 8 seconds of quantum (after boundary)\n * - Total: 16 seconds\n *\n * Value: 16 seconds (8+8)\n *\n * Protects against:\n * 1. Clock desynchronization (NTP drift, network delays)\n * 2. Ethereum miner timestamp manipulation (validators can shift \u00B115 seconds)\n * 3. Quantum boundary confusion\n *\n * Security guarantee: 16-second buffer > 15-second miner manipulation = complete protection.\n *\n * Governance-adjustable: NO (protocol-level constant, security-critical)\n */\nexport const DEAD_ZONE_SECONDS = 16;\n\n/**\n * Safe Execution Window (seconds)\n *\n * Actual usable time in each quantum after excluding the dead zone.\n *\n * Value: 44 seconds (QUANTUM_WINDOW_SECONDS - DEAD_ZONE_SECONDS)\n * With 60s quantum: safe period is seconds 8-51 of each quantum\n *\n * Governance-adjustable: NO (derived from other constants)\n */\nexport const SAFE_EXECUTION_WINDOW_SECONDS =\n QUANTUM_WINDOW_SECONDS - DEAD_ZONE_SECONDS;\n\n/**\n * Quantum Timestamp Offset (seconds)\n *\n * The offset added to the current quantum timestamp when building signed\n * message hashes. Set to the next quantum boundary to ensure the signature\n * remains valid through the current quantum and into the next.\n *\n * Value: 10 seconds \u2014 places the signed timestamp safely inside the upcoming\n * quantum window, matching the contract-side validation window.\n *\n * CRITICAL: Must match the offset expected by the smart contract validators.\n *\n * Governance-adjustable: NO (protocol-level constant, must match contract)\n */\nexport const QUANTUM_TIMESTAMP_OFFSET = 10;\n", "/**\n * Time Protocol Constants\n *\n * Canonical time unit constants used for term duration calculations\n * throughout the protocol. Centralised here to avoid silent drift if\n * any value ever needs to change.\n *\n * NOTE: The protocol models months as exactly 30 days and years as exactly\n * 365 days. This is intentional \u2014 simplicity and consistency with the\n * on-chain term calculations take precedence over calendar accuracy.\n */\n\n/**\n * Seconds per day\n *\n * Value: 86400 (24 * 60 * 60)\n *\n * Governance-adjustable: NO (physical constant)\n */\nexport const SECONDS_PER_DAY = 86400;\n\n/**\n * Days per month (protocol approximation)\n *\n * Value: 30\n *\n * The protocol uses a fixed 30-day month for all term calculations,\n * matching the on-chain TermManager configuration.\n *\n * Governance-adjustable: NO (must match contract term definitions)\n */\nexport const DAYS_PER_MONTH = 30;\n\n/**\n * Months per year\n *\n * Value: 12\n *\n * Governance-adjustable: NO (calendar constant)\n */\nexport const MONTHS_PER_YEAR = 12;\n\n/**\n * Days per year (protocol approximation)\n *\n * Value: 365\n *\n * Used specifically for 12-month term duration calculations where the\n * protocol uses 365 days instead of 12 * 30 = 360 days.\n *\n * Governance-adjustable: NO (must match contract term definitions)\n */\nexport const DAYS_PER_YEAR = 365;\n", "/**\n * Lit Actions run under a strict JS execution budget on Lit nodes (~30\u201335s observed).\n * Unbounded `eth_call` / JSON-RPC waits can hang until the node kills the action with\n * `request_timeout`. Keep per-request RPC timeouts well below that budget.\n */\nexport const LIT_ACTION_ETH_RPC_TIMEOUT_MS = 8_000;\n", "/**\n * Auto-generated pinned deployment addresses for LIT Actions.\n * Generated by sdk/scripts/sync-deployments.js \u2014 DO NOT EDIT MANUALLY.\n *\n * Security-critical contract anchors, keyed by EVM chainId, that the\n * btc-transaction-signer LIT Action uses to REFUSE caller-supplied addresses on\n * enforced chains (sepolia/ethereum) \u2014 F1 remediation. Same deployment source\n * as the SDK's deployment-addresses.ts, so the two can never drift. Only chains\n * whose FULL anchor set is present are emitted; a chain absent here makes the\n * signer fail-closed (it throws rather than trusting caller-supplied values).\n */\n\nexport interface PinnedContractAddresses {\n /** PositionManager Diamond PROXY (stable across facet upgrades). */\n PositionManager: string;\n LoanOperationsManagerModule: string;\n BTCSpendAuthorizer: string;\n BitcoinProviderRegistry: string;\n LITActionValidator: string;\n PositionDelegateRegistry: string;\n /** Rate/term source for every signed loan attestation (pinned 2026-09-23). */\n TermManagerModule: string;\n /** UCD debt token controller (pinned 2026-09-23). */\n UCDController: string;\n /** Liquidation state the validators read and sign against (pinned 2026-09-23). */\n LiquidationManagerModule: string;\n}\n\nexport const PINNED_CONTRACT_ADDRESSES: Record<\n number,\n PinnedContractAddresses\n> = {\n 1: {\n PositionManager: \"0x12A1836e56139ccaD8722B89519d84233efc224B\",\n LoanOperationsManagerModule: \"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9\",\n BTCSpendAuthorizer: \"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a\",\n BitcoinProviderRegistry: \"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC\",\n LITActionValidator: \"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512\",\n PositionDelegateRegistry: \"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C\",\n TermManagerModule: \"0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E\",\n UCDController: \"0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157\",\n LiquidationManagerModule: \"0x74B28695352E7bf736D6c9F76ccb7B4439477De9\",\n },\n 11155111: {\n PositionManager: \"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF\",\n LoanOperationsManagerModule: \"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0\",\n BTCSpendAuthorizer: \"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD\",\n BitcoinProviderRegistry: \"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2\",\n LITActionValidator: \"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856\",\n PositionDelegateRegistry: \"0x482369De283622E7b05731875ec137d4E3D208F9\",\n TermManagerModule: \"0x94Adc6F9558368B1482197584f1fc7133Ecf835b\",\n UCDController: \"0x360Bde4e489ee94E26601B206932De09EE60FF04\",\n LiquidationManagerModule: \"0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76\",\n },\n};\n\n/**\n * Pinned security-critical addresses for a chainId, or null when the chain has\n * no complete pinned set. A null result MUST make the caller fail-closed on an\n * enforced chain \u2014 never fall through to caller-supplied addresses.\n */\nexport function getPinnedContractAddresses(\n chainId: number,\n): PinnedContractAddresses | null {\n return PINNED_CONTRACT_ADDRESSES[chainId] ?? null;\n}\n\n/**\n * Agent-path trust anchors (Safe-delegated withdrawal hardening, 2026-08-05)\n * \u2014 SEPARATE from PinnedContractAddresses above and NEVER merged into it.\n * `AgentModuleFactory` has no mainnet deployment yet (decision D-1,\n * deferred), so this map is emitted BEST EFFORT per chain: a chain may carry\n * only a partial (or empty) entry. An absent key MUST make the caller (the\n * Safe-agent authorization arm) fail closed \u2014 never fall through to a\n * caller-supplied value \u2014 but MUST NOT affect the ordinary borrower\n * withdrawal path, which reads only PinnedContractAddresses above.\n */\nexport interface AgentPathPinnedAddresses {\n /** CREATE2 factory a Safe uses to deploy its own AgentModule. Absent on mainnet until D-1 ships. */\n AgentModuleFactory?: string;\n /** Per-position agent grant registry (SCOPE_WITHDRAW, floor, TTL). */\n AgentDelegationRegistry?: string;\n /**\n * Per-wallet allowlist of approved BTC withdrawal destinations (24h time-lock).\n * The destination bound the Safe-agent withdrawal arm ENFORCES: a leaked agent\n * key can only pay out to an owner-approved address. Absent \u21D2 the agent arm\n * refuses (fail closed) \u2014 it must never be taken from the caller.\n */\n BitcoinWithdrawalAddressRegistry?: string;\n}\n\nexport const AGENT_PATH_PINNED_ADDRESSES: Record<\n number,\n AgentPathPinnedAddresses\n> = {\n 1: {\n AgentDelegationRegistry: \"0x54853b7E91ce2Be34ce65655D80c4447e67187Fa\",\n BitcoinWithdrawalAddressRegistry: \"0xf667f77FDba7458345f227eB6Bfe4148243E7270\",\n },\n 11155111: {\n AgentModuleFactory: \"0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5\",\n AgentDelegationRegistry: \"0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025\",\n BitcoinWithdrawalAddressRegistry: \"0x6376D392097F0A81e51BD83960A97EA20eaf1dbe\",\n },\n};\n\n/**\n * Agent-path trust anchors for a chainId, BEST EFFORT. Never throws and\n * never gates the ordinary borrower withdrawal path \u2014 an absent key (or an\n * absent chain, returning `{}`) means the Safe-agent authorization arm\n * must refuse on this chain.\n */\nexport function getAgentPathPinnedAddresses(\n chainId: number,\n): AgentPathPinnedAddresses {\n return AGENT_PATH_PINNED_ADDRESSES[chainId] ?? {};\n}\n", "/**\n * Domain strings for `MessageHashBuilder.sol` (OperationAuthorizationRegistry / PositionManager).\n *\n * **Single source of truth** for UTF-8 labels hashed to `bytes32` domain tags in LIT Actions.\n * Changing a value requires updating Solidity (`MessageHashBuilder.sol`) and re-running\n * `contracts` tests: `MessageHashBuilder.constants.unit.test.ts`.\n *\n * @see contracts/src/libraries/MessageHashBuilder.sol\n * @see contracts/docs/EIP712_DOMAIN_SPEC.md (EIP-712 domain.name / version / verifyingContract)\n */\n\n/** Matches `PAYMENT_ACTION_HASH` / `buildPaymentHash` */\nexport const MESSAGE_HASH_DOMAIN_PARTIAL_PAYMENT = \"partial-payment\";\n\n/** Matches `LIQUIDATION_ACTION_HASH` / `buildLiquidationHash` */\nexport const MESSAGE_HASH_DOMAIN_LIQUIDATION = \"liquidation\";\n\n/**\n * Shared EIP-712 `EIP712Domain.name` for protocol verifiers (PKPValidation, LiquidationManager, future LOM).\n * Distinct `DOMAIN_SEPARATOR` per `verifyingContract` proxy. @see contracts/docs/EIP712_DOMAIN_SPEC.md\n */\nexport const PROTOCOL_EIP712_DOMAIN_NAME = \"DiamondHands.Protocol\";\n\n/** Shared EIP-712 `EIP712Domain.version` until a breaking primary-type / field-order change. */\nexport const PROTOCOL_EIP712_DOMAIN_VERSION = \"1\";\n\n/** @deprecated Use PROTOCOL_EIP712_DOMAIN_NAME \u2014 identical. */\nexport const LIQUIDATION_MANAGER_EIP712_NAME = PROTOCOL_EIP712_DOMAIN_NAME;\n\n/** @deprecated Use PROTOCOL_EIP712_DOMAIN_VERSION \u2014 identical. */\nexport const LIQUIDATION_MANAGER_EIP712_VERSION = PROTOCOL_EIP712_DOMAIN_VERSION;\n\n/** Matches `EXTENSION_ACTION_HASH` / `buildExtensionHash` */\nexport const MESSAGE_HASH_DOMAIN_EXTEND_POSITION = \"extend-position\";\n\n/** Matches `BALANCE_CONFIRMATION_ACTION_HASH` / `buildBalanceConfirmationHash` */\nexport const MESSAGE_HASH_DOMAIN_BALANCE_CONFIRMATION = \"balance-confirmation\";\n\n/**\n * Action tag for the address-only `AddressBalanceAttestation` (btc-address-balance LIT Action).\n *\n * Deliberately DISTINCT from `MESSAGE_HASH_DOMAIN_BALANCE_CONFIRMATION`: that attestation is\n * position-bound and consumed on-chain by `PositionManager.updateBalance`. This one signs a raw\n * total chain balance for a bare Bitcoin address (no positionId, no authorized-spend subtraction)\n * and has NO Solidity counterpart in `MessageHashBuilder.sol` \u2014 there is no on-chain consumer. The\n * separate tag + a non-LOM `verifyingContract` guarantee the two digests can never collide, so an\n * address-balance signature can never be replayed as a protocol BalanceConfirmation.\n */\nexport const MESSAGE_HASH_DOMAIN_ADDRESS_BALANCE = \"address-balance\";\n\n/** Matches `MessageHashBuilder.MINT_ACTION_HASH` / `buildMintHash` */\nexport const MINT_ACTION_STRING = \"mint-ucd\";\n\n/** User authorization message action for BTC withdrawal (not a MessageHashBuilder domain tag). */\nexport const WITHDRAW_BTC_ACTION_STRING = \"withdraw-btc\";\n\n/**\n * User authorization message action for partial payment (not a MessageHashBuilder domain tag).\n *\n * Distinct from `MESSAGE_HASH_DOMAIN_PARTIAL_PAYMENT = \"partial-payment\"`, which is the EIP-712\n * inner-domain tag the Lit Action signs for on-chain consumption. The string below is what the\n * SDK writes into `authMessage.action` and what `process-payment-validator` pins before\n * accepting a user signature. Audit CRIT-5: the previous payment path called the agnostic base\n * verifier without pinning this string, which made `make-payment` signatures cross-action-\n * fungible with anything else built over the same digest shape.\n *\n * Wire-compat: the SDK has been signing `\"make-payment\"` since launch; do not change the value\n * here without a coordinated SDK release.\n */\nexport const PARTIAL_PAYMENT_ACTION_STRING = \"make-payment\";\n\n/**\n * User authorization message action for stale-spend recovery (audit #62210 Phase 2).\n *\n * Distinct action string so a leaked `withdraw-btc` signature cannot be replayed as a\n * recovery intent, and vice versa. Bound by `verifyRecoveryAuthorization` (in\n * `modules/authorization.module.ts`) into the borrower-signed message that the\n * `btc-utxo-invalidator` LIT Action consumes.\n */\nexport const RECOVERY_INVALIDATE_ACTION_STRING = \"btc-utxo-invalidator\";\n\n/**\n * Submission action string for the on-chain `cancelStaleSpendWithProof` call (audit #62210).\n * Used inside the LIT-signed `StaleSpendRecovery` attestation domain \u2014 purely informational\n * (the EIP-712 type provides the cryptographic binding); kept for debug/log greppability.\n */\nexport const RECOVERY_ATTEST_ACTION_STRING = \"stale-spend-recovery\";\n", "/**\n * EIP-712 type definitions for **borrower** authorization messages.\n *\n * **Single source of truth.** The SDK builds these messages and the LIT Actions\n * verify them; both import from this module so the two can never drift. A digest\n * kept in sync by comment is a digest that will eventually disagree \u2014 and a\n * disagreement here does not degrade, it rejects every signature in flight.\n *\n * ## What these are\n *\n * The prompt a borrower sees BEFORE the on-chain transaction. Today the SDK\n * collapses the field set into one `keccak256` digest and calls `personal_sign`\n * over the 32 bytes, so the wallet renders an opaque hash and no ERC-7730\n * descriptor can help it \u2014 the preimage never reaches the wallet. Encoding the\n * same fields as typed data is what makes the values renderable.\n *\n * ## No Solidity counterpart \u2014 deliberately\n *\n * Unlike `./message-hash-domains`, nothing here mirrors a constant in\n * `MessageHashBuilder.sol`, and no contract recomputes these digests. The\n * borrower signature is consumed entirely in `modules/authorization.module.ts`\n * and never reaches Solidity: `PositionManager.mintUCD` takes exactly one\n * signature \u2014 `mintValidatorSignature` \u2014 checked against\n * `loanOps.eip712DigestMintUcd(...)` (`PositionManager.sol:1071`), which is the\n * **validator PKP's** attestation, a different signer over a different digest.\n * That is why this lives in its own module rather than alongside the\n * MessageHashBuilder domain tags: someone reading those constants is entitled\n * to assume a Solidity counterpart exists, and for these there is none to find.\n *\n * ## Naming: `*Request` vs the validator types\n *\n * Owner-signed types are `*Request`; validator-signed types keep their existing\n * names. `WithdrawRequest` sits one letter from\n * `LoanOperationsManager.WITHDRAWAL_AUTHORIZATION_TYPEHASH`'s\n * `WithdrawalAuthorization` **on purpose** \u2014 different signer, different digest,\n * deliberately non-colliding. Do not \"tidy\" the two into one name.\n *\n * @see clear-signing/registry/diamond-hands/eip712-LoanOperationsManager.json \u2014 the ERC-7730\n * descriptor, whose format keys are these `encodeType` strings verbatim.\n * Changing a type string here invalidates that descriptor.\n * @see contracts/docs/EIP712_DOMAIN_SPEC.md \u00A74.1 \u2014 descriptor maintenance coupling.\n */\n\nimport { getPinnedContractAddresses } from \"./chunks/deployment-addresses\";\nimport {\n PROTOCOL_EIP712_DOMAIN_NAME,\n PROTOCOL_EIP712_DOMAIN_VERSION,\n} from \"./message-hash-domains\";\n\n/** One EIP-712 struct member. Shape is compatible with both ethers v5 and v6. */\nexport interface BorrowerAuthorizationField {\n readonly name: string;\n readonly type: string;\n}\n\n/**\n * The four owner-signed primary types, one per loan operation.\n *\n * `execute-btc-withdrawal` and `btc-utxo-invalidator` are absent on purpose:\n * they belong to the BTCSpendAuthorizer domain, not LoanOperationsManager, so\n * they cannot share this `verifyingContract`.\n */\nexport const BORROWER_AUTHORIZATION_PRIMARY_TYPES = {\n MINT: \"MintRequest\",\n REPAY: \"RepayRequest\",\n RENEW: \"RenewRequest\",\n WITHDRAW: \"WithdrawRequest\",\n} as const;\n\nexport type BorrowerAuthorizationPrimaryType =\n (typeof BORROWER_AUTHORIZATION_PRIMARY_TYPES)[keyof typeof BORROWER_AUTHORIZATION_PRIMARY_TYPES];\n\n/**\n * Field lists per primary type. **Order is part of the digest** \u2014 appending,\n * reordering, or renaming a member changes every signature this protocol\n * produces and invalidates the ERC-7730 descriptor in the same step.\n *\n * `quantumTimestamp` is last in all four so the fields a user actually chose\n * (amount, destination) render before protocol bookkeeping on a device that\n * truncates.\n */\nexport const BORROWER_AUTHORIZATION_FIELDS: Readonly<\n Record<BorrowerAuthorizationPrimaryType, readonly BorrowerAuthorizationField[]>\n> = {\n MintRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"mintAmount\", type: \"uint256\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n RepayRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"paymentAmount\", type: \"uint256\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n RenewRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"selectedTerm\", type: \"uint256\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n WithdrawRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"totalDeduction\", type: \"uint256\" },\n { name: \"withdrawalAddress\", type: \"string\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n} as const;\n\n/**\n * Frozen `encodeType` strings \u2014 the EIP-712 typehash preimages.\n *\n * Duplicated from the field lists ON PURPOSE. These are the exact keys of\n * `display.formats` in `eip712-LoanOperationsManager.json`, so writing them out\n * literally lets a test compare descriptor to code as plain strings, with no\n * derivation step that could be wrong in both places at once. The unit suite\n * asserts these match what an encoder derives from\n * `BORROWER_AUTHORIZATION_FIELDS`; they are not trusted to agree by inspection.\n */\nexport const BORROWER_AUTHORIZATION_ENCODE_TYPES: Readonly<\n Record<BorrowerAuthorizationPrimaryType, string>\n> = {\n MintRequest:\n \"MintRequest(bytes32 positionId,uint256 mintAmount,uint256 quantumTimestamp)\",\n RepayRequest:\n \"RepayRequest(bytes32 positionId,uint256 paymentAmount,uint256 quantumTimestamp)\",\n RenewRequest:\n \"RenewRequest(bytes32 positionId,uint256 selectedTerm,uint256 quantumTimestamp)\",\n WithdrawRequest:\n \"WithdrawRequest(bytes32 positionId,uint256 totalDeduction,string withdrawalAddress,uint256 quantumTimestamp)\",\n} as const;\n\n/** EIP-712 domain for borrower authorizations. `verifyingContract` is the LOM proxy. */\nexport interface BorrowerAuthorizationDomain {\n readonly name: string;\n readonly version: string;\n readonly chainId: number;\n readonly verifyingContract: string;\n}\n\n/**\n * The `types` argument for `TypedDataEncoder.hash(domain, types, message)`.\n *\n * Returns ONLY the requested primary type. Handing an encoder a map containing\n * all four would still hash correctly, but it would let a caller pass a message\n * shaped like a different operation and have it encode without complaint \u2014 so\n * the narrow map is the safer default, not a convenience.\n *\n * Returns mutable copies: ethers v6 types `TypedDataField[]` as mutable, and a\n * `readonly` array is not assignable to it.\n *\n * @throws if `primaryType` is not one of the four. No fallback \u2014 an unknown\n * operation must not silently acquire a digest.\n */\nexport function borrowerAuthorizationTypes(\n primaryType: BorrowerAuthorizationPrimaryType,\n): Record<string, BorrowerAuthorizationField[]> {\n const fields = BORROWER_AUTHORIZATION_FIELDS[primaryType];\n if (!fields) {\n throw new Error(\n `Unknown borrower authorization primary type \"${primaryType}\"; ` +\n `expected one of ${Object.keys(BORROWER_AUTHORIZATION_FIELDS).join(\", \")}`,\n );\n }\n return { [primaryType]: fields.map((field) => ({ ...field })) };\n}\n\n/**\n * Build the EIP-712 domain for a chain.\n *\n * `verifyingContract` resolves from `PINNED_CONTRACT_ADDRESSES`, the map\n * `sdk/scripts/sync-deployments.js` generates from the deployment files \u2014 the\n * same source the SDK uses, so a redeploy cannot desync the two sides of the\n * digest. It is deliberately NOT a caller-supplied parameter by default: a\n * domain taken from `jsParams` is a domain an attacker chooses, and the\n * verifying side would then validate a signature the borrower never scoped to\n * this protocol.\n *\n * `verifyingContractOverride` exists for chains with no pinned set \u2014 hardhat in\n * the test suite. On a pinned chain it is CHECKED, not honoured: supplying a\n * value that contradicts the pin throws, mirroring\n * `resolveSecurityCriticalAddresses` (`modules/pinned-addresses.ts`), which\n * surfaces a malicious or misconfigured caller instead of quietly ignoring them.\n *\n * @throws if the chain has no pinned LOM address and no override is supplied.\n * @throws if an override contradicts the pinned address for that chain.\n */\nexport function buildBorrowerAuthorizationDomain(\n chainId: number,\n verifyingContractOverride?: string,\n): BorrowerAuthorizationDomain {\n if (!Number.isInteger(chainId) || chainId <= 0) {\n throw new Error(\n `Borrower authorization domain requires a positive integer chainId, got ${String(chainId)}`,\n );\n }\n\n const pinned = getPinnedContractAddresses(chainId);\n const pinnedLom = pinned?.LoanOperationsManagerModule;\n\n if (pinnedLom && verifyingContractOverride) {\n if (pinnedLom.toLowerCase() !== verifyingContractOverride.toLowerCase()) {\n throw new Error(\n `Refusing a caller-supplied verifyingContract that contradicts the pin for chainId ${chainId}: ` +\n `caller ${verifyingContractOverride}, pinned ${pinnedLom}`,\n );\n }\n }\n\n const verifyingContract = pinnedLom ?? verifyingContractOverride;\n if (!verifyingContract) {\n throw new Error(\n `No pinned LoanOperationsManagerModule for chainId ${chainId} and no verifyingContract supplied; ` +\n `refusing to build a borrower authorization domain without one`,\n );\n }\n\n return {\n name: PROTOCOL_EIP712_DOMAIN_NAME,\n version: PROTOCOL_EIP712_DOMAIN_VERSION,\n chainId,\n verifyingContract,\n };\n}\n", "/**\n * Bitcoin Network Configuration\n *\n * Defines approved Bitcoin RPC providers and network mappings for the protocol.\n * This ensures LIT actions only use vetted, reliable Bitcoin data sources.\n *\n * CRITICAL: Only approved providers should be added to this configuration.\n */\n\n/**\n * Supported EVM chains\n */\nexport enum EVMChain {\n /** Ethereum Sepolia testnet */\n SEPOLIA = \"sepolia\",\n\n /** Ethereum mainnet */\n ETHEREUM = \"ethereum\",\n\n /** Hardhat local testnet */\n HARDHAT = \"hardhat\",\n}\n\n/**\n * Bitcoin network types\n */\nexport enum BitcoinNetwork {\n /** Bitcoin testnet */\n TESTNET = \"testnet\",\n\n /** Bitcoin mainnet */\n MAINNET = \"mainnet\",\n\n /** Bitcoin regtest (local/testing) */\n REGTEST = \"regtest\",\n}\n\nimport type { ProviderAuth } from \"../../modules/bitcoin-provider-auth\";\n\n/**\n * Bitcoin provider configuration\n */\nexport interface BitcoinProviderConfig {\n /** Provider API URL */\n url: string;\n\n /** Bitcoin network (testnet or mainnet) */\n network: BitcoinNetwork;\n\n /**\n * Balance-confirmation threshold stamped from\n * `policy.minBitcoinBalanceConfirmations` by the provider registry. NEVER use\n * this to gate UTXO spends \u2014 spends must use\n * `policy.minBitcoinSpendConfirmations` directly.\n */\n minConfirmations: number;\n\n /** Human-readable provider name */\n name: string;\n\n /**\n * Auth descriptor for the provider's Esplora API. Absent \u21D2 no auth (public\n * Esplora / regtest faucet). Populated from the decrypted registry blob for\n * commercial providers (Maestro api-key, Blockstream Enterprise OAuth).\n */\n auth?: ProviderAuth;\n}\n\n/**\n * Mapping from EVM chain to Bitcoin network\n *\n * - Sepolia \u2192 Bitcoin Regtest (Diamond Hands uses a private regtest faucet for Sepolia testing)\n * - Ethereum (mainnet) \u2192 Bitcoin Mainnet\n *\n * NOTE: Sepolia maps to REGTEST (not TESTNET) because Diamond Hands uses a private\n * regtest Bitcoin node (regtest.diamondhands.credit) for Sepolia E2E testing.\n * Vault addresses are bcrt1q\u2026 (regtest prefix). Changing to TESTNET would cause\n * deriveBitcoinAddress to produce tb1q\u2026 addresses instead of the vault's bcrt1q\u2026 format,\n * and PSBT assembly to use bitcoin.networks.testnet which can silently corrupt the\n * broadcast flow when the endpoint returns an empty 200 body.\n */\nexport const CHAIN_TO_BITCOIN_NETWORK: Record<EVMChain, BitcoinNetwork> = {\n [EVMChain.SEPOLIA]: BitcoinNetwork.REGTEST,\n [EVMChain.ETHEREUM]: BitcoinNetwork.MAINNET,\n [EVMChain.HARDHAT]: BitcoinNetwork.REGTEST, // Local development\n};\n\n/**\n * Approved EVM RPC provider domains\n *\n * Only RPC providers whose hostnames match one of these domain suffixes are\n * permitted inside LIT Actions for Ethereum/EVM calls. Adding a provider\n * here requires a security review \u2014 untrusted RPCs can return manipulated\n * state and compromise validator logic.\n *\n * Governance-adjustable: YES (add/remove after security review)\n *\n * `drpc.live` added 2026-10-18 after review: it is dRPC's optimized load\n * balancer (ownership confirmed by the Master); `drpc.org` is its legacy host.\n */\nexport const APPROVED_EVM_RPC_DOMAINS = [\"infura.io\", \"drpc.org\", \"drpc.live\"];\n\n/**\n * Mapping from EVM chain to chain ID\n *\n * - Ethereum mainnet: 1\n * - Sepolia testnet: 11155111\n * - Hardhat local: 1337 (matches contracts/hardhat.config.ts)\n */\nexport const CHAIN_TO_CHAIN_ID: Record<EVMChain, number> = {\n [EVMChain.ETHEREUM]: 1,\n [EVMChain.SEPOLIA]: 11155111,\n [EVMChain.HARDHAT]: 1337,\n};\n\n/**\n * Approved Bitcoin RPC providers per network\n *\n * Only providers in this whitelist can be used by LIT actions.\n * Each provider has specific min confirmation requirements.\n *\n * TESTNET: Lower confirmation requirements (1 block)\n * REGTEST: Lower confirmation requirements (1 block)\n * MAINNET: Higher confirmation requirements (6 blocks - industry standard)\n */\nexport const APPROVED_BITCOIN_PROVIDERS: Record<\n BitcoinNetwork,\n BitcoinProviderConfig[]\n> = {\n [BitcoinNetwork.REGTEST]: [\n {\n url: \"https://regtest.diamondhands.credit/api/esplora\",\n network: BitcoinNetwork.REGTEST,\n minConfirmations: 1,\n name: \"Diamond Hands\",\n },\n {\n url: \"http://127.0.0.1:18443\",\n network: BitcoinNetwork.REGTEST,\n minConfirmations: 1,\n name: \"Local Regtest\",\n },\n {\n url: \"https://313561dc30c5.ngrok-free.app\",\n network: BitcoinNetwork.REGTEST,\n minConfirmations: 1,\n name: \"Ngrok Bitcoin Tunnel\",\n },\n ],\n // TESTNET and MAINNET allowlists are intentionally empty in source.\n // Provider URLs are stored encrypted on-chain in BitcoinProviderRegistry\n // and fetched at runtime via `Lit.Actions.Decrypt` (see\n // modules/bitcoin-provider-registry.ts). Hardcoding URLs here would leak\n // internal infrastructure \u2014 the faucet URLs that were previously in this\n // file were visible in the IPFS-pinned LIT Action bundle and in GitHub.\n // (audit C-1 / H-6 fix)\n [BitcoinNetwork.TESTNET]: [],\n [BitcoinNetwork.MAINNET]: [],\n};\n\n/**\n * Validate and normalize EVM chain input\n *\n * @param chain Chain identifier (case-insensitive)\n * @returns Validated EVMChain enum value\n * @throws Error if chain is not supported\n */\nexport function validateChain(chain: string): EVMChain {\n const normalized = chain.toLowerCase().trim();\n\n if (normalized === \"sepolia\") {\n return EVMChain.SEPOLIA;\n }\n\n if (normalized === \"ethereum\" || normalized === \"mainnet\") {\n return EVMChain.ETHEREUM;\n }\n\n if (normalized === \"hardhat\") {\n return EVMChain.HARDHAT;\n }\n\n throw new Error(\n `Unsupported EVM chain: \"${chain}\". ` +\n `Supported chains: ${Object.values(EVMChain).join(\", \")}`\n );\n}\n\n/**\n * Get Bitcoin network for EVM chain\n *\n * @param chain EVM chain\n * @returns Corresponding Bitcoin network\n */\nexport function getBitcoinNetworkForChain(chain: EVMChain): BitcoinNetwork {\n return CHAIN_TO_BITCOIN_NETWORK[chain];\n}\n\n/**\n * Get chain ID for EVM chain\n *\n * @param chain EVM chain\n * @returns Corresponding chain ID\n */\nexport function getChainIdForChain(chain: EVMChain): number {\n return CHAIN_TO_CHAIN_ID[chain];\n}\n\n/**\n * Validate Bitcoin provider is approved for network\n *\n * @param providerUrl Bitcoin provider URL\n * @param bitcoinNetwork Bitcoin network (testnet or mainnet)\n * @returns Provider configuration if approved\n * @throws Error if provider is not approved for network\n */\nexport function validateBitcoinProvider(\n providerUrl: string,\n bitcoinNetwork: BitcoinNetwork\n): BitcoinProviderConfig {\n const providers = APPROVED_BITCOIN_PROVIDERS[bitcoinNetwork];\n const config = providers.find((p) => p.url === providerUrl);\n\n if (!config) {\n const approvedUrls = providers\n .map((p) => `${p.name} (${p.url})`)\n .join(\", \");\n throw new Error(\n `Bitcoin provider not approved for ${bitcoinNetwork}. ` +\n `Provided URL: ${providerUrl}. ` +\n `Approved providers: ${approvedUrls}`\n );\n }\n\n return config;\n}\n\n/**\n * Validate Bitcoin provider is approved\n *\n * Searches across all networks to find the provider.\n * In development mode, the caller should create their own config directly\n * (see mint/withdraw validators for the pattern).\n *\n * @param providerUrl Bitcoin provider URL\n * @returns Provider configuration with network auto-detected\n * @throws Error if provider is not approved for any network\n */\nexport function getBitcoinProviderConfig(\n providerUrl: string\n): BitcoinProviderConfig {\n // Search across ALL networks to find this provider\n for (const network of Object.values(BitcoinNetwork)) {\n const providers = APPROVED_BITCOIN_PROVIDERS[network];\n const config = providers.find((p) => p.url === providerUrl);\n\n if (config) {\n // Found it - return with network detected\n return config;\n }\n }\n\n // Provider not found in any network\n const allProviders = Object.entries(APPROVED_BITCOIN_PROVIDERS)\n .flatMap(([network, providers]) =>\n providers.map((p) => `${network}: ${p.name} (${p.url})`)\n )\n .join(\", \");\n\n throw new Error(\n `Bitcoin provider not approved. ` +\n `Provided URL: ${providerUrl}. ` +\n `Approved providers: ${allProviders}`\n );\n}\n\n/**\n * Get list of approved provider URLs for a chain\n *\n * Useful for displaying options to users or validating inputs.\n *\n * @param chain EVM chain\n * @returns Array of approved provider URLs for that chain's Bitcoin network\n */\nexport function getApprovedProvidersForChain(chain: EVMChain): string[] {\n const bitcoinNetwork = getBitcoinNetworkForChain(chain);\n return APPROVED_BITCOIN_PROVIDERS[bitcoinNetwork].map((p) => p.url);\n}\n\n/**\n * Get human-readable provider name from URL\n *\n * @param providerUrl Provider URL\n * @param bitcoinNetwork Bitcoin network\n * @returns Provider name or URL if not found\n */\nexport function getProviderName(\n providerUrl: string,\n bitcoinNetwork: BitcoinNetwork\n): string {\n const config = APPROVED_BITCOIN_PROVIDERS[bitcoinNetwork].find(\n (p) => p.url === providerUrl\n );\n return config ? config.name : providerUrl;\n}\n", "/**\n * Business Rules Math Module\n *\n * Pure calculation functions for Diamond Hands Protocol business logic.\n * These functions contain no side effects - they only perform calculations.\n *\n * Used by vault-snapshot and other modules for consistent math across the system.\n */\n\nimport {\n BASIS_POINTS_DENOMINATOR,\n EXPIRED_LOAN_MAX_ESCALATION_ITERATIONS,\n EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS,\n SATOSHIS_PER_BITCOIN,\n PRICE_ORACLE_DECIMALS,\n UCD_TOKEN_DECIMALS,\n SECONDS_PER_DAY,\n DAYS_PER_MONTH,\n} from \"../constants\";\n\n/**\n * Calculate term start timestamp from expiry timestamp and term length\n *\n * Contract stores expiryAt but not termStartTimestamp.\n * We derive it: termStart = expiry - (termLength * 30 days)\n *\n * Uses constants to avoid magic numbers and ensure accuracy.\n *\n * @param expiryTimestamp - Unix timestamp when term expires (0 if no term)\n * @param termLengthMonths - Term length in months\n * @returns Unix timestamp when term started (0 if no term)\n */\nexport function calculateTermStartFromExpiry(\n expiryTimestamp: number,\n termLengthMonths: number\n): number {\n // No term started if expiryAt is 0\n if (expiryTimestamp === 0) {\n return 0;\n }\n\n\n // Calculate term start\n // termStart = expiry - (months * 30 days/month * 86400 seconds/day)\n const termDurationSeconds =\n termLengthMonths * DAYS_PER_MONTH * SECONDS_PER_DAY;\n\n return expiryTimestamp - termDurationSeconds;\n}\n\n/**\n * Calculate term status from timestamps\n *\n * Determines:\n * - How long into the term we are\n * - Whether term is expired\n * - Days until expiry or days into grace period\n *\n * @param termStartTimestamp - Unix timestamp when term started (0 if not started)\n * @param selectedTermMonths - Term length in months\n * @returns Complete term status metrics\n */\nexport function calculateTermStatus(\n termStartTimestamp: number,\n selectedTermMonths: number\n): {\n termDurationDays: number;\n termLengthDays: number;\n isExpired: boolean;\n daysUntilExpiry: number;\n daysIntoGracePeriod: number;\n} {\n // If no term started yet (no debt), return zeros\n if (termStartTimestamp === 0) {\n return {\n termDurationDays: 0,\n termLengthDays: selectedTermMonths * 30,\n isExpired: false,\n daysUntilExpiry: selectedTermMonths * 30,\n daysIntoGracePeriod: 0,\n };\n }\n\n const now = Math.floor(Date.now() / 1000);\n const termLengthDays = selectedTermMonths * DAYS_PER_MONTH;\n const termDurationSeconds = now - termStartTimestamp;\n const termDurationDays = Math.floor(termDurationSeconds / SECONDS_PER_DAY);\n\n const isExpired = termDurationDays > termLengthDays;\n const daysUntilExpiry = Math.max(0, termLengthDays - termDurationDays);\n const daysIntoGracePeriod = Math.max(0, termDurationDays - termLengthDays);\n\n return {\n termDurationDays,\n termLengthDays,\n isExpired,\n daysUntilExpiry,\n daysIntoGracePeriod,\n };\n}\n\n/**\n * Expired-loan escalation parameters, read from LiquidationManager on-chain.\n */\nexport interface ExpiredLoanEscalationParams {\n /** `LiquidationManager.expiryLiquidationIncrementBps` \u2014 compound daily increment. */\n dailyIncrementBps: number;\n /** `LiquidationManager.expiredLoanGracePeriodDays` \u2014 days after expiry before escalation starts. */\n gracePeriodDays: number;\n /** `LiquidationManager.maxEscalatedThreshold` \u2014 cap in basis points. */\n maxEscalatedThresholdBps: number;\n}\n\nfunction requireNonNegativeInteger(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(\n `calculateLiquidationThreshold: ${name} must be a non-negative integer, got ${String(value)}`,\n );\n }\n}\n\n/**\n * Calculate the liquidation threshold in effect for a position.\n *\n * Active loan: the on-chain `LoanOperationsManager.liquidationThreshold()`.\n *\n * Expired loan: a transcription of the contract's\n * `ExpiredLoanCalculator.isExpiredLoanLiquidatableDynamic` (aligned 2026-10-27;\n * the previous quadratic 30-day curve signed liquidations the contract then\n * rejected, and refused ones it would have allowed):\n * - up to and including `gracePeriodDays` after expiry: the hardcoded 110% base;\n * - then, per escalation day, `t = floor(t * (1e4 + inc) / 1e4)`, capped at max;\n * - 365 or more escalation days clamp straight to max.\n * The Lean model `DH/Collateral.lean` (`litThreshold`) evaluates the same loop\n * and `tests/unit/lean-vectors.unit.test.ts` replays its vectors against this.\n *\n * @param isExpired - Whether the loan term has expired\n * @param daysSinceExpiry - Whole days past expiry (0 if not expired)\n * @param activeLoanThresholdBps - On-chain active-loan threshold\n * @param escalation - On-chain escalation parameters\n * @returns Liquidation threshold in basis points\n */\nexport function calculateLiquidationThreshold(\n isExpired: boolean,\n daysSinceExpiry: number,\n activeLoanThresholdBps: number,\n escalation: ExpiredLoanEscalationParams\n): number {\n if (!isExpired) {\n return activeLoanThresholdBps;\n }\n\n requireNonNegativeInteger(\"daysSinceExpiry\", daysSinceExpiry);\n requireNonNegativeInteger(\"dailyIncrementBps\", escalation.dailyIncrementBps);\n requireNonNegativeInteger(\"gracePeriodDays\", escalation.gracePeriodDays);\n requireNonNegativeInteger(\"maxEscalatedThresholdBps\", escalation.maxEscalatedThresholdBps);\n\n if (daysSinceExpiry <= escalation.gracePeriodDays) {\n return EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS;\n }\n\n const escalationDays = daysSinceExpiry - escalation.gracePeriodDays;\n if (escalationDays >= EXPIRED_LOAN_MAX_ESCALATION_ITERATIONS) {\n return escalation.maxEscalatedThresholdBps;\n }\n\n // Integer arithmetic throughout: every intermediate is below 2^53\n // (threshold <= max <= 1e9 and multiplier <= 2e4 keep the product under 2e13).\n const multiplier = BASIS_POINTS_DENOMINATOR + escalation.dailyIncrementBps;\n let threshold = EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS;\n for (let i = 0; i < escalationDays; i++) {\n threshold = Math.floor((threshold * multiplier) / BASIS_POINTS_DENOMINATOR);\n if (threshold >= escalation.maxEscalatedThresholdBps) {\n return escalation.maxEscalatedThresholdBps;\n }\n }\n return threshold;\n}\n\n/**\n * Calculate collateral metrics from BTC balance and debt\n *\n * Converts BTC balance to USD value and calculates collateral ratio.\n * Uses BigInt for all calculations to avoid JavaScript number precision issues.\n *\n * @param availableBTCSats - Available BTC balance in satoshis\n * @param btcPriceUsd - BTC price with 8 decimals (e.g., 10000000000000 = $100,000)\n * @param ucdDebt - UCD debt in wei (18 decimals)\n * @returns Collateral value in USD and ratio in basis points\n */\nexport function calculateCollateralMetrics(\n availableBTCSats: bigint,\n btcPriceUsd: bigint,\n ucdDebt: bigint\n): {\n collateralValueUsd: bigint;\n collateralRatioBps: number;\n} {\n // Convert available BTC to USD value using BigInt math\n // btcPriceUsd has 8 decimals: $100,000 = 10000000000000n\n // availableBTCSats is in satoshis: 1 BTC = 100_000_000n sats\n // ucdDebt has 18 decimals (ERC20 wei)\n //\n // Formula: (sats * priceWith8Decimals) / (SATOSHIS_PER_BITCOIN * PRICE_ORACLE_DECIMALS)\n // This gives us USD value with 0 decimals (whole dollars)\n\n // Calculate collateral value in USD (no decimals) - ALWAYS calculate, even with no debt\n const collateralValueUsd =\n (availableBTCSats * btcPriceUsd) /\n (SATOSHIS_PER_BITCOIN * PRICE_ORACLE_DECIMALS);\n\n // If no debt, return max safe collateral ratio\n if (ucdDebt === 0n) {\n return {\n collateralValueUsd,\n collateralRatioBps: Number.MAX_SAFE_INTEGER,\n };\n }\n\n // Calculate collateral ratio in basis points\n // Ratio = (collateral / debt) * 10000\n // Example: $20,000 collateral / $10,000 debt = 2.0 = 20000 bps (200%)\n //\n // CRITICAL: We must preserve precision by doing multiplication BEFORE division\n // Use debt in wei (18 decimals) directly, adjust for collateral being in whole dollars\n //\n // Formula: (collateralUSD * UCD_TOKEN_DECIMALS * 10000) / ucdDebt\n\n const ratioBigInt =\n (collateralValueUsd * UCD_TOKEN_DECIMALS * 10000n) / ucdDebt;\n\n // Convert to number - safe because ratio will be small (typically 10000-30000)\n const collateralRatioBps = Number(ratioBigInt);\n\n return {\n collateralValueUsd,\n collateralRatioBps,\n };\n}\n\n/**\n * Check if adding additional debt would maintain required collateral ratio\n *\n * Used by minting authorization to validate new mints.\n *\n * @param collateralValueUsd - Current collateral value in USD (whole dollars)\n * @param currentDebt - Current UCD debt in wei (18 decimals)\n * @param additionalDebt - Additional UCD debt to add in wei (18 decimals)\n * @param requiredRatioBps - Required collateral ratio in basis points (e.g., 11000 for 110%)\n * @returns True if sufficient collateral exists after adding debt\n */\nexport function hasSufficientCollateralForDebt(\n collateralValueUsd: bigint,\n currentDebt: bigint,\n additionalDebt: bigint,\n requiredRatioBps: number\n): boolean {\n // Calculate new total debt\n const newTotalDebt = currentDebt + additionalDebt;\n\n // If no debt after addition, always sufficient\n if (newTotalDebt === 0n) {\n return true;\n }\n\n // Calculate new collateral ratio using precise BigInt math\n // Must multiply BEFORE dividing to preserve precision (same as calculateCollateralMetrics)\n const newCollateralRatioBps = Number(\n (collateralValueUsd * UCD_TOKEN_DECIMALS * 10000n) / newTotalDebt\n );\n\n return newCollateralRatioBps >= requiredRatioBps;\n}\n\n/**\n * Calculate fee from amount using basis points\n *\n * Bulletproof fee calculation with validation.\n * Multiply before divide to maintain precision.\n *\n * @param amount - Principal amount (in wei or sats)\n * @param feeBps - Fee in basis points (e.g., 50 = 0.5%)\n * @returns Fee amount in same units as input\n *\n * @example\n * calculateFeeBps(1000000000000000000n, 50) // 0.5% of 1 ETH\n * // Returns: 5000000000000000n (0.005 ETH)\n */\nexport function calculateFeeBps(amount: bigint, feeBps: number): bigint {\n if (amount < 0n) {\n throw new Error(\"Amount cannot be negative\");\n }\n if (feeBps < 0 || feeBps > 10000) {\n throw new Error(\n \"Fee basis points must be between 0 and 10000 (0% to 100%)\"\n );\n }\n\n // Multiply first to preserve precision, then divide\n const fee = (amount * BigInt(feeBps)) / 10000n;\n return fee;\n}\n\n/**\n * Calculate USD value of BTC amount\n *\n * Converts satoshis to USD using price with 8 decimals.\n * Result maintains 8 decimal precision.\n *\n * @param btcSats - Bitcoin amount in satoshis\n * @param btcPriceUsd8Decimals - BTC price with 8 decimals (e.g., 9800000000000n = $98,000)\n * @returns USD value with 8 decimals\n *\n * @example\n * calculateBtcValueUsd(100000000n, 9800000000000n) // 1 BTC at $98,000\n * // Returns: 9800000000000n ($98,000 with 8 decimals)\n */\nexport function calculateBtcValueUsd(\n btcSats: bigint,\n btcPriceUsd8Decimals: bigint\n): bigint {\n if (btcSats < 0n) {\n throw new Error(\"BTC amount cannot be negative\");\n }\n if (btcPriceUsd8Decimals <= 0n) {\n throw new Error(\"BTC price must be positive\");\n }\n\n // btcSats: satoshis (no decimals)\n // btcPriceUsd8Decimals: price with 8 decimals\n // Formula: (sats * priceWith8Decimals) / SATOSHIS_PER_BITCOIN\n // Result: USD value with 8 decimals\n const valueUsd = (btcSats * btcPriceUsd8Decimals) / SATOSHIS_PER_BITCOIN;\n return valueUsd;\n}\n\n/**\n * Calculate collateral ratio in basis points (with 8-decimal collateral and 18-decimal debt)\n *\n * Used for UCD mint validation where collateral is in USD (8 decimals)\n * and debt is in UCD wei (18 decimals).\n *\n * @param collateralValueUsd8Decimals - Collateral value in USD with 8 decimals\n * @param debtUsd18Decimals - Debt amount in USD with 18 decimals (UCD wei)\n * @returns Collateral ratio in basis points (e.g., 20000 = 200%)\n *\n * @example\n * calculateCollateralRatioBps(9800000000000n, 4000000000000000000000n)\n * // $98,000 collateral / $4,000 debt = 24.5 = 2450% = 24500 bps\n * // Returns: 24500\n *\n * Note: Returns MAX_SAFE_INTEGER for extreme over-collateralization cases\n */\nexport function calculateCollateralRatioBps(\n collateralValueUsd8Decimals: bigint,\n debtUsd18Decimals: bigint\n): number {\n if (collateralValueUsd8Decimals < 0n) {\n throw new Error(\"Collateral value cannot be negative\");\n }\n if (debtUsd18Decimals <= 0n) {\n throw new Error(\"Debt must be positive to calculate ratio\");\n }\n\n // Scale collateral from 8 decimals to 18 decimals: multiply by 10^10\n const scaledCollateral = collateralValueUsd8Decimals * 10000000000n;\n\n // Ratio in basis points = (collateral / debt) * 10000\n // Multiply first to preserve precision\n const ratioBps = (scaledCollateral * 10000n) / debtUsd18Decimals;\n\n // Convert to number for comparison\n const ratioBpsNumber = Number(ratioBps);\n\n // Sanity check: ratio should be non-negative\n // Cap at MAX_SAFE_INTEGER for extreme over-collateralization (prevents Infinity)\n if (ratioBpsNumber < 0) {\n throw new Error(\n `Collateral ratio out of bounds: ${ratioBpsNumber} bps (${\n ratioBpsNumber / 100\n }%)`\n );\n }\n\n // Cap at MAX_SAFE_INTEGER to prevent Infinity edge cases\n if (!isFinite(ratioBpsNumber) || ratioBpsNumber > Number.MAX_SAFE_INTEGER) {\n return Number.MAX_SAFE_INTEGER;\n }\n\n return ratioBpsNumber;\n}\n\n/**\n * Check if collateral ratio meets minimum requirement\n *\n * @param collateralValueUsd8Decimals - Collateral value in USD with 8 decimals\n * @param debtUsd18Decimals - Debt amount in USD with 18 decimals\n * @param minimumRatioBps - Minimum required ratio in basis points (e.g., 20000 = 200%)\n * @returns True if collateral is sufficient\n *\n * @example\n * isCollateralSufficient(20000000000000n, 10000000000000000000000n, 20000)\n * // $200,000 collateral / $10,000 debt = 2000% >= 200%\n * // Returns: true\n */\nexport function isCollateralSufficient(\n collateralValueUsd8Decimals: bigint,\n debtUsd18Decimals: bigint,\n minimumRatioBps: number\n): boolean {\n if (minimumRatioBps < 0 || minimumRatioBps > 1000000) {\n throw new Error(\n \"Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)\"\n );\n }\n\n const actualRatioBps = calculateCollateralRatioBps(\n collateralValueUsd8Decimals,\n debtUsd18Decimals\n );\n\n return actualRatioBps >= minimumRatioBps;\n}\n\n/**\n * Convert basis points to percentage (for display)\n *\n * @param basisPoints - Value in basis points\n * @returns Percentage as number (e.g., 20000 bps => 200)\n *\n * @example\n * bpsToPercent(20000) // Returns: 200\n * bpsToPercent(50) // Returns: 0.5\n */\nexport function bpsToPercent(basisPoints: number): number {\n return basisPoints / 100;\n}\n\n/**\n * Refuse an AGENT-authorized withdrawal that would take the position below the borrower's\n * delegation floor.\n *\n * WHY THIS IS A NAMED FUNCTION. It is the enforcement point whose absence makes\n * `agent-module-executor` refuse `mode=\"execute\"` for `op=\"withdraw\"` outright. That guard's\n * removal condition is *\"amount-vs-floor enforcement is actually wired somewhere in the chain and\n * covered by a test that proves a floor-violating amount is refused\"* \u2014 so the invariant needs a\n * name and a test, not an inline `if` inside a 900-line action.\n *\n * SCOPE. `effectiveFloorBps` is the borrower's own limit on how far an AGENT may take the\n * position, clamped by the governance minimum, and it is populated ONLY when the Safe-agent arm\n * authorized the call (`checkSafeAgentWithdrawAuthorization` sets `path.outcome`). A\n * borrower-signed or EIP-1271 withdrawal leaves it 0 and is governed by the protocol's\n * liquidation threshold alone \u2014 hence the `<= 0` early return, which is the non-agent path and\n * not a bypass.\n *\n * ZERO DEBT IS OUT OF SCOPE, deliberately. The caller applies this only where `ucdDebt > 0`,\n * because the floor is a RATIO and the post-withdrawal ratio is infinite for any amount once debt\n * is zero \u2014 there is nothing for it to bound, the protocol has no claim on the collateral, and\n * gating the scope on debt would leave a repaid multi-sig unable to retrieve its own BTC inside\n * the 60s `strictCurrentQuantum` window. What bounds the zero-debt case is the quorum-gated\n * destination allowlist. Never describe this floor to a user as a cap on withdrawal size.\n *\n * @param effectiveFloorBps Post-withdrawal collateral-ratio floor from the delegation record.\n * 0 (or negative) means \"no agent floor applies\" \u2014 see SCOPE above.\n * @param postWithdrawalCollateralRatioBps The ratio the position would hold AFTER this withdrawal.\n * @throws When an agent floor applies and the withdrawal would breach it.\n */\nexport function assertAgentWithdrawFloor(\n effectiveFloorBps: number,\n postWithdrawalCollateralRatioBps: number\n): void {\n if (!Number.isFinite(effectiveFloorBps) || effectiveFloorBps <= 0) return;\n\n // A non-finite ratio here would compare false and silently permit the withdrawal, so it is\n // refused explicitly: an unknown post-withdrawal position is not a safe one to act on.\n if (!Number.isFinite(postWithdrawalCollateralRatioBps)) {\n throw new Error(\n `Agent withdrawal refused: post-withdrawal collateral ratio is not a finite number ` +\n `(${String(postWithdrawalCollateralRatioBps)}) \u2014 refusing to evaluate the delegation ` +\n `floor of ${bpsToPercent(effectiveFloorBps)}% against it`\n );\n }\n\n // Strictly below: a withdrawal landing exactly ON the floor is permitted, matching\n // `isCollateralSufficient` (`>= minimumRatioBps`) and the registry's own `canWithdraw`\n // comparison. The two must not disagree by one basis point.\n if (postWithdrawalCollateralRatioBps < effectiveFloorBps) {\n throw new Error(\n `Agent withdrawal refused: post-withdrawal collateral ratio ${bpsToPercent(\n postWithdrawalCollateralRatioBps\n )}% is below the delegation floor ${bpsToPercent(effectiveFloorBps)}%`\n );\n }\n}\n", "/**\n * The one place a LIT Action turns an RPC URL into an ethers connection.\n *\n * dRPC authenticates either with the key in the URL (`?dkey=<key>`) or with a\n * `Drpc-Key` header on a keyless URL. ethers puts the request URL into every\n * provider error, and a LIT Action's errors travel back through Chipotle into\n * server logs and API responses \u2014 so a keyed URL is a key in every failed read.\n * The header form keeps the key out of the URL, and therefore out of the errors.\n *\n * The caller supplies the key as the `drpcKey` jsParam. It is a secret aimed at\n * one provider, so this module only ever attaches it to a dRPC host: the host\n * check sits in `evmRpcConnection`, where the header is built, so no code path\n * can send the key anywhere else, and only over https. A keyed `?dkey=` URL is\n * still accepted on its own (callers move over after the new CIDs are live), but\n * its key is moved into the header too; sending both is refused.\n */\n\n/** dRPC's hosts. Both are on APPROVED_EVM_RPC_DOMAINS; `drpc.live` is the faster load balancer. */\nconst DRPC_DOMAINS = [\"drpc.org\", \"drpc.live\"];\n\n/** dRPC's header for the API key. */\nexport const DRPC_KEY_HEADER = \"Drpc-Key\";\n\n/** dRPC keys are URL-safe base64-like strings (44 chars today). Never echoed in errors. */\nconst DRPC_KEY_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;\n\n/** The ethers v5 `ConnectionInfo` subset the actions use. */\nexport interface EvmRpcConnection {\n url: string;\n headers?: Record<string, string>;\n timeout?: number;\n}\n\nfunction isDrpcHost(hostname: string): boolean {\n return DRPC_DOMAINS.some(\n (domain) => hostname === domain || hostname.endsWith(`.${domain}`),\n );\n}\n\nfunction assertKeyFormat(key: unknown, label: string): asserts key is string {\n if (typeof key !== \"string\" || !DRPC_KEY_PATTERN.test(key)) {\n throw new Error(\n `Invalid ${label}: expected 16-128 characters of [A-Za-z0-9_-]`,\n );\n }\n}\n\n/** A key only ever travels encrypted: a plaintext `http://` dRPC URL is refused. */\nfunction assertHttps(url: URL): void {\n if (url.protocol !== \"https:\") {\n throw new Error(\n `A dRPC key is only sent over https, but the RPC URL scheme is \"${url.protocol}\"`,\n );\n }\n}\n\n/**\n * Validate a caller-supplied `drpcKey` against the RPC URL it will authenticate.\n *\n * Returns `undefined` when no key was supplied. Throws when the key is malformed,\n * when `rpcUrl` is not an https dRPC URL, or when `rpcUrl` already carries\n * `?dkey=`. Call it right after the URL itself has been validated, so a bad key\n * fails the action before any read.\n */\nexport function resolveDrpcKey(\n rpcUrl: string,\n drpcKey: unknown,\n): string | undefined {\n if (drpcKey === undefined) {\n return undefined;\n }\n assertKeyFormat(drpcKey, '\"drpcKey\"');\n const url = new URL(rpcUrl);\n if (!isDrpcHost(url.hostname)) {\n throw new Error(\n `\"drpcKey\" is only sent to dRPC, but the RPC host is \"${url.hostname}\" (expected ${DRPC_DOMAINS.join(\" or \")})`,\n );\n }\n assertHttps(url);\n if (url.searchParams.has(\"dkey\")) {\n throw new Error(\n '\"drpcKey\" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one',\n );\n }\n return drpcKey;\n}\n\n/**\n * The Lit node's own RPC endpoint for `chain` \u2014 the fallback when the caller\n * sent no `rpcUrl`. A `drpcKey` authenticates the caller's dRPC URL only, so it\n * is refused here rather than attached to an endpoint the caller did not choose\n * (which may itself be a dRPC host).\n */\nexport async function litNodeRpcUrl(\n chain: string,\n drpcKey: unknown,\n): Promise<string> {\n if (drpcKey !== undefined) {\n throw new Error(\n '\"drpcKey\" was supplied without an \"rpcUrl\" \u2014 the key only authenticates a caller-supplied dRPC rpcUrl, never the Lit node\\'s own endpoint',\n );\n }\n // @ts-ignore - Lit.Actions available in LIT runtime\n return Lit.Actions.getRpcUrl({ chain });\n}\n\n/**\n * The ethers connection for `rpcUrl`: the dRPC key, if any, goes in the\n * `Drpc-Key` header. Re-validates the key here so the header can only ever be\n * attached to an https dRPC URL, whatever the call site did before.\n *\n * A legacy keyed dRPC URL (`?dkey=<key>`) is still accepted, but its key is\n * moved out of the URL into the header, so a failed read's error carries a\n * keyless URL either way. A `dkey` on a non-dRPC host, or more than one `dkey`,\n * is refused rather than passed through.\n */\nexport function evmRpcConnection(\n rpcUrl: string,\n drpcKey?: string,\n timeout?: number,\n): EvmRpcConnection {\n const connection: EvmRpcConnection = { url: rpcUrl };\n const key = resolveDrpcKey(rpcUrl, drpcKey);\n if (key !== undefined) {\n connection.headers = { [DRPC_KEY_HEADER]: key };\n } else {\n const url = new URL(rpcUrl);\n const legacyKeys = url.searchParams.getAll(\"dkey\");\n if (legacyKeys.length > 1) {\n throw new Error(\n `rpcUrl carries ${legacyKeys.length} \"dkey\" parameters \u2014 send exactly one dRPC key`,\n );\n }\n if (legacyKeys.length === 1 && !isDrpcHost(url.hostname)) {\n throw new Error(\n `rpcUrl carries a dRPC key (?dkey=) but the RPC host is \"${url.hostname}\" \u2014 a dRPC key is only sent to ${DRPC_DOMAINS.join(\" or \")}`,\n );\n }\n if (legacyKeys.length === 1) {\n const legacyKey = legacyKeys[0];\n assertKeyFormat(legacyKey, \"dRPC key in rpcUrl (?dkey=)\");\n assertHttps(url);\n url.searchParams.delete(\"dkey\");\n connection.url = url.toString();\n connection.headers = { [DRPC_KEY_HEADER]: legacyKey };\n }\n }\n if (timeout !== undefined) {\n connection.timeout = timeout;\n }\n return connection;\n}\n", "/**\n * Protocol Parameters Module\n *\n * Fetches protocol parameters directly from smart contracts.\n * This ensures LIT actions always use current values set by protocol governance.\n *\n * Parameters fetched:\n * - Liquidation threshold (from LoanOperationsManager)\n * - Term-specific fees (from TermManager)\n */\n\nimport { LIT_ACTION_ETH_RPC_TIMEOUT_MS } from \"../constants\";\nimport { evmRpcConnection, litNodeRpcUrl } from \"./evm-rpc\";\n\n/**\n * Configuration for protocol parameters module\n */\nexport interface ProtocolParametersConfig {\n termManagerAddress: string;\n loanOpsManagerAddress: string;\n liquidationManagerAddress: string;\n chain: string;\n chainId: number;\n rpcUrl?: string; // Optional: for testing with local Hardhat/Anvil\n drpcKey?: string; // dRPC key for rpcUrl, sent in the Drpc-Key header (see evm-rpc)\n}\n\n/**\n * Term fees structure\n */\nexport interface TermFees {\n originationFeeBps: number;\n extensionFeeBps: number;\n}\n\n/**\n * Protocol Parameters Module\n *\n * Fetches governance-controlled parameters from smart contracts\n */\nexport class ProtocolParametersModule {\n private termManagerAddress: string;\n private loanOpsManagerAddress: string;\n private liquidationManagerAddress: string;\n private chain: string;\n private chainId: number;\n private rpcUrl?: string;\n private drpcKey?: string;\n\n constructor(config: ProtocolParametersConfig) {\n this.termManagerAddress = config.termManagerAddress;\n this.loanOpsManagerAddress = config.loanOpsManagerAddress;\n this.liquidationManagerAddress = config.liquidationManagerAddress;\n this.chain = config.chain;\n this.chainId = config.chainId;\n this.rpcUrl = config.rpcUrl;\n this.drpcKey = config.drpcKey;\n }\n\n /**\n * Get liquidation threshold from LoanOperationsManager\n *\n * @returns Liquidation threshold in basis points\n */\n async getLiquidationThreshold(): Promise<number> {\n try {\n // Get RPC URL - either from config (for local testing) or from Lit runtime\n let rpcUrl: string;\n if (this.rpcUrl) {\n rpcUrl = this.rpcUrl;\n } else {\n rpcUrl = await litNodeRpcUrl(this.chain, this.drpcKey);\n }\n // @ts-ignore - ethers available in LIT runtime\n // StaticJsonRpcProvider with explicit network bypasses auto-detection (required for ngrok URLs)\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n {\n name: \"any\",\n chainId: this.chainId,\n },\n );\n const abi = [\n {\n inputs: [],\n name: \"liquidationThreshold\",\n outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n ];\n // @ts-ignore - ethers available in LIT runtime\n const contract = new ethers.Contract(\n this.loanOpsManagerAddress,\n abi,\n provider\n );\n const result = await contract.liquidationThreshold();\n return Number(result.toString());\n } catch (error: any) {\n console.error(\n \"[ProtocolParameters] Error fetching liquidation threshold:\",\n error.message\n );\n throw new Error(\n `Failed to fetch liquidation threshold: ${error.message}`\n );\n }\n }\n\n /**\n * Get term-specific fees from TermManager\n *\n * @param termMonths Loan term in months\n * @returns Term fees (origination and extension) in basis points\n */\n async getTermFees(termMonths: number): Promise<TermFees> {\n try {\n // Get RPC URL - either from config (for local testing) or from Lit runtime\n let rpcUrl: string;\n if (this.rpcUrl) {\n rpcUrl = this.rpcUrl;\n } else {\n rpcUrl = await litNodeRpcUrl(this.chain, this.drpcKey);\n }\n // @ts-ignore - ethers available in LIT runtime\n // StaticJsonRpcProvider with explicit network bypasses auto-detection (required for ngrok URLs)\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n {\n name: \"any\",\n chainId: this.chainId,\n },\n );\n const abi = [\n {\n inputs: [\n { internalType: \"uint256\", name: \"_termMonths\", type: \"uint256\" },\n ],\n name: \"getTermFees\",\n outputs: [\n { internalType: \"uint88\", name: \"originationFee\", type: \"uint88\" },\n { internalType: \"uint88\", name: \"extensionFee\", type: \"uint88\" },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n ];\n // @ts-ignore - ethers available in LIT runtime\n const contract = new ethers.Contract(\n this.termManagerAddress,\n abi,\n provider\n );\n const result = await contract.getTermFees(termMonths);\n return {\n originationFeeBps: Number(\n result.originationFee?.toString?.() ??\n result[0]?.toString?.() ??\n result[0]\n ),\n extensionFeeBps: Number(\n result.extensionFee?.toString?.() ??\n result[1]?.toString?.() ??\n result[1]\n ),\n };\n } catch (error: any) {\n console.error(\n \"[ProtocolParameters] Error fetching term fees:\",\n error.message\n );\n throw new Error(`Failed to fetch term fees: ${error.message}`);\n }\n }\n\n /**\n * Get authorized spends hash from contract\n *\n * Fetches the cryptographic hash of authorized Bitcoin spends for a position.\n * This hash is used in authorization messages to prevent race conditions.\n *\n * @param positionId - Position identifier (bytes32)\n * @returns Authorized spends hash (bytes32)\n */\n async getAuthorizedSpendsHash(positionId: string): Promise<string> {\n try {\n const rpcUrl =\n this.rpcUrl || (await litNodeRpcUrl(this.chain, this.drpcKey));\n\n // @ts-ignore - ethers available in LIT runtime\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n {\n name: \"any\",\n chainId: this.chainId,\n },\n );\n\n // Convert positionId to bytes32\n const positionIdBytes32 = positionId.startsWith(\"0x\")\n ? positionId\n : `0x${positionId.padStart(64, \"0\")}`;\n\n // Call getAuthorizedSpendsHash(bytes32 positionId) on LoanOperationsManager\n // @ts-ignore - ethers available in LIT runtime\n const contract = new ethers.Contract(\n this.loanOpsManagerAddress,\n [\n {\n inputs: [{ name: \"positionId\", type: \"bytes32\" }],\n name: \"getAuthorizedSpendsHash\",\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n ],\n provider\n );\n\n const hash = await contract.getAuthorizedSpendsHash(positionIdBytes32);\n return hash;\n } catch (error: any) {\n console.error(\n \"[ProtocolParameters] Error fetching authorized spends hash:\",\n error.message\n );\n throw new Error(\n `Failed to fetch authorized spends hash: ${error.message}`\n );\n }\n }\n\n /**\n * Read one `uint256` view from LiquidationManager.\n */\n private async readLiquidationManagerUint(\n fnName: \"maxEscalatedThreshold\" | \"expiryLiquidationIncrementBps\" | \"expiredLoanGracePeriodDays\",\n description: string,\n ): Promise<number> {\n try {\n let rpcUrl: string;\n if (this.rpcUrl) {\n rpcUrl = this.rpcUrl;\n } else {\n rpcUrl = await litNodeRpcUrl(this.chain, this.drpcKey);\n }\n // @ts-ignore - ethers available in LIT runtime\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n {\n name: \"any\",\n chainId: this.chainId,\n },\n );\n const abi = [\n {\n inputs: [],\n name: fnName,\n outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n ];\n // @ts-ignore - ethers available in LIT runtime\n const contract = new ethers.Contract(\n this.liquidationManagerAddress,\n abi,\n provider\n );\n const result = await contract[fnName]();\n return Number(result.toString());\n } catch (error: any) {\n console.error(\n `[ProtocolParameters] Error fetching ${description}:`,\n error.message\n );\n throw new Error(\n `Failed to fetch ${description}: ${error.message}`\n );\n }\n }\n\n /**\n * Get max escalated threshold from LiquidationManager\n *\n * This is the governance-controlled ceiling for expired loan liquidation thresholds.\n *\n * @returns Max escalated threshold in basis points\n */\n async getMaxEscalatedThreshold(): Promise<number> {\n return this.readLiquidationManagerUint(\"maxEscalatedThreshold\", \"max escalated threshold\");\n }\n\n /**\n * Get the compound daily increment applied to an expired loan's liquidation\n * threshold (`LiquidationManager.expiryLiquidationIncrementBps`).\n *\n * @returns Daily increment in basis points\n */\n async getExpiryLiquidationIncrementBps(): Promise<number> {\n return this.readLiquidationManagerUint(\"expiryLiquidationIncrementBps\", \"expiry liquidation increment\");\n }\n\n /**\n * Get the number of days after expiry before escalation begins\n * (`LiquidationManager.expiredLoanGracePeriodDays`).\n *\n * @returns Grace period in days\n */\n async getExpiredLoanGracePeriodDays(): Promise<number> {\n return this.readLiquidationManagerUint(\"expiredLoanGracePeriodDays\", \"expired loan grace period\");\n }\n}\n\n/**\n * Factory function to create protocol parameters module\n */\nexport function createProtocolParametersModule(\n config: ProtocolParametersConfig\n): ProtocolParametersModule {\n return new ProtocolParametersModule(config);\n}\n", "/**\n * Vault-address parsing \u2014 single source of truth for turning the raw on-chain\n * `Position.vaultAddress` string into the Bitcoin address for a chain.\n *\n * The contract stores either a plain address string or a JSON object keyed by\n * Bitcoin network (`{\"mainnet\":\"bc1\u2026\",\"testnet\":\"m\u2026\",\"regtest\":\"bcrt1\u2026\"}`).\n * Extracted from `vault-snapshot.ts` (remediation P6/#7b) so the phase-2\n * signer can bind its derived PKP address to the on-chain vault address using\n * exactly the same parse the snapshot layer uses.\n */\n\nimport {\n BitcoinNetwork,\n EVMChain,\n getBitcoinNetworkForChain,\n} from \"../constants\";\n\n/**\n * Strip a storage network prefix (`REGTEST_` / `TESTNET_` / `MAINNET_`) from a\n * Bitcoin address. Parity with BitcoinDataProvider's private helper.\n */\nexport function stripNetworkPrefix(address: string): string {\n const prefixPattern = /^(REGTEST_|TESTNET_|MAINNET_)/;\n return address.replace(prefixPattern, \"\");\n}\n\n/**\n * Parse vault address based on format and network.\n *\n * Supports two formats:\n * 1. Single string: \"mqM3ZR2N6DzZkafSdFqxEAkWovAU3uYTAN\"\n * 2. JSON object: {\"mainnet\":\"bc1q...\",\"testnet\":\"mqM3...\"}\n *\n * @param rawVaultAddress Raw vault address from contract\n * @param chain Validated EVM chain (sepolia, ethereum, hardhat)\n * @returns Parsed Bitcoin address for the appropriate network\n */\nexport function parseVaultAddress(\n rawVaultAddress: string,\n chain: string,\n): string | undefined {\n // Try parsing as JSON first\n try {\n const parsed = JSON.parse(rawVaultAddress);\n\n // If it's an object with network keys\n if (typeof parsed === \"object\" && parsed !== null) {\n // Test chains never fall back to the mainnet key: that would bind a test\n // position to a mainnet address (review 2026-07-15 P1). With no test-network\n // key the result is undefined, which callers refuse.\n // Special case: Sepolia uses regtest Bitcoin addresses for local development\n const chainLower = chain.toLowerCase();\n if (chainLower === \"sepolia\") {\n return parsed.regtest || parsed.testnet || undefined;\n }\n\n // For other chains, map by the chain's Bitcoin network.\n const bitcoinNetwork = getBitcoinNetworkForChain(chain as EVMChain);\n if (bitcoinNetwork === BitcoinNetwork.REGTEST) {\n return parsed.regtest || parsed.testnet || undefined;\n }\n if (bitcoinNetwork === BitcoinNetwork.TESTNET) {\n return parsed.testnet || parsed.regtest || undefined;\n }\n // Mainnet: only the mainnet key is acceptable \u2014 a testnet/regtest\n // address must never bind a mainnet position. May be undefined; callers\n // MUST check (a JSON vault record without the required network key is a\n // data error, not something to paper over).\n return parsed.mainnet;\n }\n } catch (e) {\n // Not JSON, continue to return as plain string\n }\n\n // Return as-is if it's a plain string\n return rawVaultAddress;\n}\n", "/**\n * Vault Snapshot Module - The Brain\n *\n * This module calculates ALL vault intelligence from simple contract state.\n * It is the single source of truth for vault health metrics.\n *\n * Architecture:\n * - Smart Contract: Stores simple state (ucdDebt, termStartTimestamp, btcCollateralSats)\n * - This Module: Calculates everything else (ratios, thresholds, risk metrics)\n *\n * The vault-snapshot is used by:\n * - Minting authorization (check if sufficient collateral)\n * - Liquidation detection (check if under threshold)\n * - UI display (show vault health to user)\n * - Repayment calculations (how much can be repaid)\n */\n\nimport {\n VaultSnapshot,\n VaultSnapshotConfig,\n} from \"../interfaces/chunks/vault-snapshot.i\";\nimport {\n calculateTermStatus,\n calculateLiquidationThreshold,\n calculateCollateralMetrics,\n hasSufficientCollateralForDebt,\n calculateTermStartFromExpiry,\n} from \"./business-rules-math.module\";\nimport { createProtocolParametersModule } from \"./protocol-parameters.module\";\nimport { parseVaultAddress } from \"./vault-address\";\nimport {\n validateChain,\n LIT_ACTION_ETH_RPC_TIMEOUT_MS,\n} from \"../constants\";\nimport { evmRpcConnection, litNodeRpcUrl } from \"./evm-rpc\";\n\n/**\n * NOTE: In the LIT Actions runtime, `ethers` is provided as a global.\n * We declare it here so TypeScript can type-check this module when building\n * the package without bundling ethers or importing it as a module.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n/**\n * Vault Snapshot Module\n *\n * The intelligence layer that transforms simple contract state into\n * comprehensive vault health metrics.\n */\nexport class VaultSnapshotModule {\n private config: VaultSnapshotConfig;\n\n constructor(config: VaultSnapshotConfig) {\n // No default: a missing chainId used to become 1 (mainnet) for the protocol-parameter\n // reads and \"detect it\" for the position read \u2014 loan-vault-btc-balance omitted it on\n // every chain. Fail at construction instead.\n if (!Number.isInteger(config.chainId) || config.chainId <= 0) {\n throw new Error(`VaultSnapshotModule requires a positive integer chainId, got ${String(config.chainId)}`);\n }\n this.config = config;\n }\n\n /**\n * Get complete vault snapshot\n *\n * This is the main entry point. Returns everything you need to know\n * about a vault's health in a single call.\n *\n * @param positionId - Position to snapshot\n * @returns Complete VaultSnapshot with all metrics\n */\n async getVaultSnapshot(positionId: string): Promise<VaultSnapshot> {\n // 1. Query contract for position state\n const positionState = await this.queryPositionState(positionId);\n\n console.log(\n `[Vault Snapshot] Raw vault address from contract: \"${positionState.vaultAddress}\"`\n );\n\n // 2 & 3. Get available balance and BTC price in parallel (saves ~10s on cold starts)\n const [balanceResult, btcPriceUsd] = await Promise.all([\n this.config.vaultBalance.calculateTrustedBalance(\n positionId,\n positionState.vaultAddress\n ),\n this.config.priceOracle.getBTCPrice(),\n ]);\n\n // 4. Fetch protocol parameters from smart contracts\n const protocolParams = createProtocolParametersModule({\n termManagerAddress: this.config.termManagerAddress,\n loanOpsManagerAddress: this.config.loanOpsManagerAddress,\n liquidationManagerAddress: this.config.liquidationManagerAddress,\n chain: this.config.chain,\n chainId: this.config.chainId,\n rpcUrl: this.config.rpcUrl,\n drpcKey: this.config.drpcKey,\n });\n\n // Fetch liquidation threshold, max escalated threshold, and term fees in parallel\n // Use termOverride if provided (for extensions), otherwise use position's current term\n const termForFees = this.config.termOverride ?? positionState.selectedTerm;\n const [\n liquidationThresholdBps,\n maxEscalatedThresholdBps,\n expiryLiquidationIncrementBps,\n expiredLoanGracePeriodDays,\n termFees,\n ] = await Promise.all([\n protocolParams.getLiquidationThreshold(),\n protocolParams.getMaxEscalatedThreshold(),\n protocolParams.getExpiryLiquidationIncrementBps(),\n protocolParams.getExpiredLoanGracePeriodDays(),\n protocolParams.getTermFees(termForFees),\n ]);\n\n // 5. Calculate term status\n const termStatus = calculateTermStatus(\n positionState.termStartTimestamp,\n positionState.selectedTerm\n );\n\n // 6. Calculate liquidation threshold \u2014 on-chain values for both active and expired\n // loans; the expired curve is the contract's own compound escalation.\n const currentLiquidationThreshold = calculateLiquidationThreshold(\n termStatus.isExpired,\n termStatus.daysIntoGracePeriod,\n liquidationThresholdBps,\n {\n dailyIncrementBps: expiryLiquidationIncrementBps,\n gracePeriodDays: expiredLoanGracePeriodDays,\n maxEscalatedThresholdBps,\n }\n );\n\n // 7. Calculate collateral ratio (using BigInt for precision)\n const collateralMetrics = calculateCollateralMetrics(\n balanceResult.availableBalance,\n btcPriceUsd,\n positionState.ucdDebt\n );\n\n // 8. Calculate liquidation risk\n const isLiquidatable =\n collateralMetrics.collateralRatioBps < currentLiquidationThreshold;\n const marginToLiquidationBps =\n collateralMetrics.collateralRatioBps - currentLiquidationThreshold;\n\n // 9. Assemble complete snapshot\n return {\n // Raw state\n positionId: positionState.positionId,\n pkpId: positionState.pkpId,\n borrower: positionState.borrower,\n vaultAddress: positionState.vaultAddress,\n ucdDebt: positionState.ucdDebt,\n termStartTimestamp: positionState.termStartTimestamp,\n selectedTerm: positionState.selectedTerm,\n status: positionState.status, // Loan status enum value (0-7)\n expiryAt: positionState.expiryAt, // Loan expiry timestamp\n previousExpiryAt: positionState.previousExpiryAt, // expiryAt before last renewal; 0 if never renewed\n totalTerm: positionState.totalTerm, // total accumulated loan months; 0 before first renewal\n lastRenewedAt: positionState.lastRenewedAt, // timestamp of most recent renewal; createdAt at origination; 0 for pre-H-5 positions\n\n // Bitcoin state\n totalBTCSats: balanceResult.totalBalance,\n totalUTXOs: balanceResult.totalUTXOs,\n authorizedSpendsSats: balanceResult.authorizedBalance,\n authorizedSpendsHash: balanceResult.authorizedSpendsHash,\n availableBTCSats: balanceResult.availableBalance,\n availableUTXOs: balanceResult.availableUTXOs,\n\n // Price data\n btcPriceUsd,\n\n // Calculated metrics\n collateralValueUsd: collateralMetrics.collateralValueUsd,\n collateralRatioBps: collateralMetrics.collateralRatioBps,\n\n // Term status\n termDurationDays: termStatus.termDurationDays,\n termLengthDays: termStatus.termLengthDays,\n isExpired: termStatus.isExpired,\n daysUntilExpiry: termStatus.daysUntilExpiry,\n daysIntoGracePeriod: termStatus.daysIntoGracePeriod,\n\n // Liquidation risk\n currentLiquidationThreshold,\n isLiquidatable,\n marginToLiquidationBps,\n\n // Protocol parameters (from smart contracts)\n liquidationThresholdBps,\n originationFeeBps: termFees.originationFeeBps,\n extensionFeeBps: termFees.extensionFeeBps,\n\n // Metadata\n timestamp: Date.now(),\n };\n }\n\n // NOTE (remediation P1/#5): `getVaultSnapshotFast` \u2014 a snapshot built on the\n // skip-UTXO-validation balance path \u2014 was deleted. It had zero callers, and\n // a snapshot whose balance skipped UTXO validation + consensus must never\n // exist within reach of a signing flow. Every snapshot now runs the full\n // validation path above.\n\n /**\n * Query position state from smart contract\n *\n * Gets the simple state that contract stores:\n * - positionId, pkpId, borrower, vaultAddress\n * - ucdDebt\n * - termStartTimestamp\n * - selectedTerm\n * - status\n */\n protected async queryPositionState(positionId: string): Promise<{\n positionId: string;\n pkpId: string;\n borrower: string;\n vaultAddress: string;\n ucdDebt: bigint;\n termStartTimestamp: number;\n selectedTerm: number;\n status: number;\n expiryAt: number;\n previousExpiryAt: number;\n totalTerm: number;\n lastRenewedAt: number;\n }> {\n // Convert positionId to bytes32\n const positionIdBytes32 = positionId.startsWith(\"0x\")\n ? positionId\n : `0x${positionId.padStart(64, \"0\")}`;\n\n // Get RPC URL\n let rpcUrl: string;\n if (this.config.rpcUrl) {\n rpcUrl = this.config.rpcUrl;\n } else {\n rpcUrl = await litNodeRpcUrl(this.config.chain, this.config.drpcKey);\n }\n\n // Query contract\n // @ts-ignore - ethers available in LIT runtime\n // StaticJsonRpcProvider with just chainId to avoid network validation errors\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.config.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n this.config.chainId\n );\n\n // CRITICAL: Must call PositionManagerCore facet directly to get full Position struct with vaultAddress\n // The Diamond proxy's getPositionDetails() returns simplified struct without vaultAddress\n\n // Step 1: Get core facet address from Diamond proxy\n // @ts-ignore - ethers available in LIT runtime\n const diamondContract = new ethers.Contract(\n this.config.contractAddress,\n [\n {\n inputs: [],\n name: \"core\",\n outputs: [{ internalType: \"address\", name: \"\", type: \"address\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n ],\n provider\n );\n\n const coreAddress = await diamondContract.core();\n\n // Step 2: Call getPositionDetails on core facet (returns full struct with vaultAddress)\n // ABI for PositionManagerCoreModule.getPositionDetails\n const coreGetPositionDetailsABI = [\n {\n inputs: [\n { internalType: \"bytes32\", name: \"positionId\", type: \"bytes32\" },\n ],\n name: \"getPositionDetails\",\n outputs: [\n {\n components: [\n { internalType: \"bytes32\", name: \"positionId\", type: \"bytes32\" },\n { internalType: \"bytes32\", name: \"pkpId\", type: \"bytes32\" },\n { internalType: \"uint256\", name: \"ucdDebt\", type: \"uint256\" },\n { internalType: \"string\", name: \"vaultAddress\", type: \"string\" },\n { internalType: \"address\", name: \"borrower\", type: \"address\" },\n { internalType: \"uint40\", name: \"createdAt\", type: \"uint40\" },\n { internalType: \"uint40\", name: \"lastUpdated\", type: \"uint40\" },\n { internalType: \"uint16\", name: \"selectedTerm\", type: \"uint16\" },\n { internalType: \"uint40\", name: \"expiryAt\", type: \"uint40\" },\n {\n internalType: \"enum LoanStatusLib.LoanStatus\",\n name: \"status\",\n type: \"uint8\",\n },\n { internalType: \"uint40\", name: \"previousExpiryAt\", type: \"uint40\" },\n { internalType: \"uint16\", name: \"totalTerm\", type: \"uint16\" },\n { internalType: \"uint40\", name: \"lastRenewedAt\", type: \"uint40\" },\n ],\n internalType: \"struct IPositionManagerCore.Position\",\n name: \"\",\n type: \"tuple\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n ];\n\n // @ts-ignore - ethers available in LIT runtime\n const coreContract = new ethers.Contract(\n coreAddress,\n coreGetPositionDetailsABI,\n provider\n );\n\n const position = await coreContract.getPositionDetails(positionIdBytes32);\n\n // Validate status is in valid range (0-7)\n const statusNum = Number(position.status);\n if (statusNum < 0 || statusNum > 7) {\n // Log detailed diagnostic info for debugging\n console.error(\n \"[VaultSnapshot] INVALID STATUS - ABI decoding error detected\"\n );\n console.error(\" Position ID:\", positionIdBytes32);\n console.error(\" Contract:\", this.config.contractAddress);\n console.error(\" Status decoded:\", statusNum, \"(expected 0-7)\");\n console.error(\" Full position:\", JSON.stringify(position, null, 2));\n\n throw new Error(\n `Invalid position status decoded from contract: ${statusNum} (expected 0-7). ` +\n `This indicates an ABI decoding issue. Position: ${positionIdBytes32}`\n );\n }\n\n // Calculate term start timestamp from expiry using pure function\n // Always use selectedTerm (current period length) for term start calculation.\n // expiryAt = start of current period + selectedTerm months, so termStart = expiryAt - selectedTerm months.\n // totalTerm is the accumulated total months and is NOT relevant for when the current period started.\n const expiryAt = Number(position.expiryAt);\n const selectedTermMonths = Number(position.selectedTerm);\n const totalTermMonths = Number(position.totalTerm);\n const previousExpiryAt = Number(position.previousExpiryAt);\n const lastRenewedAt = Number(position.lastRenewedAt);\n const termStartTimestamp = calculateTermStartFromExpiry(\n expiryAt,\n selectedTermMonths\n );\n\n // A JSON vault record without the address for this chain's Bitcoin\n // network is a data error \u2014 fail loud here rather than let an undefined\n // address flow into balance reads / signed snapshots.\n const parsedVaultAddress = parseVaultAddress(\n position.vaultAddress,\n validateChain(this.config.chain)\n );\n if (typeof parsedVaultAddress !== \"string\" || parsedVaultAddress.length === 0) {\n throw new Error(\n `Position ${positionIdBytes32} vaultAddress has no entry for chain \"${this.config.chain}\"`\n );\n }\n\n return {\n positionId: position.positionId,\n pkpId: position.pkpId,\n borrower: position.borrower,\n vaultAddress: parsedVaultAddress,\n ucdDebt: BigInt(position.ucdDebt.toString()),\n termStartTimestamp,\n selectedTerm: selectedTermMonths,\n status: statusNum,\n expiryAt,\n previousExpiryAt,\n totalTerm: totalTermMonths,\n lastRenewedAt,\n };\n }\n\n // parseVaultAddress moved to `modules/vault-address.ts` (shared with the\n // phase-2 signer for the P6/#7b vault-identity binding).\n\n /**\n * Quick check if position is liquidatable\n *\n * Convenience method when you only need to know if position can be liquidated.\n *\n * @param positionId - Position to check\n * @returns True if position is liquidatable\n */\n async isLiquidatable(positionId: string): Promise<boolean> {\n const snapshot = await this.getVaultSnapshot(positionId);\n return snapshot.isLiquidatable;\n }\n\n /**\n * Get collateral ratio for position\n *\n * Convenience method when you only need the collateral ratio.\n *\n * @param positionId - Position to check\n * @returns Collateral ratio in basis points\n */\n async getCollateralRatio(positionId: string): Promise<number> {\n const snapshot = await this.getVaultSnapshot(positionId);\n return snapshot.collateralRatioBps;\n }\n\n /**\n * Get available BTC balance\n *\n * Convenience method when you only need available balance.\n *\n * @param positionId - Position to check\n * @returns Available BTC in satoshis\n */\n async getAvailableBalance(positionId: string): Promise<bigint> {\n const snapshot = await this.getVaultSnapshot(positionId);\n return snapshot.availableBTCSats;\n }\n\n /**\n * Check if position has sufficient collateral for new debt\n *\n * Used by minting authorization to validate new mints.\n *\n * @param positionId - Position to check\n * @param additionalDebt - Additional UCD debt to add\n * @param requiredRatioBps - Required collateral ratio (e.g., 11000 for 110%)\n * @returns True if sufficient collateral exists\n */\n async hasSufficientCollateral(\n positionId: string,\n additionalDebt: bigint,\n requiredRatioBps: number\n ): Promise<boolean> {\n const snapshot = await this.getVaultSnapshot(positionId);\n\n // Delegate to pure math function\n return hasSufficientCollateralForDebt(\n snapshot.collateralValueUsd,\n snapshot.ucdDebt,\n additionalDebt,\n requiredRatioBps\n );\n }\n}\n\n/**\n * Factory function to create VaultSnapshotModule\n *\n * @param config - Configuration\n * @returns VaultSnapshotModule instance\n */\nexport function createVaultSnapshotModule(\n config: VaultSnapshotConfig\n): VaultSnapshotModule {\n return new VaultSnapshotModule(config);\n}\n\n/**\n * USAGE EXAMPLE:\n *\n * ```typescript\n * import { createVaultSnapshotModule } from './modules/vault-snapshot';\n * import { BitcoinDataProvider } from './modules/bitcoin-data-provider.module';\n * import { PriceOracleModule } from './modules/price-oracle.module';\n *\n * // Initialize dependencies\n * const bitcoinProvider = new BitcoinDataProvider({\n * providerUrl: 'https://blockstream.info/testnet/api'\n * });\n *\n * const priceOracle = new PriceOracleModule('mainnet');\n *\n * // Create vault balance module\n * const vaultBalance = createVaultBalanceModule({\n * contractAddress: '0x...',\n * chain: 'sepolia',\n * bitcoinProvider,\n * minConfirmations: 6\n * });\n *\n * // Create vault snapshot module\n * const vaultSnapshot = createVaultSnapshotModule({\n * contractAddress: '0x...',\n * chain: 'sepolia',\n * vaultBalance,\n * priceOracle,\n * });\n *\n * // Get complete snapshot\n * const snapshot = await vaultSnapshot.getVaultSnapshot('position123');\n *\n * console.log('Position:', snapshot.positionId);\n * console.log('Collateral Ratio:', snapshot.collateralRatioBps / 100, '%');\n * console.log('Liquidatable:', snapshot.isLiquidatable);\n * console.log('Days Until Expiry:', snapshot.daysUntilExpiry);\n * console.log('Available BTC:', snapshot.availableBTCSats, 'sats');\n *\n * // Or use convenience methods\n * const isLiquidatable = await vaultSnapshot.isLiquidatable('position123');\n * const collateralRatio = await vaultSnapshot.getCollateralRatio('position123');\n * const availableBalance = await vaultSnapshot.getAvailableBalance('position123');\n *\n * // Check if can mint more UCD\n * const canMint = await vaultSnapshot.hasSufficientCollateral(\n * 'position123',\n * BigInt(5000), // Want to mint 5000 more UCD\n * 11000 // Required 110% ratio\n * );\n * ```\n */\n", "/**\n * Opt-in verbose logging for Lit Actions.\n *\n * Production / IPFS builds should stay quiet: no message hashes, PKP material,\n * encoded blobs, or user signatures in logs unless explicitly enabled.\n *\n * Enable via (after jsParams merge onto globalThis):\n * - globalThis.debugAction === true (existing)\n * - globalThis.LIT_ACTION_DEBUG === true or \"true\"\n * - process.env.LIT_ACTION_DEBUG or process.env.DEBUG === \"1\" | \"true\" (Node/tests only)\n */\n\n/**\n * Strip credentials and common API-key query params from URLs before logging.\n * (RPC providers often put secrets in the query string, e.g. dkey=.)\n * Uses string replacement so values stay human-readable (no URL-encoding of [REDACTED]).\n */\nexport function sanitizeUrlForLogs(url: string): string {\n if (url == null || typeof url !== \"string\") return \"[missing]\";\n let out = url.replace(\n /([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,\n \"$1$2=[REDACTED]\",\n );\n try {\n const u = new URL(out);\n if (u.username || u.password) {\n u.username = \"\";\n u.password = \"\";\n out = u.toString();\n }\n } catch {\n /* invalid URL after redaction \u2014 return regex-sanitized string */\n }\n return out;\n}\n\nfunction envDebugEnabled(): boolean {\n try {\n if (typeof process === \"undefined\" || !process.env) return false;\n const a = process.env.LIT_ACTION_DEBUG;\n const b = process.env.DEBUG;\n return (\n a === \"1\" ||\n a === \"true\" ||\n b === \"1\" ||\n b === \"true\"\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Whether verbose debug logging is enabled for this execution.\n * @param override - When set (e.g. from explicit jsParams), takes precedence.\n */\nexport function isLitActionDebugEnabled(override?: boolean): boolean {\n if (override === true) return true;\n if (override === false) return false;\n\n const g = globalThis as Record<string, unknown>;\n\n if (g.debugAction === true) return true;\n if (g.LIT_ACTION_DEBUG === true) return true;\n if (g.LIT_ACTION_DEBUG === \"true\") return true;\n\n return envDebugEnabled();\n}\n\n/** Logs only when {@link isLitActionDebugEnabled} is true. */\nexport function litDebugLog(...args: unknown[]): void {\n if (!isLitActionDebugEnabled()) return;\n console.log(...args);\n}\n\n/** console.warn only when debug enabled (rare; prefer litDebugLog). */\nexport function litDebugWarn(...args: unknown[]): void {\n if (!isLitActionDebugEnabled()) return;\n console.warn(...args);\n}\n", "import { isLitActionDebugEnabled } from \"./lit-action-debug\";\n\n/**\n * LIT Action Logger Module\n *\n * Centralized logging and timing infrastructure for LIT Actions.\n *\n * Features:\n * - Opt-in debugging via globalThis.debugAction or LIT_ACTION_DEBUG (see lit-action-debug.ts)\n * - Execution ID for multi-node correlation\n * - Step timing with automatic elapsed/remaining calculation\n * - Timeout warnings (30s LIT Protocol limit)\n * - Node context detection\n * - Final execution summary\n *\n * Usage:\n * ```typescript\n * const logger = LitActionLogger.create();\n * logger.stepStart('1', 'Fetching vault snapshot');\n * // ... do work ...\n * logger.stepEnd('1');\n * logger.summary();\n * ```\n *\n * Debug mode when isLitActionDebugEnabled() is true (debugAction, LIT_ACTION_DEBUG, etc.)\n *\n * Performance: When disabled (99% of cases), returns a no-op stub that does nothing.\n */\n\n/**\n * No-op logger stub for when debugging is disabled\n * Zero overhead - all methods are empty\n */\nclass NoOpLogger implements ILitActionLogger {\n stepStart(_stepId: string, _description: string): void {}\n stepEnd(_stepId: string, _warnThresholdMs?: number): void {}\n log(_stepId: string, _message: string, ..._rest: unknown[]): void {}\n warn(_stepId: string, _message: string): void {}\n error(_stepId: string, _message: string): void {}\n getElapsed(): number {\n return 0;\n }\n getRemaining(): number {\n return 30000;\n }\n summary(): void {}\n getExecutionId(): string {\n return \"\";\n }\n isDebugEnabled(): boolean {\n return false;\n }\n}\n\n/**\n * Interface for LIT Action Logger\n */\ninterface ILitActionLogger {\n stepStart(stepId: string, description: string): void;\n stepEnd(stepId: string, warnThresholdMs?: number): void;\n log(stepId: string, message: string, ...rest: unknown[]): void;\n warn(stepId: string, message: string): void;\n error(stepId: string, message: string): void;\n getElapsed(): number;\n getRemaining(): number;\n summary(): void;\n getExecutionId(): string;\n isDebugEnabled(): boolean;\n}\n\n/**\n * Full logger implementation for when debugging is enabled\n */\nclass DebugLogger implements ILitActionLogger {\n private executionId: string;\n private executionStartTime: number;\n private stepStartTimes: Map<string, number> = new Map();\n private stepDurations: Map<string, number> = new Map();\n private readonly TIMEOUT_MS = 30000; // 30 seconds LIT Action timeout\n private actionName: string;\n\n constructor(actionName: string) {\n this.actionName = actionName;\n this.executionStartTime = Date.now();\n\n // Generate unique execution ID for multi-node correlation\n const timestamp = Date.now();\n const random = Math.random().toString(36).substring(2, 9);\n this.executionId = `exec_${timestamp}_${random}`;\n\n this.logHeader();\n }\n\n /**\n * Log action header with execution context\n */\n private logHeader(): void {\n console.log(\n `[${this.actionName}] ========================================`\n );\n console.log(`[${this.actionName}] Execution started`);\n console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);\n\n // Detect if running in LIT node context vs browser\n const isLitNode = typeof (globalThis as any).litNodeContext !== \"undefined\";\n if (isLitNode) {\n console.log(`[${this.actionName}] Context: LIT Node`);\n console.log(\n `[${this.actionName}] Node: ${\n (globalThis as any).litNodeContext?.nodeAddress || \"unknown\"\n }`\n );\n } else {\n console.log(`[${this.actionName}] Context: Browser/Test`);\n }\n\n console.log(\n `[${this.actionName}] ========================================`\n );\n }\n\n stepStart(stepId: string, description: string): void {\n this.stepStartTimes.set(stepId, Date.now());\n const elapsed = Date.now() - this.executionStartTime;\n const remaining = this.TIMEOUT_MS - elapsed;\n console.log(`[Step ${stepId}] ${description}...`);\n console.log(\n `[Step ${stepId}] Elapsed: ${elapsed}ms | Remaining: ${remaining}ms`\n );\n }\n\n stepEnd(stepId: string, warnThresholdMs: number = 5000): void {\n const startTime = this.stepStartTimes.get(stepId);\n if (!startTime) {\n console.warn(\n `[Step ${stepId}] \u26A0\uFE0F stepEnd called without matching stepStart`\n );\n return;\n }\n\n const duration = Date.now() - startTime;\n this.stepDurations.set(stepId, duration);\n console.log(`[Step ${stepId}] Duration: ${duration}ms`);\n\n // Warn if step took longer than threshold\n if (duration > warnThresholdMs) {\n console.warn(\n `\u26A0\uFE0F [Step ${stepId}] Took ${duration}ms (> ${warnThresholdMs}ms threshold)`\n );\n }\n\n // Warn if approaching timeout\n const elapsed = Date.now() - this.executionStartTime;\n const remaining = this.TIMEOUT_MS - elapsed;\n if (remaining < 5000) {\n console.warn(\n `\u26A0\uFE0F [Step ${stepId}] Time remaining: ${remaining}ms (approaching timeout)`\n );\n }\n }\n\n log(stepId: string, message: string, ...rest: unknown[]): void {\n if (rest.length > 0) {\n console.log(`[Step ${stepId}] ${message}`, ...rest);\n } else {\n console.log(`[Step ${stepId}] ${message}`);\n }\n }\n\n warn(stepId: string, message: string): void {\n console.warn(`\u26A0\uFE0F [Step ${stepId}] ${message}`);\n }\n\n error(stepId: string, message: string): void {\n console.error(`\u274C [Step ${stepId}] ${message}`);\n }\n\n getElapsed(): number {\n return Date.now() - this.executionStartTime;\n }\n\n getRemaining(): number {\n return this.TIMEOUT_MS - this.getElapsed();\n }\n\n summary(): void {\n const totalDuration = Date.now() - this.executionStartTime;\n const remaining = this.TIMEOUT_MS - totalDuration;\n\n console.log(\n `[${this.actionName}] ========================================`\n );\n console.log(`[${this.actionName}] Execution Summary`);\n console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);\n console.log(\n `[${this.actionName}] Total time: ${(totalDuration / 1000).toFixed(2)}s`\n );\n console.log(`[${this.actionName}] Time remaining: ${remaining}ms`);\n\n // Log step timing breakdown\n if (this.stepDurations.size > 0) {\n console.log(`[${this.actionName}] Step breakdown:`);\n for (const [stepId, duration] of this.stepDurations.entries()) {\n const percent = ((duration / totalDuration) * 100).toFixed(1);\n console.log(\n `[${this.actionName}] Step ${stepId}: ${duration}ms (${percent}%)`\n );\n }\n }\n\n // Warnings for slow execution\n if (totalDuration > 20000) {\n console.warn(\n `\u26A0\uFE0F [${this.actionName}] Slow execution: ${(\n totalDuration / 1000\n ).toFixed(2)}s (${remaining}ms remaining)`\n );\n }\n if (remaining < 5000) {\n console.warn(\n `\u26A0\uFE0F [${this.actionName}] CRITICAL: Only ${remaining}ms remaining before timeout!`\n );\n }\n\n console.log(\n `[${this.actionName}] ========================================`\n );\n }\n\n getExecutionId(): string {\n return this.executionId;\n }\n\n isDebugEnabled(): boolean {\n return true;\n }\n}\n\n/**\n * LIT Action Logger factory\n */\nexport class LitActionLogger {\n /**\n * Create logger instance\n * Returns NoOpLogger when disabled (99% case), DebugLogger when enabled\n * @param actionName - Name of the LIT Action (for logging context)\n * @param debugAction - Optional override for globalThis.debugAction\n */\n static create(\n actionName: string = \"LIT Action\",\n debugAction?: boolean\n ): ILitActionLogger {\n const debugEnabled = isLitActionDebugEnabled(debugAction);\n\n if (debugEnabled) {\n return new DebugLogger(actionName);\n } else {\n // Return lightweight no-op stub - zero overhead for 99% of executions\n return new NoOpLogger();\n }\n }\n}\n", "/**\n * Lit SDK global parameter handling (chipotle / V8 style).\n *\n * `jsParams` is nested under `globalThis.jsParams`. Call\n * {@link mergeJsParamsOntoGlobalThis} once at the start of an action so code\n * that reads `globalThis.chain` (etc.) works with flat access. Use\n * {@link getLitActionParams} when you need a single object reference.\n */\n\n/** Minimal shape for the V8 nested bag (values are merged onto globalThis). */\nexport type LitJsParams = Record<string, unknown>;\n\ntype GlobalWithJsParams = typeof globalThis & { jsParams?: LitJsParams };\n\nfunction asGlobalWithJsParams(): GlobalWithJsParams {\n return globalThis as GlobalWithJsParams;\n}\n\n/**\n * Copy `globalThis.jsParams` onto `globalThis` so flat reads work (V8 compat).\n * No-op when `jsParams` is missing or not a plain object.\n */\nexport function mergeJsParamsOntoGlobalThis(): void {\n const g = asGlobalWithJsParams();\n const jp = g.jsParams;\n if (jp != null && typeof jp === \"object\" && !Array.isArray(jp)) {\n Object.assign(g, jp);\n }\n}\n\n/**\n * Parameter object for the current execution: nested `jsParams` (V8) or the global\n * object itself (V7). Prefer calling after {@link mergeJsParamsOntoGlobalThis} when\n * other code expects flat `globalThis` fields.\n */\nexport function getLitActionParams<\n T extends object = Record<string, unknown>,\n>(): T {\n const g = asGlobalWithJsParams();\n const jp = g.jsParams;\n if (jp != null && typeof jp === \"object\" && !Array.isArray(jp)) {\n return jp as T;\n }\n return g as unknown as T;\n}\n\n/**\n * Safe message extraction for `catch (error: unknown)` paths.\n */\nexport function getUnknownErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n if (typeof error === \"string\") {\n return error;\n }\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n\n/**\n * Whether an unknown error is an AbortError (fetch timeout / abort).\n */\nexport function isAbortError(error: unknown): boolean {\n return error instanceof Error && error.name === \"AbortError\";\n}\n", "/**\n * Bitcoin provider auth (LIT Action side).\n *\n * The BitcoinProviderRegistry stores one encrypted blob per\n * `(chainId, providerId)`. Historically that blob was a bare Esplora base URL.\n * To support commercial providers that require credentials, the blob may now be\n * a JSON object:\n *\n * { \"provider\": \"esplora\", \"url\": \"https://blockstream.info/api\" }\n * { \"provider\": \"maestro\", \"url\": \".../v0/esplora\", \"apiKey\": \"...\" }\n * { \"provider\": \"blockstream-enterprise\", \"url\": \".../api\",\n * \"clientId\": \"...\", \"clientSecret\": \"...\", \"tokenUrl\"?: \"...\" }\n *\n * Secrets only ever materialize HERE, inside the running LIT Action (the blob is\n * decrypted in-TEE). They are never in jsParams, on-chain plaintext, or the\n * bundle.\n *\n * Backward compatibility: a legacy plaintext that is a bare URL (does not parse\n * as a JSON object with a string `url`) is treated as\n * `{ provider: \"esplora\", url }` \u2014 existing registry entries keep working\n * without re-encryption.\n */\n\n// `fetch` is provided by the LIT runtime (used throughout the bitcoin modules).\ndeclare const fetch: any;\n\nexport type ProviderAuth =\n | { provider: \"esplora\" }\n | { provider: \"maestro\"; apiKey: string }\n | {\n provider: \"blockstream-enterprise\";\n clientId: string;\n clientSecret: string;\n tokenUrl?: string;\n };\n\nexport interface ParsedProvider {\n /** Esplora base URL (no trailing slash; paths are concatenated onto it). */\n url: string;\n /** Auth descriptor used to build request headers. */\n auth: ProviderAuth;\n}\n\n/** Default Blockstream Enterprise OAuth2 token endpoint (client-credentials). */\nconst BLOCKSTREAM_TOKEN_URL =\n \"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token\";\n\n/**\n * Reject non-`https://` URLs for any provider that sends credentials over the\n * wire (api-key header / OAuth secret \u2192 Bearer). Plain `http://` would leak the\n * secret in transit.\n */\nfunction requireHttps(u: string, label: string): void {\n if (!/^https:\\/\\//i.test(u.trim())) {\n throw new Error(\n `parseProviderPlaintext: ${label} must use https:// (credentials must not be sent over http)`,\n );\n }\n}\n\n/** Options for {@link parseProviderPlaintext}. */\nexport interface ParseProviderOptions {\n /**\n * Require `https://` for EVERY provider type, including credential-less\n * esplora and legacy bare URLs. Registry call sites set this whenever\n * `!policy.allowArbitraryBitcoinProvider` (sepolia/mainnet) \u2014 a plain-http\n * provider there hands an on-path attacker the balance feed the PKP signs\n * over (finding #3). Hardhat/regtest bypasses the registry entirely, so the\n * local `http://` daemon keeps working.\n */\n requireHttps?: boolean;\n}\n\n/**\n * Parse a decrypted provider plaintext into `{ url, auth }`.\n *\n * Accepts either a JSON object (when the trimmed plaintext starts with `{` and\n * has a non-empty string `url`) or a legacy bare URL string. Throws on a JSON\n * object that is missing `url` or required credentials for its provider type.\n * Credentialed provider types (maestro / blockstream-enterprise) ALWAYS\n * require https; `opts.requireHttps` extends that to esplora/bare URLs.\n */\nexport function parseProviderPlaintext(\n plaintext: string,\n opts?: ParseProviderOptions,\n): ParsedProvider {\n if (typeof plaintext !== \"string\" || plaintext.trim().length === 0) {\n throw new Error(\"parseProviderPlaintext: empty plaintext\");\n }\n const trimmed = plaintext.trim();\n\n // Legacy: bare URL string, no auth.\n if (!trimmed.startsWith(\"{\")) {\n if (opts?.requireHttps) requireHttps(trimmed, \"provider url\");\n return { url: trimmed, auth: { provider: \"esplora\" } };\n }\n\n let obj: any;\n try {\n obj = JSON.parse(trimmed);\n } catch (e: any) {\n throw new Error(\n `parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${\n e?.message ?? String(e)\n }`,\n );\n }\n if (typeof obj.url !== \"string\" || obj.url.trim().length === 0) {\n throw new Error(\n \"parseProviderPlaintext: JSON provider config missing non-empty string `url`\",\n );\n }\n const url = obj.url.trim();\n\n switch (obj.provider) {\n case undefined:\n case \"esplora\":\n if (opts?.requireHttps) requireHttps(url, \"esplora provider url\");\n return { url, auth: { provider: \"esplora\" } };\n\n case \"maestro\": {\n if (typeof obj.apiKey !== \"string\" || obj.apiKey.length === 0) {\n throw new Error(\n \"parseProviderPlaintext: maestro provider requires a non-empty `apiKey`\",\n );\n }\n // Credentials travel in request headers \u2014 refuse to send them over http.\n requireHttps(url, \"maestro provider url\");\n return { url, auth: { provider: \"maestro\", apiKey: obj.apiKey } };\n }\n\n case \"blockstream-enterprise\": {\n if (\n typeof obj.clientId !== \"string\" ||\n obj.clientId.length === 0 ||\n typeof obj.clientSecret !== \"string\" ||\n obj.clientSecret.length === 0\n ) {\n throw new Error(\n \"parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`\",\n );\n }\n // Credentials (client secret \u2192 token \u2192 Bearer) travel over the wire.\n requireHttps(url, \"blockstream-enterprise provider url\");\n const hasTokenUrl =\n typeof obj.tokenUrl === \"string\" && obj.tokenUrl.length > 0;\n if (hasTokenUrl) requireHttps(obj.tokenUrl, \"blockstream-enterprise tokenUrl\");\n return {\n url,\n auth: {\n provider: \"blockstream-enterprise\",\n clientId: obj.clientId,\n clientSecret: obj.clientSecret,\n ...(hasTokenUrl ? { tokenUrl: obj.tokenUrl } : {}),\n },\n };\n }\n\n default:\n throw new Error(\n `parseProviderPlaintext: unknown provider type \"${String(obj.provider)}\"`,\n );\n }\n}\n\n/**\n * Per-run OAuth token cache. LIT Action module state is fresh per execution, so\n * this Map lives only for the current run. Keyed by `${tokenUrl}\\n${clientId}`\n * so concurrent fetches (e.g. the parallel utxo+tip `Promise.all`) share ONE\n * token exchange. Rejected entries are evicted so a retry can re-attempt.\n */\nconst oauthTokenCache = new Map<string, Promise<string>>();\n\n/** Default timeout (ms) for the OAuth token exchange \u2014 bounds the extra round-trip. */\nconst OAUTH_TOKEN_TIMEOUT_MS = 10_000;\n\nasync function getBlockstreamBearerToken(\n auth: {\n clientId: string;\n clientSecret: string;\n tokenUrl?: string;\n },\n timeoutMs?: number,\n): Promise<string> {\n const tokenUrl = auth.tokenUrl || BLOCKSTREAM_TOKEN_URL;\n const key = `${tokenUrl}\\n${auth.clientId}`;\n const cached = oauthTokenCache.get(key);\n if (cached) return cached;\n\n const promise = (async () => {\n const body =\n `grant_type=client_credentials` +\n `&client_id=${encodeURIComponent(auth.clientId)}` +\n `&client_secret=${encodeURIComponent(auth.clientSecret)}` +\n `&scope=openid`;\n // The token endpoint is NOT covered by any caller's request AbortController,\n // so bound it explicitly \u2014 otherwise a slow/hung token server stalls the Lit\n // Action up to the global ~30s kill.\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n timeoutMs && timeoutMs > 0 ? timeoutMs : OAUTH_TOKEN_TIMEOUT_MS,\n );\n let resp: any;\n try {\n resp = await fetch(tokenUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timeoutId);\n }\n if (!resp.ok) {\n throw new Error(\n `Blockstream OAuth token exchange failed: ${resp.status} ${resp.statusText}`,\n );\n }\n const json: any = await resp.json();\n const token = json?.access_token;\n if (typeof token !== \"string\" || token.length === 0) {\n throw new Error(\n \"Blockstream OAuth token exchange returned no access_token\",\n );\n }\n return token;\n })();\n\n // Evict on rejection so a transient failure isn't sticky for the rest of the run.\n promise.catch(() => oauthTokenCache.delete(key));\n oauthTokenCache.set(key, promise);\n return promise;\n}\n\n/**\n * Resolve the HTTP headers to attach to an Esplora request for the given auth.\n *\n * - `esplora` (or undefined) \u2192 no auth headers\n * - `maestro` \u2192 `{ \"api-key\": <key> }`\n * - `blockstream-enterprise` \u2192 OAuth client-credentials exchange \u2192 `Authorization: Bearer <token>`\n */\nexport async function authHeaders(\n auth: ProviderAuth | undefined,\n timeoutMs?: number,\n): Promise<Record<string, string>> {\n if (!auth) return {};\n switch (auth.provider) {\n case \"esplora\":\n return {};\n case \"maestro\":\n return { \"api-key\": auth.apiKey };\n case \"blockstream-enterprise\": {\n const token = await getBlockstreamBearerToken(auth, timeoutMs);\n return { Authorization: `Bearer ${token}` };\n }\n default:\n return {};\n }\n}\n\n/**\n * Auth-aware GET with an END-TO-END timeout budget.\n *\n * A request to an authenticated provider has two sequential network legs \u2014 the\n * OAuth token exchange (Blockstream Enterprise) and the data request itself.\n * Bounding each leg independently would let a single logical request run up to\n * `2 \u00D7 timeoutMs`, which can collide with Lit's ~30s execution limit. Instead we\n * pin one deadline at the start: the token exchange is bounded by `timeoutMs`,\n * and the data fetch only gets the REMAINING time. Total wall-time \u2264 `timeoutMs`.\n *\n * Maestro/esplora have no token leg, so the data fetch gets ~the full budget.\n * Returns the raw fetch Response; callers handle `.ok` / `.json()` as today.\n */\nexport async function authedFetch(\n url: string,\n auth: ProviderAuth | undefined,\n timeoutMs: number,\n): Promise<any> {\n const deadline = Date.now() + timeoutMs;\n const headers = await authHeaders(auth, timeoutMs);\n const remaining = Math.max(1, deadline - Date.now());\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), remaining);\n try {\n return await fetch(url, { headers, signal: controller.signal });\n } finally {\n clearTimeout(timeoutId);\n }\n}\n", "/**\n * Bitcoin Data Provider Module\n *\n * Provides Bitcoin network data with support for future consensus mechanisms.\n * Current implementation: Single provider with fallback support\n * Future implementation: 2-of-3 provider consensus\n *\n * This module centralizes all Bitcoin data queries to maintain a consistent\n * interface that won't break when upgrading to multi-provider consensus.\n */\n\nimport {\n BitcoinDataProviderConfig,\n UTXO,\n UTXOSet,\n} from \"../interfaces/chunks/vault-balance.i\";\nimport { IBitcoinDataProvider } from \"../interfaces/chunks/bitcoin-data-provider.i\";\nimport { LitActionLogger } from \"./lit-action-logger.module\";\nimport {\n MAX_BTC_AMOUNT,\n UTXO_QUERY_MAX_RETRIES,\n UTXO_QUERY_RETRY_DELAY_MS,\n} from \"../constants\";\n\n/**\n * Assert a provider-reported satoshi amount is a sane integer before it is\n * promoted to a `bigint` the protocol signs over (remediation P1/#13). A\n * non-integer, negative, or supply-exceeding value is provider corruption or\n * manipulation \u2014 `BigInt()` would either throw opaquely (fractions) or admit\n * the bogus magnitude (negatives / absurd values) into a signed balance.\n */\nfunction assertSaneSatoshis(value: number, context: string): void {\n if (!Number.isSafeInteger(value) || value < 0 || value > MAX_BTC_AMOUNT) {\n throw new Error(\n `${context}: satoshi value ${value} is not a sane amount ` +\n `(must be an integer in [0, ${MAX_BTC_AMOUNT}])`,\n );\n }\n}\nimport {\n getUnknownErrorMessage,\n isAbortError,\n} from \"./lit-global-bootstrap\";\nimport { litDebugLog } from \"./lit-action-debug\";\nimport { authHeaders } from \"./bitcoin-provider-auth\";\n\n/** Opening words of every tip-read failure message (kept stable for operators). */\nconst TIP_READ_FAILURE_PREFIX = \"Bitcoin tip-height read failed\";\n\n/**\n * One provider could not state the chain tip, so no confirmation depth exists\n * to report. Distinct from every other provider error on purpose:\n *\n * - `getTransaction`'s own boundary translates a message containing \"404\" into\n * `null` (\"transaction not found\"). The tip endpoint is a DIFFERENT resource\n * on the same provider, so a 404 there must not be read as a missing\n * transaction \u2014 that `null` is the fabricated-depth bug in another costume.\n * - The consensus layer treats THIS class, and only this class, as provider\n * ABSENCE (quorum reduced, floor still enforced). Every other failure \u2014\n * notably a provider that answers \"I have never seen that transaction\" \u2014\n * stays fatal, because it is a claim about the chain, not an outage, and it\n * is the signature of a fabricated UTXO (review 2026-07-15 P1).\n *\n * Identified by a structural marker rather than `instanceof`: the bundler and\n * downlevel transpilation can break the prototype chain across the action\n * bundle, and a mis-identified error here fails in the dangerous direction.\n */\nexport class BitcoinTipUnreadableError extends Error {\n readonly isBitcoinTipUnreadable = true as const;\n constructor(message: string) {\n super(message);\n this.name = \"BitcoinTipUnreadableError\";\n }\n}\n\n/** True when `error` is a {@link BitcoinTipUnreadableError} (bundle-safe check). */\nexport function isBitcoinTipUnreadableError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { isBitcoinTipUnreadable?: unknown }).isBitcoinTipUnreadable ===\n true\n );\n}\n\n/** Bitcoin Core `listunspent` row (subset used here) */\ninterface RpcUnspentOutput {\n txid: string;\n vout: number;\n amount: number;\n confirmations: number;\n}\n\n/** Esplora / Blockstream UTXO JSON row before normalization */\ninterface EsploraUtxoRow {\n txid?: string;\n vout?: number;\n n?: number;\n value?: number;\n satoshis?: number;\n confirmations?: number;\n status?: {\n confirmed?: boolean;\n block_height?: number;\n };\n}\n\n/** `/address/:addr` chain_stats response (Esplora) */\ninterface EsploraAddressChainStats {\n chain_stats?: {\n funded_txo_sum?: number;\n spent_txo_sum?: number;\n };\n}\n\n/**\n * Bitcoin Data Provider\n *\n * Fetches UTXO data from Bitcoin network.\n * Interface designed to remain stable when adding multi-provider consensus.\n */\nexport class BitcoinDataProvider implements IBitcoinDataProvider {\n private config: BitcoinDataProviderConfig;\n private timeout: number;\n private logger: ReturnType<typeof LitActionLogger.create>;\n\n constructor(config: BitcoinDataProviderConfig) {\n // Fail closed (2026-10-27 ruling): a provider with no URL must not exist.\n // Before this guard, `getTransactionOutputs` answered `null` for a blank\n // URL \u2014 \"transaction not found\" \u2014 which the self-change consensus reader\n // counts as a \"not self-change\" vote, a silent fallback contrary to \u00A71.\n if (\n typeof config.providerUrl !== \"string\" ||\n config.providerUrl.trim().length === 0\n ) {\n throw new Error(\n \"BitcoinDataProvider: providerUrl must be a non-empty string; refusing to construct a provider that cannot be queried\",\n );\n }\n this.config = config;\n // 15 seconds to leave time for other operations in LIT action (30s total limit)\n this.timeout = config.timeout || 15000;\n this.logger = LitActionLogger.create(\"BitcoinDataProvider\");\n }\n\n /**\n * Merge per-provider auth headers into a base header set. No-op for public\n * Esplora / regtest faucet (no `auth`); attaches the `api-key` header for\n * Maestro and performs a (memoized) OAuth exchange \u2192 `Bearer` for Blockstream\n * Enterprise. Awaited at every fetch site so a single run shares one token.\n */\n private async withAuth(\n base: Record<string, string> = {},\n ): Promise<Record<string, string>> {\n // Pass this.timeout so the OAuth token exchange (Blockstream Enterprise) is\n // bounded by the same budget as the data request it precedes.\n return { ...base, ...(await authHeaders(this.config.auth, this.timeout)) };\n }\n\n /**\n * Get current Bitcoin block height from provider\n */\n private async getCurrentBlockHeight(): Promise<number> {\n this.logger.stepStart(\"0\", \"getCurrentBlockHeight\");\n // If RPC helper is provided, use it\n if (this.config.rpcHelper) {\n const blockCount = await this.config.rpcHelper.getBlockCount();\n this.logger.stepEnd(\"0\");\n return blockCount;\n }\n\n // Fetch from Esplora API\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const t0 = Date.now();\n const response = await fetch(\n `${this.config.providerUrl}/blocks/tip/height`,\n {\n signal: controller.signal,\n headers: await this.withAuth({\n Accept: \"text/plain\",\n \"User-Agent\": \"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)\",\n \"ngrok-skip-browser-warning\": \"true\",\n }),\n }\n );\n\n clearTimeout(timeoutId);\n litDebugLog(\n `[BitcoinDataProvider] blocks/tip/height ${Date.now() - t0}ms (timeout budget ${this.timeout}ms)`,\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch block height: ${response.status} ${response.statusText}`\n );\n }\n\n const heightText = await response.text();\n \n // FAIL FAST: Detect HTML response (wrong URL pointing to web interface)\n if (heightText.trim().startsWith('<!DOCTYPE') || heightText.trim().startsWith('<html')) {\n throw new Error(\n `Bitcoin RPC endpoint returned HTML instead of block height. ` +\n `URL may be pointing to web interface instead of API endpoint. ` +\n `Expected: plain text number, Got: HTML document. ` +\n `Check that URL ends with /api/esplora (not root /)`\n );\n }\n \n const height = parseInt(heightText.trim(), 10);\n\n if (isNaN(height)) {\n // Truncate response to prevent HTML dump catastrophe\n const truncated = heightText.length > 200 \n ? heightText.substring(0, 200) + '... (truncated)'\n : heightText;\n throw new Error(`Invalid block height response: ${truncated}`);\n }\n\n this.logger.stepEnd(\"0\");\n return height;\n } catch (error: unknown) {\n clearTimeout(timeoutId);\n this.logger.stepEnd(\"0\");\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n\n /**\n * Fetch all UTXOs for a Bitcoin address\n *\n * @param address - Bitcoin address (legacy, segwit, or taproot)\n * @returns Array of UTXOs\n */\n async getUTXOs(address: string): Promise<UTXO[]> {\n this.logger.log(\"0\", `Original address: \"${address}\"`);\n\n // Strip network prefix if present (e.g., \"REGTEST_address\" -> \"address\")\n const cleanAddress = this.stripNetworkPrefix(address);\n\n this.logger.log(\"0\", `Cleaned address: \"${cleanAddress}\"`);\n\n // If RPC helper is provided (for regtest/testing), use it directly\n if (this.config.rpcHelper) {\n return await this.fetchUTXOsFromRPC(cleanAddress);\n }\n\n // Try primary provider first\n try {\n return await this.fetchUTXOsFromProvider(\n this.config.providerUrl,\n cleanAddress\n );\n } catch (error: unknown) {\n this.logger.warn(\n \"0\",\n `Primary provider failed: ${getUnknownErrorMessage(error)}`,\n );\n\n // Try fallback providers if available\n if (\n this.config.fallbackProviders &&\n this.config.fallbackProviders.length > 0\n ) {\n const sortedFallbacks = [...this.config.fallbackProviders].sort(\n (a, b) => a.priority - b.priority\n );\n\n for (const fallback of sortedFallbacks) {\n try {\n this.logger.log(\n \"0\",\n `Trying fallback: ${fallback.name} (${fallback.url})`\n );\n return await this.fetchUTXOsFromProvider(\n fallback.url,\n cleanAddress\n );\n } catch (fallbackError: unknown) {\n this.logger.warn(\n \"0\",\n `Fallback ${fallback.name} failed: ${getUnknownErrorMessage(fallbackError)}`,\n );\n continue;\n }\n }\n }\n\n throw new Error(`Failed to fetch UTXOs: ${getUnknownErrorMessage(error)}`);\n }\n }\n\n /**\n * Strip network prefix from Bitcoin address\n *\n * Addresses may be stored with network prefix (e.g., \"REGTEST_address\")\n * but APIs expect clean addresses without prefix.\n *\n * @param address - Address with optional prefix\n * @returns Clean address without prefix\n */\n private stripNetworkPrefix(address: string): string {\n const prefixPattern = /^(REGTEST_|TESTNET_|MAINNET_)/;\n return address.replace(prefixPattern, \"\");\n }\n\n /**\n * Fetch UTXOs using Bitcoin RPC (for regtest/testing)\n */\n private async fetchUTXOsFromRPC(address: string): Promise<UTXO[]> {\n if (!this.config.rpcHelper) {\n throw new Error(\"RPC helper not configured\");\n }\n\n const wallet = this.config.rpcWallet || \"\";\n const unspentOutputs = await this.config.rpcHelper.listUnspent(\n wallet,\n address\n );\n\n const utxos: UTXO[] = (unspentOutputs as RpcUnspentOutput[]).map(\n (utxo) => {\n const satNumber = Math.round(utxo.amount * 100000000); // BTC to satoshis\n assertSaneSatoshis(satNumber, `fetchUTXOsFromRPC ${utxo.txid}:${utxo.vout}`);\n return {\n txid: utxo.txid,\n vout: utxo.vout,\n satoshis: BigInt(satNumber),\n confirmations: utxo.confirmations,\n };\n },\n );\n\n return utxos;\n }\n\n /**\n * Parse Esplora/Blockstream/Mempool.space UTXO response\n *\n * Supports multiple formats:\n * - Esplora format: {txid, vout, value, status: {confirmed, block_height}}\n * - Blockstream format: {txid, vout, value, confirmations}\n *\n * @param data Raw response from provider API\n * @param currentBlockHeight Current block height (for calculating confirmations from block_height)\n * @returns Array of normalized UTXOs\n */\n private parseBlockstreamUTXOs(\n data: unknown,\n currentBlockHeight: number,\n ): UTXO[] {\n if (!Array.isArray(data)) {\n throw new Error(\"Invalid Blockstream response format: expected an array\");\n }\n\n const rows = data as EsploraUtxoRow[];\n\n // Normalize UTXO format (different providers may have different field names)\n const utxos: UTXO[] = [];\n for (const utxo of rows) {\n // Calculate confirmations based on format\n let confirmations = 0;\n\n // Check for Esplora format (status.confirmed and status.block_height)\n if (utxo.status && typeof utxo.status === \"object\") {\n if (utxo.status.confirmed) {\n // For Esplora format: calculate confirmations from block heights\n // confirmations = current_height - tx_block_height + 1\n if (\n utxo.status.block_height !== undefined &&\n utxo.status.block_height > 0\n ) {\n confirmations = currentBlockHeight - utxo.status.block_height + 1;\n } else {\n // Confirmed but no block_height (or block_height is 0)\n // This handles regtest where blocks are mined instantly\n confirmations = 1;\n }\n }\n // If not confirmed, confirmations remains 0\n } else if (utxo.confirmations !== undefined) {\n // Blockstream format: direct confirmations field\n confirmations = utxo.confirmations;\n }\n\n const txid = utxo.txid;\n const vout =\n utxo.vout !== undefined ? utxo.vout : utxo.n;\n const satRaw =\n utxo.value !== undefined ? utxo.value : utxo.satoshis;\n if (txid === undefined || vout === undefined || satRaw === undefined) {\n throw new Error(\n \"Invalid UTXO row: missing txid, vout/n, or value/satoshis\",\n );\n }\n assertSaneSatoshis(satRaw, `parseBlockstreamUTXOs ${txid}:${vout}`);\n\n utxos.push({\n txid,\n vout,\n satoshis: BigInt(satRaw),\n confirmations,\n });\n }\n\n return utxos;\n }\n\n /**\n * Internal method to fetch UTXOs from a specific provider\n *\n * Supports standard Esplora API format:\n * - Standard format: {providerUrl}/address/{address}/utxo\n * - providerUrl must include full base path (e.g., \"http://localhost:3002/api/esplora\")\n */\n private async fetchUTXOsFromProvider(\n providerUrl: string,\n address: string\n ): Promise<UTXO[]> {\n this.logger.stepStart(\"1\", \"fetchUTXOsFromProvider\");\n // Standard Esplora API format only\n // providerUrl must include full base path (e.g., \"http://localhost:3002/api/esplora\")\n // Canonical Esplora endpoint is SINGULAR `/utxo` (Blockstream + Maestro). Our regtest\n // faucet also serves `/utxo` (and keeps a `/utxos` alias for older deployed bundles).\n const endpoint = `${providerUrl}/address/${address}/utxo`;\n this.logger.log(\"1\", `Fetching UTXOs from ${endpoint}`);\n\n // Run block-height fetch and UTXO fetch in parallel \u2014 saves ~8s vs sequential\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const tParallel = Date.now();\n const [currentBlockHeight, response] = await Promise.all([\n this.getCurrentBlockHeight(),\n fetch(endpoint, {\n signal: controller.signal,\n headers: await this.withAuth({\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)\",\n \"ngrok-skip-browser-warning\": \"true\", // Skip ngrok browser warning page\n }),\n }),\n ]);\n\n clearTimeout(timeoutId);\n litDebugLog(\n `[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now() - tParallel}ms endpoint tail .../${address.slice(0, 12)}.../utxo (timeout budget ${this.timeout}ms)`,\n );\n this.logger.log(\"1\", `Current block height: ${currentBlockHeight}`);\n\n if (!response.ok) {\n throw new Error(\n `Bitcoin provider error: ${response.status} ${response.statusText}`\n );\n }\n\n // Get response text first to detect HTML before JSON parsing\n const responseText = await response.text();\n \n // FAIL FAST: Detect HTML response (wrong URL pointing to web interface)\n if (responseText.trim().startsWith('<!DOCTYPE') || responseText.trim().startsWith('<html')) {\n throw new Error(\n `Bitcoin RPC endpoint returned HTML instead of JSON. ` +\n `URL may be pointing to web interface instead of API endpoint. ` +\n `Expected: JSON array of UTXOs, Got: HTML document. ` +\n `Check that URL ends with /api/esplora (not root /)`\n );\n }\n \n let data;\n try {\n data = JSON.parse(responseText) as unknown;\n } catch (parseError: unknown) {\n // Truncate response to prevent catastrophic logs\n const truncated = responseText.length > 200\n ? responseText.substring(0, 200) + '... (truncated)'\n : responseText;\n throw new Error(\n `Failed to parse JSON response: ${getUnknownErrorMessage(parseError)}. Response: ${truncated}`,\n );\n }\n\n // Log the parsed data\n this.logger.log(\n \"1\",\n `Raw API Response: ${JSON.stringify(data, null, 2)}`\n );\n\n // Parse standard Esplora/Blockstream format with current block height\n const utxos = this.parseBlockstreamUTXOs(data, currentBlockHeight);\n this.logger.stepEnd(\"1\");\n return utxos;\n } catch (error: unknown) {\n clearTimeout(timeoutId);\n this.logger.stepEnd(\"1\");\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n\n /**\n * Get complete UTXO set with balance summary\n *\n * This is the SINGLE method that vault-balance module should call.\n * Returns everything needed to know about Bitcoin network state for an address.\n *\n * @param address - Bitcoin address\n * @param minConfirmations - Minimum confirmations for \"confirmed\" status (REQUIRED - caller must specify)\n * @returns Complete UTXO set with balance breakdown\n */\n async getUTXOSet(\n address: string,\n minConfirmations: number\n ): Promise<UTXOSet> {\n // Retry logic to handle transient failures from Bitcoin provider\n let utxos: UTXO[] = [];\n let lastError: Error | null = null;\n const maxRetries = UTXO_QUERY_MAX_RETRIES;\n const retryDelay = UTXO_QUERY_RETRY_DELAY_MS;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n this.logger.log(\"2\", `UTXO query attempt ${attempt}/${maxRetries}...`);\n utxos = await this.getUTXOs(address);\n this.logger.log(\"2\", `UTXO query succeeded on attempt ${attempt}`);\n lastError = null;\n break; // Success - exit retry loop\n } catch (error: unknown) {\n lastError =\n error instanceof Error ? error : new Error(getUnknownErrorMessage(error));\n this.logger.error(\n \"2\",\n `UTXO query failed on attempt ${attempt}: ${getUnknownErrorMessage(error)}`,\n );\n\n if (attempt < maxRetries) {\n this.logger.log(\"2\", `Waiting ${retryDelay}ms before retry...`);\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n }\n }\n }\n\n // If all retries failed, throw the last error\n if (lastError) {\n throw new Error(\n `Failed to query UTXOs after ${maxRetries} attempts: ${lastError.message}`,\n );\n }\n\n const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.satoshis, 0n);\n const confirmedBalance = utxos\n .filter((utxo) => utxo.confirmations >= minConfirmations)\n .reduce((sum, utxo) => sum + utxo.satoshis, 0n);\n const unconfirmedBalance = totalBalance - confirmedBalance;\n\n return {\n utxos,\n totalBalance,\n totalUTXOs: utxos.length,\n confirmedBalance,\n unconfirmedBalance,\n };\n }\n\n /**\n * Get balance for a Bitcoin address (fast, no UTXO details)\n *\n * WARNING: This method does NOT validate individual UTXOs.\n * Use ONLY for non-critical balance display, never for authorization validation.\n * For authorization/security: ALWAYS use getUTXOSet() with full UTXO validation.\n *\n * Uses Esplora /address/:address endpoint to get confirmed balance from chain_stats.\n *\n * @param address - Bitcoin address\n * @returns Balance in satoshis (confirmed balance only)\n * @throws Error if the request fails or response is invalid\n */\n async getBalance(address: string): Promise<bigint> {\n const cleanAddress = this.stripNetworkPrefix(address);\n const endpoint = `${this.config.providerUrl}/address/${cleanAddress}`;\n this.logger.log(\"3\", `Fetching balance from ${endpoint}`);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const t0 = Date.now();\n const response = await fetch(endpoint, {\n signal: controller.signal,\n headers: await this.withAuth({\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)\",\n \"ngrok-skip-browser-warning\": \"true\",\n }),\n });\n\n clearTimeout(timeoutId);\n litDebugLog(\n `[BitcoinDataProvider] GET address chain_stats ${Date.now() - t0}ms (timeout budget ${this.timeout}ms)`,\n );\n\n if (!response.ok) {\n throw new Error(\n `Bitcoin provider error: ${response.status} ${response.statusText}`\n );\n }\n\n const data = (await response.json()) as EsploraAddressChainStats;\n\n // Validate response structure\n if (!data.chain_stats) {\n throw new Error(\"Invalid response: missing chain_stats\");\n }\n\n const fundedTxoSum = data.chain_stats.funded_txo_sum;\n const spentTxoSum = data.chain_stats.spent_txo_sum;\n\n if (fundedTxoSum === undefined || spentTxoSum === undefined) {\n throw new Error(\n `Invalid response: missing required fields. funded_txo_sum: ${fundedTxoSum}, spent_txo_sum: ${spentTxoSum}`\n );\n }\n\n // Calculate confirmed balance: funded - spent. Guard both operands and\n // the result before the bigint promotion \u2014 a negative difference means\n // the provider served corrupt chain_stats (spent > funded is impossible\n // on an honest view).\n assertSaneSatoshis(fundedTxoSum, `getBalance ${cleanAddress} funded_txo_sum`);\n assertSaneSatoshis(spentTxoSum, `getBalance ${cleanAddress} spent_txo_sum`);\n const confirmedBalance = fundedTxoSum - spentTxoSum;\n assertSaneSatoshis(confirmedBalance, `getBalance ${cleanAddress} confirmed balance`);\n const balance = BigInt(confirmedBalance);\n\n this.logger.log(\"3\", `Balance: ${balance.toString()} sats`);\n this.logger.log(\n \"3\",\n ` - Funded: ${fundedTxoSum} sats, Spent: ${spentTxoSum} sats`\n );\n\n return balance;\n } catch (error: unknown) {\n clearTimeout(timeoutId);\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${this.timeout}ms`);\n }\n const errorMessage = getUnknownErrorMessage(error);\n this.logger.log(\"3\", `Balance fetch failed: ${errorMessage}`);\n throw new Error(\n `Failed to fetch Bitcoin balance for address ${cleanAddress}: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Get transaction with confirmation count\n *\n * Checks if transaction exists on Bitcoin network and returns confirmation count.\n * Used to validate authorized spends have been broadcasted.\n *\n * @param txid - Transaction ID to check\n * @returns Transaction with confirmation count, or null if not found\n */\n async getTransaction(\n txid: string\n ): Promise<{ txid: string; confirmations: number } | null> {\n // If RPC helper is provided (for regtest/testing), use it directly\n if (this.config.rpcHelper) {\n try {\n const wallet = this.config.rpcWallet || \"\";\n const tx = await this.config.rpcHelper.getTransaction(wallet, txid);\n return {\n txid: tx.txid,\n confirmations: tx.confirmations || 0,\n };\n } catch (error: unknown) {\n // Transaction not found\n const msg = getUnknownErrorMessage(error);\n const code =\n error !== null &&\n typeof error === \"object\" &&\n \"code\" in error &&\n typeof (error as { code: unknown }).code === \"number\"\n ? (error as { code: number }).code\n : undefined;\n if (msg.includes(\"Invalid or non-wallet transaction\") || code === -5) {\n return null;\n }\n throw error;\n }\n }\n\n // Try provider API\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const t0 = Date.now();\n const response = await fetch(`${this.config.providerUrl}/tx/${txid}`, {\n signal: controller.signal,\n headers: await this.withAuth(),\n });\n\n clearTimeout(timeoutId);\n litDebugLog(\n `[BitcoinDataProvider] GET tx/${txid.slice(0, 10)}\u2026 ${Date.now() - t0}ms (timeout budget ${this.timeout}ms)`,\n );\n\n if (!response.ok) {\n if (response.status === 404) {\n return null; // Transaction not found\n }\n throw new Error(\n `Bitcoin provider error: ${response.status} ${response.statusText}`\n );\n }\n\n const data = (await response.json()) as {\n txid?: string;\n status?: { confirmed?: boolean; block_height?: number };\n };\n\n // Blockstream / Esplora API format. Compute actual confirmation depth\n // by subtracting the tx's block_height from the current tip height:\n // confirmations = current_height - block_height + 1\n // Previously this hard-coded `1` whenever the tx was confirmed, making\n // any caller that gates on a confirmation threshold (e.g. the\n // stale-spend recovery validator's `MIN_CONFIRMATIONS_DEFAULT = 6`)\n // structurally unable to pass. Mirrors the depth math already used by\n // `getUtxos` lower in this module.\n if (data.status) {\n if (!data.status.confirmed || !data.status.block_height) {\n return { txid: data.txid ?? txid, confirmations: 0 };\n }\n // Depth is derived from the chain tip, and there is no honest way to\n // guess it. Until 2026-09-23 all three tip-read failure modes\n // (endpoint not ok / unparseable body / fetch threw) answered\n // `confirmations: 1`. On a BTC-custody protocol that is the most\n // dangerous value this module can invent: confirmation depth is\n // exactly what the spend and balance gates consult, and `1` already\n // clears every one-confirmation gate (regtest/sepolia thresholds, and\n // each provider's depth vote on the stale-spend recovery path).\n // \"Could not read the tip\" must never become \"it has a confirmation\",\n // so the read throws, named \u2014 see `fetchTipHeight`. The self-change\n // consensus layer above treats a provider that cannot state the tip as\n // ABSENT from the quorum, never as agreeing, and fails loudly once the\n // survivors fall below `policy.minConsensusProviders`; the stale-spend\n // recovery path keeps its stricter rule and refuses outright.\n const tipHeight = await this.fetchTipHeight(controller.signal);\n const depth = tipHeight - data.status.block_height + 1;\n return {\n txid: data.txid ?? txid,\n confirmations: depth > 0 ? depth : 0,\n };\n }\n\n return null;\n } catch (error: unknown) {\n clearTimeout(timeoutId);\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${this.timeout}ms`);\n }\n // A tip-height failure is NOT \"transaction not found\" \u2014 it is a refusal\n // to state a depth. It must escape intact, BEFORE the 404 heuristic\n // below, which would otherwise turn a 404 from `/blocks/tip/height`\n // into `null` and let callers silently drop a transaction that exists.\n if (isBitcoinTipUnreadableError(error)) {\n throw error;\n }\n // 404 means transaction not found\n if (getUnknownErrorMessage(error).includes(\"404\")) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Current chain tip height from THIS provider \u2014 or throw.\n *\n * Every exit is a throw naming the provider and the precise failure, because\n * the only alternative is inventing a confirmation depth (see the call site).\n * The single `try` exists solely to attach that name to a transport-level\n * rejection (DNS, TLS, connection reset, abort); it re-throws the cause\n * verbatim inside the message and never substitutes a value \u2014 authorized for\n * this case by the Batch 2 plan, \u00A7C2.\n *\n * @param signal - The caller's AbortSignal, so this read shares the same\n * timeout budget as the transaction fetch it serves.\n */\n private async fetchTipHeight(signal: AbortSignal): Promise<number> {\n const endpoint = `${this.config.providerUrl}/blocks/tip/height`;\n // `Awaited<ReturnType<typeof fetch>>`, not `Response`: inside a Lit Action\n // the ambient `fetch` resolves to the runtime's narrower `LitFetchResponse`.\n let tipResp: Awaited<ReturnType<typeof fetch>>;\n try {\n tipResp = await fetch(endpoint, {\n signal,\n headers: await this.withAuth(),\n });\n } catch (error: unknown) {\n throw new BitcoinTipUnreadableError(\n `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} threw \u2014 ${getUnknownErrorMessage(error)}`,\n );\n }\n if (!tipResp.ok) {\n throw new BitcoinTipUnreadableError(\n `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} \u2192 ${tipResp.status} ${tipResp.statusText}`,\n );\n }\n const tipBody = (await tipResp.text()).trim();\n const tipHeight = Number.parseInt(tipBody, 10);\n if (!Number.isFinite(tipHeight) || tipHeight <= 0) {\n throw new BitcoinTipUnreadableError(\n `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} returned an unusable tip height ` +\n `\"${tipBody.slice(0, 64)}\"`,\n );\n }\n return tipHeight;\n }\n\n /**\n * Get outputs (vouts) of a Bitcoin transaction\n *\n * Fetches the full transaction from the Esplora API and returns all outputs\n * with their index, scriptPubKey, address, and value.\n *\n * Used to canonicalize UTXO vout index when the Esplora UTXO endpoint\n * returns a wrong vout (a known faucet API bug in regtest environments).\n *\n * @param txid - Transaction ID\n * @returns Array of transaction outputs with index, or null if not found\n */\n async getTransactionOutputs(\n txid: string\n ): Promise<Array<{ index: number; scriptpubkey?: string; scriptpubkey_address?: string; value: number }> | null> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(`${this.config.providerUrl}/tx/${txid}`, {\n signal: controller.signal,\n headers: await this.withAuth(),\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n if (response.status === 404) {\n return null;\n }\n throw new Error(\n `Bitcoin provider error: ${response.status} ${response.statusText}`\n );\n }\n\n const data = await response.json() as {\n vout?: Array<{\n scriptpubkey?: string;\n scriptpubkey_address?: string;\n value?: number;\n }>;\n };\n\n if (!data.vout || !Array.isArray(data.vout)) {\n return null;\n }\n\n return data.vout.map((output, index) => {\n // The withdrawal canonicalization matches on VALUE \u2014 a missing value\n // silently defaulted to 0 would fail every match and surface as a\n // misleading \"no vault output matches\" abort. A response without a\n // per-output value is malformed: fail loud here instead.\n if (output.value === undefined) {\n throw new Error(\n `getTransactionOutputs(${txid}): output ${index} is missing its ` +\n `value \u2014 malformed provider response, refusing to return ` +\n `outputs that cannot be value-verified`,\n );\n }\n assertSaneSatoshis(\n output.value,\n `getTransactionOutputs(${txid}) output ${index}`,\n );\n return {\n index,\n scriptpubkey: output.scriptpubkey,\n scriptpubkey_address: output.scriptpubkey_address,\n value: output.value,\n };\n });\n } catch (error: unknown) {\n clearTimeout(timeoutId);\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n\n // FUTURE: Multi-provider consensus methods will be added here\n // async getUTXOsWithConsensus(address: string): Promise<UTXO[]> {\n // // Fetch from all providers\n // // Return UTXOs that appear in 2+ sources\n // // Use median value if amounts differ\n // }\n}\n\n/**\n * Factory function for creating Bitcoin Data Provider\n * Useful for dependency injection and testing\n */\nexport function createBitcoinDataProvider(\n config: BitcoinDataProviderConfig\n): BitcoinDataProvider {\n return new BitcoinDataProvider(config);\n}\n", "// LIT Actions environment provides native fetch API - no imports needed\nimport {\n IPriceOracle,\n PriceSourceConfig,\n} from \"../interfaces/chunks/price-oracle.i\";\n\nconst PRICE_ORACLE_TOLERANCE = 0.01; // 1% max spread: (hi - lo) / lo\n\nexport class PriceOracleModule implements IPriceOracle {\n private sources: PriceSourceConfig[];\n\n /**\n * The locked production set. Every signed-price flow uses exactly these three\n * providers. The set was narrowed from five to three (dropping Binance and\n * Coinbase) after Binance returned HTTP 451 from the Lit TEE egress IP \u2014 the\n * two exchange APIs geofence/restrict in ways the global-egress data APIs do\n * not. Each provider here MUST be invoked with an API key (per-key rate\n * limiting + revokability + tenant attribution).\n *\n * Adding to this list re-opens the 2-of-3-consensus manipulation path flagged\n * in audit H-2 \u2014 do not extend without an explicit design review.\n */\n private static readonly ACTIVE_PROVIDER_NAMES = [\n \"cryptocompare\",\n \"coinmarketcap\",\n \"coingecko\",\n ] as const;\n\n /**\n * Number of DISTINCT providers required for a price signature. Strict 3-of-3\n * \u2014 not \"at least 3\"; not \"3 of N.\" Callers MUST pass exactly three entries\n * from {@link PriceOracleModule.ACTIVE_PROVIDER_NAMES}. Names are deduplicated\n * before the count is checked, so three CoinGecko entries still count as one.\n */\n private static readonly REQUIRED_PROVIDER_COUNT = 3;\n\n /**\n * Hardhat-only single-provider mode. When true the oracle requires exactly ONE\n * plaintext provider instead of the locked 3-of-3 encrypted set. Set ONLY by a\n * validator that has already verified `chain-policy.allowDevSinglePriceProvider`\n * (true only for hardhat). It NEVER relaxes consensus on sepolia/mainnet, and a\n * price signed under it is bound to the hardhat chainId domain (unusable elsewhere).\n */\n private readonly devSingleProvider: boolean;\n\n /** Distinct providers required for the active mode: 1 in hardhat dev, else 3. */\n private requiredCount(): number {\n return this.devSingleProvider ? 1 : PriceOracleModule.REQUIRED_PROVIDER_COUNT;\n }\n\n /**\n * @param priceProvidersOrConfig - REQUIRED in production flows. An array of\n * exactly 3 `{name, apiKey}` entries, one per locked provider. Every entry\n * needs an apiKey. Names are deduplicated so three entries with\n * `name: \"coingecko\"` collapse to a single provider \u2014 which then fails the\n * strict count check.\n * @param legacySources - Test-only back door. When supplied, the constructor\n * trusts the caller-supplied array verbatim and skips credential checks.\n * The strict count is still enforced (exactly 3).\n * @param _mode - Ignored. Retained for backward-compatible call sites.\n */\n constructor(\n priceProvidersOrConfig?:\n | Array<{ name: string; apiKey?: string; apiSecret?: string }>\n | any,\n legacySources?: PriceSourceConfig[],\n _mode?: \"dev\" | \"prod\",\n opts?: { devSingleProvider?: boolean },\n ) {\n this.devSingleProvider = opts?.devSingleProvider === true;\n if (legacySources && Array.isArray(legacySources)) {\n this.sources = legacySources;\n } else {\n if (!Array.isArray(priceProvidersOrConfig)) {\n throw new Error(\n \"Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. \" +\n `Pass exactly ${PriceOracleModule.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: ` +\n PriceOracleModule.ACTIVE_PROVIDER_NAMES.join(\", \"),\n );\n }\n this.sources = this.buildSources(priceProvidersOrConfig);\n }\n\n this.sources.sort((a, b) => a.priority - b.priority);\n this.validateProviderCount();\n }\n\n /**\n * Enforces strict 3-of-3. Any deviation re-opens the consensus-manipulation\n * path flagged as H-2 in the audit. There is no \"\u22653\" or \"3 of N\" mode.\n */\n private validateProviderCount(): void {\n if (this.sources.length !== this.requiredCount()) {\n throw new Error(\n `Price oracle requires exactly ${this.requiredCount()} provider(s). ` +\n `Currently configured: ${this.sources.length} provider(s). ` +\n (this.devSingleProvider\n ? \"(hardhat dev single-provider mode)\"\n : `Locked production set: ${PriceOracleModule.ACTIVE_PROVIDER_NAMES.join(\", \")}`),\n );\n }\n }\n\n /**\n * Build price sources from the caller-supplied config.\n *\n * Rules (all unconditional):\n * - Exactly 3 entries \u2014 reject fewer and reject more.\n * - Every entry must be a supported provider name from the locked set.\n * - Every entry must carry an `apiKey`.\n * - Duplicates by `name` are rejected outright.\n *\n * Throws as soon as any rule is violated.\n */\n private buildSources(\n priceProviders: Array<{\n name: string;\n apiKey?: string;\n apiSecret?: string;\n }>,\n ): PriceSourceConfig[] {\n if (priceProviders.length !== this.requiredCount()) {\n throw new Error(\n `priceProviders must contain exactly ${this.requiredCount()} entr${this.requiredCount() === 1 ? \"y\" : \"ies\"}. ` +\n `Received: ${priceProviders.length}. ` +\n (this.devSingleProvider\n ? \"(hardhat dev single-provider mode)\"\n : `Locked production set: ${PriceOracleModule.ACTIVE_PROVIDER_NAMES.join(\", \")}`),\n );\n }\n\n const sources: PriceSourceConfig[] = [];\n const seen = new Set<string>();\n let priority = 1;\n\n for (const provider of priceProviders) {\n if (!provider || typeof provider.name !== \"string\") {\n throw new Error(\"priceProviders entries must be {name, apiKey, apiSecret?} objects\");\n }\n const name = provider.name.toLowerCase();\n\n if (!PriceOracleModule.ACTIVE_PROVIDER_NAMES.includes(name as any)) {\n throw new Error(\n `Unsupported price provider \"${provider.name}\". ` +\n `Locked production set: ${PriceOracleModule.ACTIVE_PROVIDER_NAMES.join(\", \")}`,\n );\n }\n\n if (seen.has(name)) {\n throw new Error(\n `Duplicate price provider \"${name}\" \u2014 the oracle requires ${PriceOracleModule.REQUIRED_PROVIDER_COUNT} DISTINCT ` +\n `providers so a single upstream failure or manipulation cannot ` +\n `compromise consensus. Use ${PriceOracleModule.REQUIRED_PROVIDER_COUNT} different provider names from: ` +\n `${PriceOracleModule.ACTIVE_PROVIDER_NAMES.join(\", \")}`,\n );\n }\n seen.add(name);\n\n switch (name) {\n case \"cryptocompare\":\n if (!provider.apiKey) {\n throw new Error(\"CryptoCompare provider requires an apiKey\");\n }\n sources.push(\n this.createCryptoCompareSource(provider.apiKey, priority++),\n );\n break;\n case \"coinmarketcap\":\n if (!provider.apiKey) {\n throw new Error(\"CoinMarketCap provider requires an apiKey\");\n }\n sources.push(\n this.createCoinMarketCapSource(provider.apiKey, priority++),\n );\n break;\n case \"coingecko\":\n if (!provider.apiKey) {\n throw new Error(\n \"CoinGecko provider requires an apiKey (Demo or Pro). \" +\n \"Unauthenticated CoinGecko access is not accepted \u2014 the \" +\n \"free tier is rate-limited and edge-cached, which breaks \" +\n \"median consensus under load.\",\n );\n }\n sources.push(\n this.createCoinGeckoSource(provider.apiKey, priority++),\n );\n break;\n default:\n // Unreachable: validated against ACTIVE_PROVIDER_NAMES above.\n throw new Error(`Unhandled provider: ${name}`);\n }\n }\n\n return sources;\n }\n\n /**\n * Create CryptoCompare price source\n * Requires API key for access\n */\n private createCryptoCompareSource(\n apiKey: string,\n priority: number\n ): PriceSourceConfig {\n const fetchJson = async (url: string) => {\n const controller = new AbortController();\n const timeoutMs = 5000;\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(url, {\n signal: controller.signal,\n headers: {\n // LIT runtime rejects custom User-Agent headers (gRPC invalid_argument)\n Accept: \"application/json\",\n },\n });\n clearTimeout(timeoutId);\n if (!res.ok) {\n throw new Error(\n `CryptoCompare HTTP ${res.status} ${res.statusText}`,\n );\n }\n return await res.json();\n } catch (error: any) {\n clearTimeout(timeoutId);\n if (error.name === \"AbortError\") {\n throw new Error(`Request timeout after ${timeoutMs}ms`);\n }\n throw error;\n }\n };\n\n return {\n name: \"CryptoCompare\",\n fetchPrice: async () => {\n // Each node fetches the price\n const url = new URL(\"https://min-api.cryptocompare.com/data/price\");\n url.searchParams.set(\"fsym\", \"BTC\");\n url.searchParams.set(\"tsyms\", \"USDT\");\n url.searchParams.set(\"api_key\", apiKey);\n\n const data: any = await fetchJson(url.toString());\n // Response format: {\"USDT\":86800.42}\n // Treat USDT as USD (1:1 for price oracle purposes)\n const price = Number((data as any)?.USDT);\n if (!Number.isFinite(price) || price <= 0) {\n throw new Error(\"Invalid CryptoCompare price payload\");\n }\n\n // Chipotle: no broadcastAndCollect \u2014 each node uses its local fetch (deterministic if APIs agree).\n return price;\n },\n priority,\n };\n }\n\n /**\n * Create shared fetch helper with timeout\n * LIT runtime rejects custom User-Agent headers\n */\n private createFetchJson(providerName: string) {\n return async (url: string, headers?: Record<string, string>) => {\n const controller = new AbortController();\n const timeoutMs = 5000;\n const id = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(url, {\n headers: { Accept: \"application/json\", ...(headers || {}) },\n signal: controller.signal,\n });\n if (!res.ok) {\n throw new Error(\n `${providerName} HTTP ${res.status} ${res.statusText}`,\n );\n }\n return await res.json();\n } finally {\n clearTimeout(id);\n }\n };\n }\n\n /**\n * Create CoinGecko price source.\n *\n * CoinGecko's public endpoint has no authentication, but we intentionally\n * require the caller to supply either a Demo (`x-cg-demo-api-key`) or Pro\n * (`x-cg-pro-api-key`) key.\n */\n private createCoinGeckoSource(\n apiKey: string,\n priority: number,\n ): PriceSourceConfig {\n if (!apiKey) {\n throw new Error(\"createCoinGeckoSource requires an apiKey\");\n }\n const fetchJson = this.createFetchJson(\"CoinGecko\");\n\n return {\n name: \"CoinGecko\",\n fetchPrice: async () => {\n // Pro API keys use `x-cg-pro-api-key`; Demo keys use `x-cg-demo-api-key`.\n // Diamond Hands deployments issue Demo keys; if a Pro key is supplied\n // the caller should prefix it with \"pro:\" so we route it correctly.\n const isPro = apiKey.startsWith(\"pro:\");\n const key = isPro ? apiKey.slice(4) : apiKey;\n const headers: Record<string, string> = isPro\n ? { \"x-cg-pro-api-key\": key }\n : { \"x-cg-demo-api-key\": key };\n\n const url = new URL(\"https://api.coingecko.com/api/v3/simple/price\");\n url.searchParams.set(\"ids\", \"bitcoin\");\n url.searchParams.set(\"vs_currencies\", \"usd\");\n\n const data: any = await fetchJson(url.toString(), headers);\n const price = Number((data as any)?.bitcoin?.usd);\n if (!Number.isFinite(price) || price <= 0) {\n throw new Error(\"Invalid CoinGecko price payload\");\n }\n\n return price;\n },\n priority,\n };\n }\n\n private createCoinMarketCapSource(\n apiKey: string,\n priority: number\n ): PriceSourceConfig {\n const fetchJson = this.createFetchJson(\"CoinMarketCap\");\n\n return {\n name: \"CoinMarketCap\",\n fetchPrice: async () => {\n const url = new URL(\n \"https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest\"\n );\n url.searchParams.set(\"symbol\", \"BTC\");\n url.searchParams.set(\"convert\", \"USDT\");\n\n const data: any = await fetchJson(url.toString(), {\n \"X-CMC_PRO_API_KEY\": apiKey,\n });\n const quote =\n data?.data?.BTC?.[0]?.quote?.USDT?.price ??\n data?.data?.BTC?.quote?.USDT?.price;\n const price = Number(quote);\n if (!Number.isFinite(price) || price <= 0) {\n throw new Error(\"Invalid CoinMarketCap price payload\");\n }\n\n return price;\n },\n priority,\n };\n }\n\n /**\n * Get BTC price in USD with 8 decimals.\n *\n * Strict 3-of-3: queries all sources in parallel; if any one fails, the whole\n * call fails (no fallback). All three prices must lie within 1% of each other\n * (`(hi - lo) / lo <= 0.01`). Returns the median of the three.\n *\n * This is the only signed-price path in the codebase. The previously-exposed\n * `getBTCPriceConsensus()` (with outlier filtering + lenient survivor median)\n * was removed in the H-2 fix.\n */\n async getBTCPrice(): Promise<bigint> {\n const startTime = Date.now();\n\n if (this.sources.length !== this.requiredCount()) {\n throw new Error(\n `Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`\n );\n }\n\n const GLOBAL_TIMEOUT_MS = 8000;\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(\n new Error(`Price oracle global timeout after ${GLOBAL_TIMEOUT_MS}ms`)\n );\n }, GLOBAL_TIMEOUT_MS);\n });\n\n const fetchAll = Promise.all(\n this.sources.map(async (source) => {\n const t = Date.now();\n try {\n const priceUSD = await source.fetchPrice();\n console.log(\n `[Price Oracle] \u2705 [+${Date.now() - t}ms] ${source.name}: $${priceUSD.toLocaleString()}`,\n );\n return priceUSD;\n } catch (error) {\n const cause = error instanceof Error ? error.message : String(error);\n console.log(`[Price Oracle] \u274C ${source.name}: ${cause}`);\n throw new Error(`${source.name} price fetch failed: ${cause}`);\n }\n }),\n );\n\n const prices: number[] = await Promise.race([fetchAll, timeoutPromise]);\n\n // Sort ascending; median is middle value\n const sorted = [...prices].sort((a, b) => a - b);\n\n let median: number;\n if (this.devSingleProvider) {\n // Hardhat dev mode: exactly one provider, so there is no cross-provider\n // spread to check \u2014 use the single fetched price directly.\n median = sorted[0];\n } else {\n median = sorted[1];\n // Tolerance check: (hi - lo) / lo must be within 1%\n const spread = (sorted[2] - sorted[0]) / sorted[0];\n if (spread > PRICE_ORACLE_TOLERANCE) {\n const names = this.sources.map((s) => s.name).join(\", \");\n const formatted = sorted.map((p) => `$${p.toLocaleString()}`).join(\", \");\n throw new Error(\n `Price consensus failed: prices not within ${PRICE_ORACLE_TOLERANCE * 100}% tolerance. ` +\n `Providers: [${names}]. Prices: [${formatted}]`\n );\n }\n }\n\n // Convert median to 8-decimal bigint (deterministic: cents \u2192 BigInt)\n const priceCents = Math.round(median * 100);\n const priceWith8Decimals = BigInt(priceCents) * 1_000_000n;\n\n const totalElapsed = Date.now() - startTime;\n console.log(`[Price Oracle] Median price: $${median.toLocaleString()} \u2014 total time: ${totalElapsed}ms`);\n console.log(`[Price Oracle] Price with 8 decimals: ${priceWith8Decimals}`);\n\n return priceWith8Decimals;\n }\n}\n", "/**\n * Vault Balance Consensus \u2014 multi-provider cross-checks for the trusted balance\n *\n * Extracted from `vault-balance.module.ts` (review 2026-07-15) so the balance\n * module owns only the contract-state / authorized-spend / filter orchestration\n * while this class owns everything provider-facing:\n * - provider expansion (one data reader per registered provider),\n * - confirmed-UTXO-set consensus (each confirmed UTXO must match, by value,\n * on every provider; tip skew demotes, forgery / depth-lie throws),\n * - self-change proofing (unconfirmed change admitted only when every\n * provider agrees the parent tx spends confirmed vault-owned outputs and\n * corroborates the claimed output),\n * - the fan-out / concurrency / timeout policy those checks depend on.\n *\n * Bundling note: this file is imported ONLY by `vault-balance.module.ts` (hence\n * only by the six vault-balance consumer actions). It deliberately does NOT\n * touch `bitcoin-data-provider.module.ts`, whose other importers \u2014 including\n * `btc-transaction-signer`, pinned by an in-flight deploy ceremony \u2014 must not\n * rebundle. See docs/vault-balance-confirmed-gate-plan-2026-07-14.md \u00A73.1/\u00A73.2.\n */\n\nimport {\n SelfChangeProviderConfig,\n TransactionInput,\n UTXO,\n UTXOSet,\n} from \"../interfaces/chunks/vault-balance.i\";\nimport { IBitcoinDataProvider } from \"../interfaces/chunks/bitcoin-data-provider.i\";\nimport {\n BitcoinDataProvider,\n isBitcoinTipUnreadableError,\n} from \"./bitcoin-data-provider.module\";\nimport { authHeaders } from \"./bitcoin-provider-auth\";\nimport { isAbortError } from \"./lit-global-bootstrap\";\nimport { litDebugLog } from \"./lit-action-debug\";\n\n/**\n * Self-change classification budget: at most this many distinct unconfirmed\n * parent transactions are classified per balance calculation, largest claimed\n * value first (deterministic). Anyone can dust a vault address with 0-conf\n * deposits, so an unbounded fan-out would let mempool spam amplify into\n * provider rate-limit failures and \u2014 since consensus is fail-closed \u2014 an\n * action-wide outage. Protocol self-spends are rare and high-value, so they\n * always win the ordering; overflow parents are excluded (the safe direction\n * for third-party dust).\n */\nconst MAX_CLASSIFIED_PARENTS = 5;\n\n/** Parent transactions evaluated concurrently (each fans out to all providers). */\nconst CLASSIFICATION_CONCURRENCY = 2;\n\n/**\n * Max acceptable spread (in blocks) between the highest and lowest confirmation\n * count any registered provider reports for the SAME confirmed UTXO. Honest\n * providers track the chain tip within a block or two, so a spread inside this\n * tolerance is treated as benign tip skew (the UTXO is gated on the minimum\n * count \u2014 it simply waits a block if that dips below threshold). A spread\n * beyond it means providers materially disagree on the UTXO's depth \u2014 a\n * compromised provider trying to inflate a shallow UTXO past the gate, or to\n * deflate a deep one to force a wrongful liquidation \u2014 and is refused\n * (fail-closed) rather than silently demoted.\n */\nconst CONFIRMATION_SKEW_TOLERANCE = 3;\n\n/** Parsed output of a parent transaction (Esplora `/tx/:txid` vout row). */\ninterface ParentTxOutput {\n index: number;\n scriptpubkey_address?: string;\n value?: bigint;\n}\n\n/** Parent transaction data needed for the self-change proof. */\ninterface ParentTransactionData {\n inputs: TransactionInput[];\n outputs: ParentTxOutput[];\n}\n\n/**\n * Run `fn` over `items` with at most `limit` in flight, preserving order.\n * First rejection propagates (fail-closed) once in-flight work settles.\n */\nasync function mapWithConcurrency<T, R>(\n items: T[],\n limit: number,\n fn: (item: T) => Promise<R>\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n const workers = Array.from(\n { length: Math.min(limit, items.length) },\n async () => {\n while (true) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n results[i] = await fn(items[i]!);\n }\n }\n );\n await Promise.all(workers);\n return results;\n}\n\n/**\n * Verify the primary provider's claimed UTXOs against a provider's view of\n * the parent transaction's outputs. Returns a mismatch description, or null\n * when every claim matches (exists at the claimed index, pays the vault,\n * exact claimed value).\n */\nfunction findOutputClaimMismatch(\n claimedUtxos: UTXO[],\n outputs: ParentTxOutput[],\n cleanVaultAddress: string\n): string | null {\n for (const claim of claimedUtxos) {\n const output = outputs.find((o) => o.index === claim.vout);\n if (!output) {\n return `claimed output ${claim.txid}:${claim.vout} not present in parent tx`;\n }\n if (output.scriptpubkey_address !== cleanVaultAddress) {\n return `claimed output ${claim.txid}:${claim.vout} pays ${output.scriptpubkey_address ?? \"<no address>\"}, not the vault`;\n }\n if (output.value === undefined || output.value !== claim.satoshis) {\n return `claimed output ${claim.txid}:${claim.vout} value ${output.value?.toString() ?? \"<missing>\"} != reported ${claim.satoshis.toString()}`;\n }\n }\n return null;\n}\n\n/**\n * Strip network prefix from a Bitcoin address.\n *\n * Parity with BitcoinDataProvider's private `stripNetworkPrefix` \u2014 duplicated\n * (2 lines) rather than exported from the provider module, so this change does\n * not rebundle the provider's other importers.\n */\nfunction stripNetworkPrefix(address: string): string {\n const prefixPattern = /^(REGTEST_|TESTNET_|MAINNET_)/;\n return address.replace(prefixPattern, \"\");\n}\n\n/**\n * Multi-provider consensus over a vault's UTXO set.\n *\n * Constructed per balance calculation from the primary data provider (the one\n * the primary UTXO set came from \u2014 index 0, reused verbatim to preserve test\n * doubles) plus the full registered provider list. All secondary readers are\n * built once, up front, and shared by both consensus passes.\n */\nexport class VaultBalanceConsensus {\n private readonly readers: IBitcoinDataProvider[] | null;\n\n /**\n * @param minConsensusProviders Policy floor (`policy.minConsensusProviders`,\n * remediation P1/#1). Both consensus passes THROW when fewer providers are\n * configured than the floor demands \u2014 below it the cross-checks cannot run\n * and neither trusting the primary (inflation) nor excluding UTXOs\n * (deflation \u2192 wrongful liquidation) is a safe direction. A floor of 1\n * (hardhat / single-provider sepolia) preserves the trust-primary /\n * exclude-unconfirmed baseline unchanged.\n */\n constructor(\n private readonly primaryProvider: IBitcoinDataProvider,\n private readonly providerConfigs: SelfChangeProviderConfig[] | undefined,\n private readonly minConsensusProviders: number\n ) {\n // A provider with no endpoint cannot vote. Counting it as \"not self-change\"\n // would exclude real collateral (deflation \u2192 wrongful liquidation), so a\n // config without a URL is refused up front rather than at read time.\n (providerConfigs ?? []).forEach((cfg, i) => {\n if (!cfg.providerUrl) {\n throw new Error(\n `VaultBalanceConsensus: provider config ${i} (\"${cfg.name}\") has no providerUrl; refusing to count it as a vote`\n );\n }\n });\n this.readers = this.buildReaders();\n }\n\n /**\n * Fail-closed floor check shared by both consensus passes. Only floors above\n * 1 can bite: a floor of 1 with zero configs means \"no esplora access\n * configured\" (dev/test), where the documented pre-gate behaviour \u2014\n * trust-primary confirmed set, exclude unconfirmed \u2014 remains correct.\n */\n private assertProviderFloor(pass: string): void {\n const configured = this.providerConfigs?.length ?? 0;\n if (this.minConsensusProviders > 1 && configured < this.minConsensusProviders) {\n throw new Error(\n `${pass}: this chain requires at least ${this.minConsensusProviders} Bitcoin providers ` +\n `for consensus; ${configured} configured. Refusing to proceed without cross-check.`\n );\n }\n }\n\n /**\n * Build one data reader per configured provider (primary first). Index 0\n * reuses the injected primary instance; the rest are constructed from their\n * configs so cross-check reads hit the right endpoint. Null when no providers\n * are configured \u2014 both passes then fall back to primary-only behaviour.\n */\n private buildReaders(): IBitcoinDataProvider[] | null {\n const configs = this.providerConfigs;\n if (!configs || configs.length === 0) {\n return null;\n }\n return configs.map((cfg, i) =>\n i === 0\n ? this.primaryProvider\n : new BitcoinDataProvider({\n providerUrl: cfg.providerUrl,\n auth: cfg.auth,\n ...(cfg.timeout ? { timeout: cfg.timeout } : {}),\n })\n );\n }\n\n /**\n * Confirmed-UTXO-set consensus across every registered provider (strict).\n *\n * The signed balance is dominated by the primary's confirmed UTXOs, but the\n * UTXO set \u2014 txid, vout, and value \u2014 is read only from the primary; the\n * `assertBitcoinBalanceConsensus` check the validators run compares\n * `chain_stats` totals, not individual outpoints. So a compromised primary\n * can add a fabricated confirmed UTXO, or inflate a real one's value, and the\n * balance consensus still passes (it serves honest `chain_stats`). This\n * closes that: each UTXO the primary reports at or above `minConfirmations`\n * must be present with the EXACT same value on every registered provider.\n *\n * Semantics:\n * - Absent on any provider, or value mismatch \u2192 THROW (fail-closed). Confirmed\n * transactions are fully propagated, so absence is unambiguous forgery, not\n * a race.\n * - Present + value-matched everywhere: the UTXO counts as confirmed only if\n * it meets `minConfirmations` on ALL providers (gated on the minimum\n * reported depth). A UTXO just past the boundary on the primary but a block\n * behind on a lagging provider is DEMOTED \u2014 excluded until it matures \u2014\n * rather than signed over. A depth spread beyond CONFIRMATION_SKEW_TOLERANCE\n * is not benign skew but a provider lying about depth (to inflate a shallow\n * UTXO past the gate, or deflate a deep one into a wrongful liquidation) \u2192\n * THROW.\n * - SYMMETRIC (finding #6): a confirmed outpoint any secondary reports that\n * the primary omits entirely, reports with a different value, or reports\n * at a depth more than the skew tolerance BELOW the secondary's \u2192 THROW.\n * Without this, a compromised primary deflates the balance by omission and\n * forces a wrongful liquidation.\n *\n * Below `minConsensusProviders` this THROWS (P1/#1). With a floor of 1 and\n * 0/1 providers configured, no cross-check is possible and the primary's\n * confirmed UTXOs are returned unchanged (behaviour identical to before\n * this gate).\n *\n * Cross-checking `chain_stats` totals against the confirmed-UTXO sum was\n * considered and rejected: `getBalance` reads mempool-blind `chain_stats`\n * while `getUTXOSet` removes mempool-spent outputs, so the two legitimately\n * diverge during any pending spend \u2014 precisely the self-change window \u2014 and\n * that comparison would false-fail there. Outpoint-set consensus asserts\n * agreement only on confirmed outpoints, which the mempool does not touch.\n *\n * @returns Set of \"txid:vout\" keys admitted as confirmed-with-consensus.\n */\n async confirmedUtxoConsensus(\n primaryUtxos: UTXO[],\n vaultAddress: string,\n minConfirmations: number\n ): Promise<Set<string>> {\n const providerConfigs = this.providerConfigs;\n const readers = this.readers;\n\n // P1/#1: below the policy floor, refusing to sign is the only safe move \u2014\n // trusting the primary's confirmed set unverified is the exact single-\n // provider inflation vector this pass exists to close.\n this.assertProviderFloor(\"confirmedUtxoConsensus\");\n\n const confirmedKeys = new Set<string>();\n const primaryConfirmed = primaryUtxos.filter(\n (utxo) => utxo.confirmations >= minConfirmations\n );\n for (const utxo of primaryConfirmed) {\n confirmedKeys.add(`${utxo.txid}:${utxo.vout}`);\n }\n\n // 0 or 1 provider (only reachable with a floor of 1 \u2014 hardhat / single-\n // provider sepolia): no cross-check possible; trust the primary (unchanged).\n // NOTE: an empty primaryConfirmed set does NOT short-circuit the multi-\n // provider path \u2014 a primary omitting EVERY confirmed UTXO is the most\n // extreme deflation (finding #6), and only the symmetric pass below can\n // catch it.\n if (!providerConfigs || providerConfigs.length <= 1 || !readers) {\n return confirmedKeys;\n }\n\n const providerName = (i: number) =>\n providerConfigs[i]!.name || providerConfigs[i]!.providerUrl;\n\n // Fetch every SECONDARY provider's UTXO set concurrently (the primary's is\n // already in hand). Fail-closed: any request failure throws and names it.\n //\n // NOTE: getUTXOSet's second argument does NOT filter the returned `utxos`\n // array \u2014 it only shapes the summary balance fields. Each secondary's map\n // below therefore contains the provider's FULL UTXO set (0-conf included),\n // so a boundary UTXO on a provider one block behind the primary is still\n // PRESENT here with its lower count and takes the demote path \u2014 absence\n // from the map means the provider doesn't know the outpoint at all, even\n // in its mempool, which for a \u2265minConfirmations claim is forgery or a\n // materially desynced provider, not tip skew.\n const settled = await Promise.allSettled(\n readers\n .slice(1)\n .map((reader) => reader.getUTXOSet(vaultAddress, minConfirmations))\n );\n const failures = settled\n .map((r, i) => ({ r, name: providerName(i + 1) }))\n .filter(\n (x): x is { r: PromiseRejectedResult; name: string } =>\n x.r.status === \"rejected\"\n )\n .map(\n ({ r, name }) => `${name} \u2192 ${r.reason?.message ?? String(r.reason)}`\n );\n if (failures.length > 0) {\n throw new Error(\n `Confirmed UTXO set read failed for ${vaultAddress} on ${failures.length}/${providerConfigs.length - 1} secondary provider(s): ${failures.join(\"; \")}`\n );\n }\n\n // Index secondary sets by outpoint for O(1) lookup.\n const secondaryMaps = settled.map((r) => {\n const map = new Map<string, { value: bigint; confirmations: number }>();\n for (const utxo of (r as PromiseFulfilledResult<UTXOSet>).value.utxos) {\n map.set(`${utxo.txid}:${utxo.vout}`, {\n value: utxo.satoshis,\n confirmations: utxo.confirmations,\n });\n }\n return map;\n });\n\n const demoted: string[] = [];\n for (const utxo of primaryConfirmed) {\n const key = `${utxo.txid}:${utxo.vout}`;\n let minConfs = utxo.confirmations;\n let maxConfs = utxo.confirmations;\n for (let s = 0; s < secondaryMaps.length; s++) {\n const entry = secondaryMaps[s]!.get(key);\n const name = providerName(s + 1);\n if (!entry) {\n throw new Error(\n `Confirmed UTXO ${key} present on ${providerName(0)} but absent on ${name}; refusing to sign (possible fabricated UTXO).`\n );\n }\n if (entry.value !== utxo.satoshis) {\n throw new Error(\n `Confirmed UTXO ${key} value mismatch: ${providerName(0)}=${utxo.satoshis.toString()} vs ${name}=${entry.value.toString()}; refusing to sign.`\n );\n }\n if (entry.confirmations < minConfs) minConfs = entry.confirmations;\n if (entry.confirmations > maxConfs) maxConfs = entry.confirmations;\n }\n\n if (maxConfs - minConfs > CONFIRMATION_SKEW_TOLERANCE) {\n throw new Error(\n `Confirmed UTXO ${key} confirmation spread ${maxConfs - minConfs} exceeds tolerance ${CONFIRMATION_SKEW_TOLERANCE} (min ${minConfs}, max ${maxConfs}); providers disagree on depth, refusing to sign.`\n );\n }\n if (minConfs < minConfirmations) {\n // Benign tip skew at the boundary: present + value-matched everywhere\n // but a provider is a block behind. Demote (exclude) until it matures.\n confirmedKeys.delete(key);\n demoted.push(key);\n }\n }\n if (demoted.length > 0) {\n litDebugLog(\n `[VaultBalance] confirmed-consensus: ${demoted.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${demoted.join(\", \")}`\n );\n }\n\n // Symmetric direction (finding #6): a confirmed outpoint a SECONDARY\n // reports that the primary omits \u2014 or reports at a wildly lower depth /\n // different value \u2014 is a deflation attempt (suppress collateral \u2192 wrongful\n // liquidation) or a materially desynced provider. The primary-direction\n // loop above cannot see it because it iterates only the primary's set.\n // Compared against the primary's FULL UTXO set (mempool included), so a\n // boundary UTXO the primary merely has at a lower depth takes the skew /\n // demote semantics, not this absence throw. NOTE: this can throw\n // transiently when the primary has already seen a just-broadcast vault\n // spend in its mempool (outpoint removed) and a secondary has not \u2014 that\n // is fail-closed in the safe direction and resolves on retry.\n const primaryByKey = new Map(\n primaryUtxos.map((utxo) => [`${utxo.txid}:${utxo.vout}`, utxo])\n );\n for (let s = 0; s < secondaryMaps.length; s++) {\n const name = providerName(s + 1);\n for (const [key, entry] of secondaryMaps[s]!) {\n if (entry.confirmations < minConfirmations) continue;\n const primaryUtxo = primaryByKey.get(key);\n if (!primaryUtxo) {\n throw new Error(\n `Confirmed UTXO ${key} present on ${name} (${entry.confirmations} confs) but absent on ` +\n `${providerName(0)}; refusing to sign (possible omitted UTXO / balance deflation \u2014 ` +\n `may be transient during an in-flight vault spend).`\n );\n }\n if (primaryUtxo.satoshis !== entry.value) {\n throw new Error(\n `Confirmed UTXO ${key} value mismatch: ${providerName(0)}=${primaryUtxo.satoshis.toString()} ` +\n `vs ${name}=${entry.value.toString()}; refusing to sign.`\n );\n }\n if (entry.confirmations - primaryUtxo.confirmations > CONFIRMATION_SKEW_TOLERANCE) {\n throw new Error(\n `Confirmed UTXO ${key} depth disagreement: ${providerName(0)}=${primaryUtxo.confirmations} ` +\n `vs ${name}=${entry.confirmations} exceeds tolerance ${CONFIRMATION_SKEW_TOLERANCE}; ` +\n `the primary may be under-reporting depth to suppress collateral, refusing to sign.`\n );\n }\n }\n }\n return confirmedKeys;\n }\n\n /**\n * Classify unconfirmed UTXOs as protocol self-change.\n *\n * A UTXO below minConfirmations counts as confirmed-equivalent ONLY when the\n * transaction that created it spends exclusively vault-owned, confirmed\n * outputs. Such a transaction can only have been signed by the vault's PKP,\n * so no third party can RBF-replace or double-spend it \u2014 the reversal risk\n * the confirmation gate exists to close does not apply. Any non-vault input,\n * unconfirmed funding tx, or coinbase input disqualifies the UTXO\n * (fail-safe: exclusion, never inclusion).\n *\n * Multi-provider consensus (audit C-1/C-2 parity): the parent-tx proof is\n * verified independently against EVERY configured provider and admitted\n * only on unanimity. The confirmed-balance consensus the validators run\n * covers `chain_stats` only, so without this the primary provider alone\n * could fabricate an unconfirmed UTXO plus a self-consistent parent proof\n * and inflate the signed balance. Any verdict disagreement THROWS\n * (fail-closed) \u2014 exclusion on a suppressed proof would deflate the balance\n * and open a wrongful-liquidation window, so neither direction may proceed\n * without agreement. A provider that cannot state the chain tip \u2014 and only\n * that failure \u2014 is dropped from the quorum rather than aborting the read (it\n * never counts as agreeing), and falling below `minConsensusProviders`\n * survivors throws \u2014 see `verifyParentIsSelfSpendConsensus`.\n *\n * The same per-provider `/tx` fetch also returns the parent's outputs, and\n * every provider must corroborate each claimed UTXO (index, vault address,\n * exact value) before admission \u2014 the UTXO list itself comes only from the\n * primary, so an unchecked claim would let it attach a fabricated or\n * inflated output to a genuine self-spend.\n *\n * Fetch cost: zero when every UTXO is confirmed (the common case); otherwise\n * per provider: one tx lookup per classified parent (vins + vouts in one\n * response), plus per distinct funding tx a confirmation check and \u2014 only\n * when the provider omits vin prevout data \u2014 an output lookup. Classified\n * parents are capped at MAX_CLASSIFIED_PARENTS (largest claimed value\n * first, deterministic) and evaluated CLASSIFICATION_CONCURRENCY at a time,\n * so third-party dust spam cannot amplify into provider rate-limiting and\n * an action-wide outage.\n *\n * See docs/vault-balance-confirmed-gate-plan-2026-07-14.md \u00A73.1.\n *\n * @param utxos - Full UTXO set for the vault address\n * @param vaultAddress - Bitcoin address of the vault (may carry network prefix)\n * @param minConfirmations - Confirmation threshold for the chain\n * @returns Set of \"txid:vout\" keys for UTXOs verified as self-change\n */\n async classifySelfChange(\n utxos: UTXO[],\n vaultAddress: string,\n minConfirmations: number\n ): Promise<Set<string>> {\n const providerConfigs = this.providerConfigs;\n const readers = this.readers;\n\n const selfChange = new Set<string>();\n const unconfirmed = utxos.filter(\n (utxo) => utxo.confirmations < minConfirmations\n );\n if (unconfirmed.length === 0) {\n return selfChange;\n }\n\n // P1/#1: below the policy floor a self-change proof cannot be unanimously\n // verified, and silently excluding (deflating) opens the wrongful-\n // liquidation window this module's own docs warn about. Fail closed.\n this.assertProviderFloor(\"classifySelfChange\");\n\n if (!providerConfigs || providerConfigs.length === 0 || !readers) {\n // No Esplora access configured \u2014 unconfirmed UTXOs cannot be verified\n // as self-change and stay excluded (fail-safe).\n litDebugLog(\n `[VaultBalance] ${unconfirmed.length} unconfirmed UTXO(s) excluded: no bitcoinProviderConfigs for self-change classification`\n );\n return selfChange;\n }\n\n const cleanVaultAddress = stripNetworkPrefix(vaultAddress);\n\n // Group claims per parent tx, then rank parents by total claimed value\n // (desc, txid asc tiebreak). The ordering is a pure function of the UTXO\n // set, so every LIT node classifies the same parents and consensus\n // reconciliation is unaffected.\n const claimsByParent = new Map<string, UTXO[]>();\n for (const utxo of unconfirmed) {\n const claims = claimsByParent.get(utxo.txid) ?? [];\n claims.push(utxo);\n claimsByParent.set(utxo.txid, claims);\n }\n const claimedSum = (txid: string) =>\n claimsByParent\n .get(txid)!\n .reduce((sum, utxo) => sum + utxo.satoshis, 0n);\n const rankedParents = [...claimsByParent.keys()].sort((a, b) => {\n const diff = claimedSum(b) - claimedSum(a);\n if (diff !== 0n) {\n return diff > 0n ? 1 : -1;\n }\n return a < b ? -1 : a > b ? 1 : 0;\n });\n const parentTxids = rankedParents.slice(0, MAX_CLASSIFIED_PARENTS);\n const skippedParents = rankedParents.length - parentTxids.length;\n if (skippedParents > 0) {\n litDebugLog(\n `[VaultBalance] self-change: ${skippedParents} parent tx(s) beyond the ${MAX_CLASSIFIED_PARENTS}-parent classification budget excluded (mempool-spam bound; largest claimed value classified first)`\n );\n }\n\n const verdicts = await mapWithConcurrency(\n parentTxids,\n CLASSIFICATION_CONCURRENCY,\n async (parentTxid) => ({\n parentTxid,\n verified: await this.verifyParentIsSelfSpendConsensus(\n parentTxid,\n claimsByParent.get(parentTxid)!,\n cleanVaultAddress,\n minConfirmations,\n providerConfigs,\n readers\n ),\n })\n );\n\n const verifiedParents = new Set(\n verdicts.filter((v) => v.verified).map((v) => v.parentTxid)\n );\n for (const utxo of unconfirmed) {\n if (verifiedParents.has(utxo.txid)) {\n selfChange.add(`${utxo.txid}:${utxo.vout}`);\n }\n }\n if (verifiedParents.size > 0) {\n litDebugLog(\n `[VaultBalance] self-change: ${selfChange.size}/${unconfirmed.length} unconfirmed UTXO(s) verified as protocol change by ${providerConfigs.length} provider(s)`\n );\n }\n return selfChange;\n }\n\n /**\n * Run the self-spend proof against every configured provider and require\n * unanimity AMONG THE PROVIDERS THAT ANSWERED. Fail-closed on disagreement:\n * a verdict mismatch throws and aborts the balance calculation \u2014 see\n * classifySelfChange for why exclusion is not a safe fallback here.\n *\n * Quorum semantics (2026-09-23, plan C2). ONE failure class is tolerated: a\n * provider that could not state the chain tip (`BitcoinTipUnreadableError`).\n * It is ABSENT from the quorum \u2014 never counted as agreeing, never allowed to\n * decide the verdict \u2014 and the policy floor, not \"at least one\", decides when\n * that absence is fatal: below `minConsensusProviders` surviving readings\n * there is no cross-check left to trust, and the read fails loudly naming\n * every provider that dropped out.\n *\n * Why only that class. `getTransaction` now throws on an unreadable tip\n * instead of fabricating `confirmations: 1`; without this carve-out one flaky\n * `/blocks/tip/height` endpoint would take every balance and spend path down\n * with it. Every OTHER failure remains fatal, as before: a provider that\n * answers \"I have never seen that transaction\" is making a claim about the\n * chain rather than suffering an outage, and that shape is precisely the\n * fabricated-UTXO signature the fail-closed rule exists to catch.\n *\n * When the parent IS a unanimous self-spend, every provider's view of the\n * parent's OUTPUTS must additionally corroborate the primary's claimed\n * UTXOs (index exists, pays the vault, exact value). Without this, a\n * compromised primary could attach a fabricated or value-inflated output\n * to a genuine self-spend the honest providers happily verify.\n *\n * @returns True when every provider verified the parent and corroborated\n * the claimed outputs, false when every provider rejected the\n * parent (genuine third-party deposit)\n */\n private async verifyParentIsSelfSpendConsensus(\n parentTxid: string,\n claimedUtxos: UTXO[],\n cleanVaultAddress: string,\n minConfirmations: number,\n providerConfigs: SelfChangeProviderConfig[],\n readers: IBitcoinDataProvider[]\n ): Promise<boolean> {\n const providerName = (i: number) =>\n providerConfigs[i]!.name || providerConfigs[i]!.providerUrl;\n\n const settled = await Promise.allSettled(\n providerConfigs.map((cfg, i) =>\n this.evaluateParentForProvider(\n parentTxid,\n claimedUtxos,\n cleanVaultAddress,\n minConfirmations,\n readers[i]!,\n cfg\n )\n )\n );\n\n // Partition into the quorum (providers that answered), the providers that\n // could not state the chain tip (ABSENT), and everything else (fatal). The\n // provider INDEX travels with each entry so every message below still names\n // the real provider once the list is no longer dense.\n const answered: Array<{\n index: number;\n evaluation: { selfSpend: boolean; outputMismatch: string | null };\n }> = [];\n const absences: string[] = [];\n const failures: string[] = [];\n settled.forEach((result, i) => {\n if (result.status === \"fulfilled\") {\n answered.push({ index: i, evaluation: result.value });\n return;\n }\n const described = `${providerName(i)} \u2192 ${result.reason?.message ?? String(result.reason)}`;\n if (isBitcoinTipUnreadableError(result.reason)) {\n absences.push(described);\n return;\n }\n failures.push(described);\n });\n\n // Anything OTHER than an unreadable tip stays fatal, exactly as before.\n // A provider that answers \"I have never seen that transaction\" is making a\n // claim about the chain, not suffering an outage, and that shape IS the\n // fabricated-UTXO signature (review 2026-07-15 P1): dropping it from the\n // quorum would let a compromised primary invent an unconfirmed UTXO and\n // have the honest provider's 404 quietly ignored.\n if (failures.length > 0) {\n throw new Error(\n `Self-change classification failed for tx ${parentTxid} on ${failures.length}/${providerConfigs.length} provider(s): ${failures.join(\"; \")}`\n );\n }\n\n // The floor is the policy's (1 on hardhat/sepolia, 2 on ethereum), never\n // below 1 \u2014 a verdict resting on zero readings would be no verdict at all.\n const floor = Math.max(1, this.minConsensusProviders);\n if (answered.length < floor) {\n throw new Error(\n `Self-change classification for tx ${parentTxid}: only ${answered.length}/${providerConfigs.length} ` +\n `provider(s) could state a confirmation depth, below this chain's floor of ${floor}. ` +\n `Unreadable tips: ${absences.join(\"; \")}`\n );\n }\n if (absences.length > 0) {\n // Loud in the action log, not silent: the read proceeded on a REDUCED\n // quorum, which an operator must be able to see after the fact.\n litDebugLog(\n `[VaultBalance] self-change: tx ${parentTxid} classified on a reduced quorum \u2014 ` +\n `${answered.length}/${providerConfigs.length} provider(s) answered (floor ${floor}); ` +\n `dropped for an unreadable chain tip: ${absences.join(\"; \")}`\n );\n }\n\n const first = answered[0]!;\n const disagreements = answered\n .slice(1)\n .filter((a) => a.evaluation.selfSpend !== first.evaluation.selfSpend)\n .map(\n (a) =>\n `${providerName(first.index)}=${first.evaluation.selfSpend} vs ` +\n `${providerName(a.index)}=${a.evaluation.selfSpend}`\n );\n if (disagreements.length > 0) {\n throw new Error(\n `Self-change consensus mismatch for tx ${parentTxid}: ${disagreements.join(\"; \")}. ` +\n `A provider may be compromised or out of sync; refusing to sign.`\n );\n }\n\n if (!first.evaluation.selfSpend) {\n return false;\n }\n\n const outputMismatches = answered\n .map((a) =>\n a.evaluation.outputMismatch\n ? `${providerName(a.index)} \u2192 ${a.evaluation.outputMismatch}`\n : null\n )\n .filter((m): m is string => m !== null);\n if (outputMismatches.length > 0) {\n throw new Error(\n `Self-change output claim mismatch for tx ${parentTxid}: ${outputMismatches.join(\"; \")}. ` +\n `The reported UTXO set contradicts the parent transaction; refusing to sign.`\n );\n }\n\n return true;\n }\n\n /**\n * Single provider's evaluation of a parent tx: the self-spend proof plus \u2014\n * when the proof holds \u2014 corroboration of the claimed outputs against this\n * provider's view of the parent's vout set. The output check is skipped for\n * non-self-spend parents (their UTXOs are excluded regardless, and a\n * third-party deposit's values are not ours to police).\n */\n private async evaluateParentForProvider(\n parentTxid: string,\n claimedUtxos: UTXO[],\n cleanVaultAddress: string,\n minConfirmations: number,\n reader: IBitcoinDataProvider,\n providerConfig: SelfChangeProviderConfig\n ): Promise<{ selfSpend: boolean; outputMismatch: string | null }> {\n const parentTx = await this.fetchParentTransaction(\n parentTxid,\n providerConfig\n );\n // null == provably coinbase-funded (legitimate \"not self-change\" vote).\n // Provider inability throws inside fetchParentTransaction and surfaces as\n // a named provider failure in the consensus caller (fail-closed).\n if (!parentTx || parentTx.inputs.length === 0) {\n return { selfSpend: false, outputMismatch: null };\n }\n const selfSpend = await this.verifyInputsAreSelfSpend(\n parentTx.inputs,\n cleanVaultAddress,\n minConfirmations,\n reader\n );\n const outputMismatch = selfSpend\n ? findOutputClaimMismatch(claimedUtxos, parentTx.outputs, cleanVaultAddress)\n : null;\n return { selfSpend, outputMismatch };\n }\n\n /**\n * Verify that a transaction's inputs spend exclusively vault-owned,\n * confirmed outputs, using a single provider's view of the chain.\n *\n * @param inputs - Parsed inputs of the parent transaction\n * @param cleanVaultAddress - Vault address with network prefix stripped\n * @param minConfirmations - Required depth for every funding transaction\n * @param reader - Data provider for funding-tx lookups (same provider the inputs came from)\n * @returns True only when every input is a confirmed, vault-owned outpoint\n */\n private async verifyInputsAreSelfSpend(\n inputs: TransactionInput[],\n cleanVaultAddress: string,\n minConfirmations: number,\n reader: IBitcoinDataProvider\n ): Promise<boolean> {\n // Every input must spend an output owned by the vault address. Use the\n // provider's vin prevout when present; otherwise resolve ownership from\n // the funding transaction's outputs (regtest faucet omits prevout).\n const fundingTxids = [...new Set(inputs.map((input) => input.txid))];\n const outputsByFundingTx = new Map<\n string,\n Awaited<ReturnType<IBitcoinDataProvider[\"getTransactionOutputs\"]>>\n >();\n const needsOutputLookup = fundingTxids.filter((fundingTxid) =>\n inputs.some(\n (input) =>\n input.txid === fundingTxid && input.prevoutAddress === undefined\n )\n );\n await Promise.all(\n needsOutputLookup.map(async (fundingTxid) => {\n outputsByFundingTx.set(\n fundingTxid,\n await reader.getTransactionOutputs(fundingTxid)\n );\n })\n );\n\n for (const input of inputs) {\n let ownerAddress: string | undefined = input.prevoutAddress;\n if (ownerAddress === undefined) {\n const outputs = outputsByFundingTx.get(input.txid);\n ownerAddress = outputs?.find(\n (output) => output.index === input.vout\n )?.scriptpubkey_address;\n }\n if (ownerAddress !== cleanVaultAddress) {\n return false;\n }\n }\n\n // Defense in depth: every funding transaction must itself be confirmed to\n // the chain threshold. Protocol coin selection only spends confirmed\n // UTXOs, so this always holds for protocol-created transactions; it\n // protects against a legacy/buggy action version having signed a\n // chained-unconfirmed spend. No recursion \u2014 an unconfirmed ancestor\n // disqualifies.\n const fundingStatuses = await Promise.all(\n fundingTxids.map((fundingTxid) => reader.getTransaction(fundingTxid))\n );\n for (const status of fundingStatuses) {\n if (!status || status.confirmations < minConfirmations) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Fetch a parent transaction's inputs (vins) and outputs (vouts) via Esplora.\n *\n * A module-private fetch (not a `BitcoinDataProvider` method) so editing this\n * consensus logic does not rebundle the shared provider module's other\n * importers \u2014 see this file's header for the ripple-set constraint.\n *\n * @param txid - Transaction ID\n * @param providerConfig - Esplora endpoint to query (one of the configured\n * consensus providers)\n * @returns Parsed inputs + outputs, or null ONLY when the tx is provably not\n * a self-spend candidate (coinbase-funded). Provider inability \u2014\n * 404, malformed vin rows, missing vin array \u2014 THROWS (review\n * 2026-07-15 P1): the parent of a UTXO the primary lists must\n * exist, so \"can't fetch it\" is a provider failure, and treating it\n * as a false self-change vote would silently deflate collateral\n * (wrongful-liquidation direction) if every provider failed the\n * same way.\n */\n private async fetchParentTransaction(\n txid: string,\n providerConfig: SelfChangeProviderConfig\n ): Promise<ParentTransactionData | null> {\n // Every providerUrl is non-empty (checked in the constructor).\n // Same latency budget as BitcoinDataProvider (15s of the 30s action limit)\n const timeout = providerConfig.timeout || 15000;\n\n const controller = new AbortController();\n // The timer stays armed through body parsing \u2014 a stalled response body\n // must count against the same budget as the headers, otherwise a\n // misbehaving provider can hang classification past the configured\n // timeout. Cleared in `finally`.\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(`${providerConfig.providerUrl}/tx/${txid}`, {\n signal: controller.signal,\n headers: await authHeaders(providerConfig.auth, timeout),\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n // The parent of a UTXO the primary lists must exist somewhere \u2014 a\n // 404 means THIS provider cannot serve the proof. Fail closed\n // rather than vote \"not self-change\" (review 2026-07-15 P1).\n throw new Error(\n `parent tx ${txid} not found on this provider \u2014 cannot verify the self-change proof`\n );\n }\n throw new Error(\n `Bitcoin provider error: ${response.status} ${response.statusText}`\n );\n }\n\n const data = (await response.json()) as {\n vin?: Array<{\n txid?: string;\n vout?: number;\n is_coinbase?: boolean;\n prevout?: {\n scriptpubkey_address?: string;\n };\n }>;\n vout?: Array<{\n scriptpubkey_address?: string;\n value?: number;\n }>;\n };\n\n if (!data.vin || !Array.isArray(data.vin) || data.vin.length === 0) {\n // Every real Bitcoin transaction has at least one input \u2014 a missing\n // vin array is a malformed provider response, not a tx property.\n throw new Error(\n `provider returned tx ${txid} without a vin array \u2014 malformed response`\n );\n }\n\n const inputs: TransactionInput[] = [];\n for (const vin of data.vin) {\n if (vin.is_coinbase) {\n // Coinbase-funded: provably NOT a vault self-spend \u2014 a legitimate\n // \"false\" vote, not a provider failure.\n return null;\n }\n if (vin.txid === undefined || vin.vout === undefined) {\n // A non-coinbase input without an outpoint is provider data\n // corruption; fail closed (review 2026-07-15 P1).\n throw new Error(\n `provider returned tx ${txid} with a malformed vin row (missing txid/vout)`\n );\n }\n inputs.push({\n txid: vin.txid,\n vout: vin.vout,\n prevoutAddress: vin.prevout?.scriptpubkey_address,\n });\n }\n\n // Esplora vout rows are positional; a row that omits value/address\n // simply fails the output-claim check for any UTXO that references it.\n const outputs: ParentTxOutput[] = Array.isArray(data.vout)\n ? data.vout.map((vout, index) => ({\n index,\n scriptpubkey_address: vout?.scriptpubkey_address,\n value:\n typeof vout?.value === \"number\" ? BigInt(vout.value) : undefined,\n }))\n : [];\n\n return { inputs, outputs };\n } catch (error: unknown) {\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${timeout}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n", "/**\n * Vault Balance Module - Super Module for Trusted Balance Calculation\n *\n * Combines Bitcoin network data with smart contract state to calculate\n * the \"trusted balance\" - the amount available for new authorizations.\n *\n * Formula: Available Balance = Total UTXOs - Authorized Spends\n *\n * This is the primary source of truth for determining if a new spending\n * authorization can be created for a given position.\n */\n\nimport {\n AuthorizedSpend,\n UTXO,\n UTXOSet,\n VaultBalanceConfig,\n VaultBalanceResult,\n} from \"../interfaces/chunks/vault-balance.i\";\n\nimport { IVaultBalance } from \"../interfaces/chunks/vault-balance-module.i\";\nimport { IBitcoinDataProvider } from \"../interfaces/chunks/bitcoin-data-provider.i\";\nimport { LIT_ACTION_ETH_RPC_TIMEOUT_MS } from \"../constants\";\nimport { evmRpcConnection, litNodeRpcUrl } from \"./evm-rpc\";\nimport { VaultBalanceConsensus } from \"./vault-balance-consensus.module\";\n\n/**\n * Vault Balance Module\n *\n * This module is the \"super module\" that combines:\n * 1. Bitcoin network data (UTXOs from bitcoin-data-provider)\n * 2. Smart contract state (authorized spends from contract)\n *\n * To produce: Trusted Balance = Total - Authorized\n *\n * DESIGN NOTES:\n *\n * 1. Change Output Handling:\n * When a UTXO is spent, the change output will have a DIFFERENT txid.\n * This means we don't need special logic for change - it appears as a new UTXO.\n * The old UTXO (original deposit) will be gone from Bitcoin queries.\n *\n * 2. Authorization is Commitment:\n * Any UTXO in the AuthorizedSpend array is considered committed/consumed.\n * Once authorized, it's the user's responsibility to sign and broadcast.\n * If they don't, that's their problem - not the ecosystem's concern.\n *\n * 3. Security Model - Dual Source of Truth:\n * - Bitcoin Network: What UTXOs actually exist\n * - Smart Contract: What UTXOs are authorized to be spent\n * - Available Balance = Total UTXOs - Authorized UTXOs\n *\n * This prevents double-spending by ensuring the same UTXO cannot be\n * authorized twice. The contract's isAuthorizedSpend mapping enforces this.\n *\n * 4. Race Condition Protection:\n * The FAFO (First Actor Fails Others) model protects against concurrent\n * authorization attempts via state hash commitment in quantum time windows.\n * This module provides the trusted balance INPUT to that authorization process.\n *\n * 5. UTXO Matching:\n * We match authorized spends to UTXOs by (txid, vout) pair.\n * A UTXO is available if it exists in Bitcoin but NOT in authorized spends.\n *\n * 6. Edge Cases:\n * - UTXO authorized but not yet spent: Appears in Bitcoin, appears in contract\n * - UTXO spent: Doesn't appear in Bitcoin, may still appear in contract\n * - New deposit: Appears in Bitcoin, doesn't appear in contract\n *\n * 7. Confirmed-Only Gate (+ self-change carve-out):\n * A UTXO contributes to availableBalance only once it reaches\n * minConfirmations \u2014 a 0-conf third-party deposit is RBF-replaceable /\n * double-spendable and must never back a signed collateral figure.\n * EXCEPTION: unconfirmed \"self-change\" (change returned to the vault by a\n * transaction whose every input spends a confirmed, vault-owned output)\n * counts as confirmed-equivalent. Only the vault's PKP can sign such a\n * transaction, so no third party can replace it; excluding it would zero a\n * position's visible collateral for ~minConfirmations blocks after every\n * partial withdrawal and make healthy positions transiently liquidatable.\n * The self-change proof (parent tx inputs, prevout ownership, funding-tx\n * depth) is verified independently against EVERY registered provider and\n * requires unanimity; any disagreement or provider failure aborts the\n * calculation (fail-closed) so a single compromised provider can neither\n * inflate the balance (fabricated change) nor deflate it (suppressed\n * change enabling wrongful liquidation).\n * See docs/vault-balance-confirmed-gate-plan-2026-07-14.md \u00A73.1.\n */\nexport class VaultBalanceModule implements IVaultBalance {\n private config: VaultBalanceConfig;\n private bitcoinProvider: IBitcoinDataProvider;\n\n constructor(config: VaultBalanceConfig) {\n if (\n !Number.isInteger(config.minConfirmations) ||\n config.minConfirmations < 1\n ) {\n throw new Error(\n `VaultBalanceModule: minConfirmations must be a positive integer ` +\n `(got ${config.minConfirmations}). Pass the policy-derived ` +\n `balance-confirmation threshold \u2014 there is no default.`,\n );\n }\n this.config = config;\n this.bitcoinProvider = config.bitcoinProvider;\n }\n\n /**\n * Calculate balance (arithmetic only - no UTXO validation)\n *\n * Balance-only calculation: Total Balance - Authorized Balance = Available.\n *\n * \u26A0\uFE0F SECURITY (remediation P1/#5): this result skips UTXO validation, the\n * confirmed-consensus gate, and self-change proofing. It must NEVER feed a\n * signed BalanceConfirmation or any authorization decision. No production\n * action calls it (the `skipUTXOValidation` fast path that used to route\n * here was deleted); it exists for read-only diagnostics and tests. Adding\n * a production caller requires Master sign-off.\n *\n * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @returns Complete breakdown of vault balance (with empty UTXO arrays)\n */\n async calculateBalance(\n positionId: string,\n vaultAddress: string\n ): Promise<VaultBalanceResult> {\n // 1. Get balance from Bitcoin network (fast, no UTXO details)\n const totalBalance = await this.bitcoinProvider.getBalance(vaultAddress);\n\n // 2. Get authorized spends from smart contract\n const authorizedSpends: AuthorizedSpend[] =\n await this.getAuthorizedSpendsFromContract(positionId);\n\n // 3. Calculate authorized balance (sum of all authorized spends)\n const authorizedBalance = authorizedSpends.reduce(\n (sum, spend) => sum + spend.satoshis,\n 0n\n );\n\n // 4. Calculate available balance = Total - Authorized\n const availableBalance =\n totalBalance > authorizedBalance ? totalBalance - authorizedBalance : 0n;\n\n // 5. Compute authorized spends hash (race prevention)\n // Hash each spend's full details, then hash the array\n // @ts-ignore - ethers available in LIT runtime\n const authorizedSpendsHash = this.computeAuthorizedSpendsHash(\n positionId,\n authorizedSpends\n );\n\n return {\n // Total from Bitcoin\n totalUTXOs: [], // Empty for fast path\n totalBalance,\n\n // Authorized from Contract\n authorizedUTXOs: authorizedSpends,\n authorizedBalance,\n authorizedSpendsHash,\n\n // Available = Total - Authorized (THIS IS THE TRUSTED BALANCE)\n availableUTXOs: [], // Empty for fast path\n availableBalance,\n\n // Metadata\n vaultAddress,\n positionId,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Calculate trusted balance for a position (full validation)\n *\n * This is the main entry point for determining available balance with full validation.\n *\n * CRITICAL: Validates that all authorized spends have been properly broadcasted\n * to Bitcoin network with sufficient confirmations. Throws errors if:\n * 1. Authorized transaction not found on network (not broadcasted)\n * 2. Authorized transaction has insufficient confirmations (network updating)\n *\n * NOTE: the `skipUTXOValidation` fast path was removed (remediation P1/#5).\n * Every trusted-balance read runs full UTXO validation + consensus; a\n * balance that skipped validation must never feed a signed\n * BalanceConfirmation.\n *\n * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @returns Complete breakdown of vault balance\n * @throws Error if authorized spends are in invalid state\n */\n async calculateTrustedBalance(\n positionId: string,\n vaultAddress: string\n ): Promise<VaultBalanceResult> {\n const minConfirmations = this.config.minConfirmations;\n\n // 1. Get all UTXOs from Bitcoin network\n const utxoSet: UTXOSet = await this.bitcoinProvider.getUTXOSet(\n vaultAddress,\n minConfirmations\n );\n\n // 2. Get authorized spends from smart contract\n const authorizedSpends: AuthorizedSpend[] =\n await this.getAuthorizedSpendsFromContract(positionId);\n\n // 3. Authorized spends are COMMITMENTS, not exceptions (design note 2\n // above: \"Once authorized, it's the user's responsibility to sign and\n // broadcast. If they don't, that's their problem\").\n //\n // An authorized outpoint can be in one of two states, and BOTH are\n // handled by exclusion at step 6 rather than by an error here:\n // - already spent \u2192 it is absent from the UTXO set, so it cannot be\n // counted anyway;\n // - authorized but not yet broadcast \u2192 still present in the UTXO set,\n // and `isUTXOAuthorized` removes it from `availableUTXOs`, so the\n // signed collateral figure never includes sats the borrower already\n // holds a signature to move.\n //\n // This loop used to THROW on the second case (\"Authorized UTXO ... not\n // yet spent\"). That turned a borrower-controlled state into a denial of\n // service on the WHOLE module: `calculateTrustedBalance` is the only\n // balance path, and liquidation-validator \u2192 vault-snapshot goes through\n // it, so a borrower could call withdrawBTC while healthy, never\n // broadcast phase 2, and block EVERY liquidation attestation on their\n // position indefinitely (clearing an unspent reservation needs their own\n // signed envelope or the 24h admin timelock) while the position sank\n // into bad debt. Excluding is also the strictly conservative direction:\n // it can only LOWER `availableBalance`, never overstate collateral \u2014 and\n // `availableBalance` is the only figure any caller signs over\n // (vault-snapshot maps it to `availableBTCSats`; `totalBalance` is\n // informational).\n\n // 4. Calculate authorized balance (sum of all authorized spends)\n const authorizedBalance = authorizedSpends.reduce(\n (sum, spend) => sum + spend.satoshis,\n 0n\n );\n\n // Multi-provider consensus over the primary UTXO set. The consensus object\n // owns provider expansion, fan-out, output-claim parsing, confirmation-depth\n // policy, and self-change proofing (built once; both passes share readers).\n const consensus = new VaultBalanceConsensus(\n this.bitcoinProvider,\n this.config.bitcoinProviderConfigs,\n // Absent \u21D2 1: dev/test constructions without a policy keep the\n // single-provider baseline; validators pass policy.minConsensusProviders.\n this.config.minConsensusProviders ?? 1\n );\n\n // 5a. Confirmed-UTXO-set consensus: the primary's confirmed UTXOs are the\n // bulk of the signed balance, yet the UTXO set (txid/vout/value) comes only\n // from the primary \u2014 the balance consensus checks `chain_stats` totals, not\n // individual outpoints. Each primary-confirmed UTXO is cross-checked against\n // EVERY registered provider (strict: present + exact value on all). A\n // fabricated or value-inflated confirmed UTXO throws; benign tip skew at\n // the confirmation boundary demotes the UTXO (it waits a block) rather than\n // signing over a disputed figure.\n const confirmedConsensusKeys = await consensus.confirmedUtxoConsensus(\n utxoSet.utxos,\n vaultAddress,\n minConfirmations\n );\n\n // 5b. Classify unconfirmed UTXOs: only protocol self-change may bypass the\n // confirmation gate (no network calls when everything is confirmed)\n const selfChangeKeys = await consensus.classifySelfChange(\n utxoSet.utxos,\n vaultAddress,\n minConfirmations\n );\n\n // 6. Filter to available UTXOs. A UTXO is available only when it is\n // (a) confirmed with multi-provider consensus OR verified protocol\n // self-change, AND\n // (b) not committed to an authorized spend.\n // (b) is judged against the FULL UTXO set (confirmed + mempool) on purpose:\n // an authorized outpoint whose spending transaction is sitting in the\n // mempool must STAY excluded \u2014 it must not re-enter the collateral figure\n // merely because it is no longer confirmed.\n const availableUTXOs = utxoSet.utxos.filter(\n (utxo) =>\n (confirmedConsensusKeys.has(`${utxo.txid}:${utxo.vout}`) ||\n selfChangeKeys.has(`${utxo.txid}:${utxo.vout}`)) &&\n !this.isUTXOAuthorized(utxo, authorizedSpends)\n );\n\n // 7. Calculate available balance\n const availableBalance = availableUTXOs.reduce(\n (sum, utxo) => sum + utxo.satoshis,\n 0n\n );\n\n // 8. Compute authorized spends hash (race prevention)\n // Hash each spend's full details, then hash the array\n // @ts-ignore - ethers available in LIT runtime\n const authorizedSpendsHash = this.computeAuthorizedSpendsHash(\n positionId,\n authorizedSpends\n );\n\n return {\n // Total from Bitcoin\n totalUTXOs: utxoSet.utxos,\n totalBalance: utxoSet.totalBalance,\n\n // Authorized from Contract\n authorizedUTXOs: authorizedSpends,\n authorizedBalance,\n authorizedSpendsHash,\n\n // Available = Total - Authorized (THIS IS THE TRUSTED BALANCE)\n availableUTXOs,\n availableBalance,\n\n // Metadata\n vaultAddress,\n positionId,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Get just the trusted balance amount\n *\n * Convenience method when you only need the number.\n *\n * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @returns Available balance in satoshis\n */\n async getTrustedBalance(\n positionId: string,\n vaultAddress: string\n ): Promise<bigint> {\n const result = await this.calculateTrustedBalance(positionId, vaultAddress);\n return result.availableBalance;\n }\n\n /**\n * Get available UTXOs that can be used for new authorizations\n *\n * This is useful when you need to select specific UTXOs for authorization.\n *\n * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @returns Array of available UTXOs\n */\n async getAvailableUTXOs(\n positionId: string,\n vaultAddress: string\n ): Promise<UTXO[]> {\n const result = await this.calculateTrustedBalance(positionId, vaultAddress);\n return result.availableUTXOs;\n }\n\n /**\n * Check if a specific UTXO is available for authorization\n *\n * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @param txid - Transaction ID of the UTXO\n * @param vout - Output index of the UTXO\n * @returns True if UTXO is available, false otherwise\n */\n async isUTXOAvailable(\n positionId: string,\n vaultAddress: string,\n txid: string,\n vout: number\n ): Promise<boolean> {\n const availableUTXOs = await this.getAvailableUTXOs(\n positionId,\n vaultAddress\n );\n return availableUTXOs.some(\n (utxo) => utxo.txid === txid && utxo.vout === vout\n );\n }\n\n /**\n * Check if a UTXO is authorized (appears in authorized spends)\n *\n * @param utxo - The UTXO to check\n * @param authorizedSpends - List of authorized spends from contract\n * @returns True if UTXO is authorized, false otherwise\n */\n private isUTXOAuthorized(\n utxo: UTXO,\n authorizedSpends: AuthorizedSpend[]\n ): boolean {\n return authorizedSpends.some(\n (spend) => spend.txid === utxo.txid && spend.vout === utxo.vout\n );\n }\n\n /**\n * Query smart contract for authorized spends\n *\n * Calls the contract's getAuthorizedSpends(positionId) view function\n * to retrieve all authorized Bitcoin spends for this position.\n *\n * Contract struct AuthorizedSpend:\n * - txid: string\n * - vout: uint32\n * - satoshis: uint256\n * - authorizedAt: uint256 (timestamp)\n *\n * @param positionId - The position ID to query\n * @returns Array of authorized spends for this position\n */\n protected async getAuthorizedSpendsFromContract(\n positionId: string\n ): Promise<AuthorizedSpend[]> {\n // For LIT Actions, Lit.Actions.call provides RPC access\n // This uses the ethers.js-like interface available in LIT runtime\n\n // Convert positionId to bytes32 if it's a hex string\n const positionIdBytes32 = positionId.startsWith(\"0x\")\n ? positionId\n : `0x${positionId.padStart(64, \"0\")}`;\n\n // ABI fragment for getAuthorizedSpends function\n const getAuthorizedSpendsABI = [\n {\n inputs: [\n { internalType: \"bytes32\", name: \"positionId\", type: \"bytes32\" },\n ],\n name: \"getAuthorizedSpends\",\n outputs: [\n {\n components: [\n { internalType: \"string\", name: \"txid\", type: \"string\" },\n { internalType: \"uint32\", name: \"vout\", type: \"uint32\" },\n { internalType: \"uint256\", name: \"satoshis\", type: \"uint256\" },\n {\n internalType: \"string\",\n name: \"targetAddress\",\n type: \"string\",\n },\n {\n internalType: \"uint256\",\n name: \"targetAmount\",\n type: \"uint256\",\n },\n // changeAddress removed - contract derives from position.vaultAddress\n {\n internalType: \"uint256\",\n name: \"authorizedAt\",\n type: \"uint256\",\n },\n ],\n internalType: \"struct LoanOperationsManager.AuthorizedSpend[]\",\n name: \"\",\n type: \"tuple[]\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n ];\n\n // Get RPC URL - either from config (for local testing) or from Lit runtime\n let rpcUrl: string;\n\n if (this.config.rpcUrl) {\n // Local testing: use provided RPC URL\n rpcUrl = this.config.rpcUrl;\n } else {\n // Production: get RPC from Lit runtime\n rpcUrl = await litNodeRpcUrl(this.config.chain, this.config.drpcKey);\n }\n\n // Use ethers.js to query the contract directly\n // @ts-ignore - ethers is available in LIT runtime\n // StaticJsonRpcProvider with just chainId (no network name) to avoid validation errors\n // This works for all chains including custom RPCs (ngrok, localhost, hardhat)\n // @ts-ignore - ethers is available in LIT runtime\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.config.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n this.config.chainId\n );\n\n // @ts-ignore - ethers is available in LIT runtime\n const contract = new ethers.Contract(\n this.config.contractAddress,\n getAuthorizedSpendsABI,\n provider\n );\n\n const result = await contract.getAuthorizedSpends(positionIdBytes32);\n\n // Transform contract response to our interface\n return result.map((spend: any) => ({\n txid: spend.txid,\n vout: Number(spend.vout),\n satoshis: BigInt(spend.satoshis.toString()),\n positionId: positionId,\n targetAddress: spend.targetAddress,\n targetAmount: BigInt(spend.targetAmount.toString()),\n // changeAddress removed - contract doesn't return this field\n timestamp: Number(spend.authorizedAt),\n }));\n }\n\n /**\n * Compute authorized spends hash matching contract implementation\n *\n * CRITICAL: Must match LoanOperationsManager.getAuthorizedSpendsHash()\n *\n * Algorithm:\n * 1. For each AuthorizedSpend, hash all 6 fields:\n * - keccak256(txid string)\n * - vout (uint32)\n * - satoshis (uint256)\n * - keccak256(targetAddress string)\n * - targetAmount (uint256)\n * - authorizedAt (uint256 timestamp)\n * 2. Hash the array: keccak256(abi.encode(positionId, array of hashed spends))\n *\n * @param positionId - Position identifier\n * @param authorizedSpends - Array of authorized spends\n * @returns bytes32 hash matching contract\n */\n private computeAuthorizedSpendsHash(\n positionId: string,\n authorizedSpends: AuthorizedSpend[]\n ): string {\n const positionIdBytes32 = positionId.startsWith(\"0x\")\n ? positionId\n : `0x${positionId.padStart(64, \"0\")}`;\n\n // Empty authorized spends case\n if (authorizedSpends.length === 0) {\n // @ts-ignore - ethers available in LIT runtime\n return ethers.utils.keccak256(\n // @ts-ignore - ethers available in LIT runtime\n ethers.utils.defaultAbiCoder.encode(\n [\"bytes32\", \"bytes32[]\"],\n [positionIdBytes32, []]\n )\n );\n }\n\n // Hash each authorized spend with all 6 fields\n const hashedSpends = authorizedSpends.map((spend) => {\n // @ts-ignore - ethers available in LIT runtime\n const txidHash = ethers.utils.keccak256(\n // @ts-ignore - ethers available in LIT runtime\n ethers.utils.toUtf8Bytes(spend.txid)\n );\n // @ts-ignore - ethers available in LIT runtime\n const targetHash = ethers.utils.keccak256(\n // @ts-ignore - ethers available in LIT runtime\n ethers.utils.toUtf8Bytes(spend.targetAddress)\n );\n\n // Hash all 6 fields: txidHash, vout, satoshis, targetHash, targetAmount, authorizedAt\n // @ts-ignore - ethers available in LIT runtime\n return ethers.utils.keccak256(\n // @ts-ignore - ethers available in LIT runtime\n ethers.utils.defaultAbiCoder.encode(\n [\"bytes32\", \"uint32\", \"uint256\", \"bytes32\", \"uint256\", \"uint256\"],\n [\n txidHash,\n spend.vout,\n spend.satoshis.toString(),\n targetHash,\n spend.targetAmount.toString(),\n spend.timestamp, // authorizedAt\n ]\n )\n );\n });\n\n // Hash positionId with array of hashed spends\n // @ts-ignore - ethers available in LIT runtime\n return ethers.utils.keccak256(\n // @ts-ignore - ethers available in LIT runtime\n ethers.utils.defaultAbiCoder.encode(\n [\"bytes32\", \"bytes32[]\"],\n [positionIdBytes32, hashedSpends]\n )\n );\n }\n}\n\n/**\n * Factory function to create VaultBalanceModule instance\n *\n * @param config - Configuration for the module\n * @returns VaultBalanceModule instance\n */\nexport function createVaultBalanceModule(\n config: VaultBalanceConfig\n): VaultBalanceModule {\n return new VaultBalanceModule(config);\n}\n\n/**\n * USAGE EXAMPLE:\n *\n * ```typescript\n * import { createVaultBalanceModule } from './vault-balance.module';\n * import { BitcoinDataProvider } from './bitcoin-data-provider.module';\n *\n * const bitcoinProvider = new BitcoinDataProvider({\n * providerUrl: 'https://blockstream.info/testnet/api'\n * });\n *\n * const vaultBalance = createVaultBalanceModule({\n * contractAddress: '0x...',\n * chain: 'sepolia',\n * bitcoinProvider,\n * minConfirmations: 6\n * });\n *\n * // Get complete balance breakdown\n * const result = await vaultBalance.calculateTrustedBalance(\n * 'position123',\n * 'tb1q...'\n * );\n *\n * console.log('Total Balance:', result.totalBalance, 'sats');\n * console.log('Authorized Balance:', result.authorizedBalance, 'sats');\n * console.log('Available Balance:', result.availableBalance, 'sats');\n *\n * // Or just get the available amount\n * const available = await vaultBalance.getTrustedBalance('position123', 'tb1q...');\n * console.log('Can authorize:', available, 'sats');\n * ```\n */\n", "/**\n * Chain-derived security policy for LIT Actions.\n *\n * Replaces the previous attacker-supplied `auth.mode === \"prod\" | \"dev\"`\n * toggle (see audit finding C-1). Policy is derived from the `chain` string\n * the caller passes, after running it through `validateChain` \u2014 anything\n * outside the known chain set is rejected up front.\n *\n * Because every signed EIP-712 payload produced downstream binds the\n * chainId via OZ EIP712Upgradeable (block.chainid at verify time), an\n * attacker who lies about `chain` to soften the policy can only obtain a\n * signature valid under the chain they claimed \u2014 which is useless against\n * any other chain's contracts. Chain binding is therefore sufficient to\n * make per-chain policy an authoritative switch.\n */\n\nimport {\n APPROVED_EVM_RPC_DOMAINS,\n BitcoinNetwork,\n CHAIN_TO_BITCOIN_NETWORK,\n CHAIN_TO_CHAIN_ID,\n EVMChain,\n validateChain,\n} from \"../constants\";\n\nexport interface ChainPolicy {\n chain: EVMChain;\n chainId: number;\n bitcoinNetwork: BitcoinNetwork;\n /**\n * When true, the caller-supplied Bitcoin provider URL is accepted without\n * looking it up in any allowlist / registry. Only hardhat (regtest) sets\n * this \u2014 the local Bitcoin daemon URL is never fixed.\n */\n allowArbitraryBitcoinProvider: boolean;\n /**\n * When true, the caller-supplied EVM RPC URL is accepted without\n * matching APPROVED_EVM_RPC_DOMAINS. Only hardhat sets this \u2014 we\n * want to allow `http://localhost:8545` during local tests.\n */\n allowArbitraryEvmRpc: boolean;\n /**\n * When true, the security-critical contract addresses are taken from the\n * generated pinned map (constants/chunks/deployment-addresses.ts) and any\n * caller-supplied values are IGNORED \u2014 a contradicting supplied value is\n * rejected loudly (F1 remediation). sepolia + ethereum set this; hardhat\n * does not, because local deployments are freshly generated per run and\n * carry no real funds, so the caller-supplied addresses are used as before.\n *\n * This is the ONLY switch that decides \"real chain\" for address pinning, and\n * \u2014 like allowArbitraryEvmRpc \u2014 it is bound to the signed `chain` string, not\n * to any mutable server env. A caller who lies about `chain` to soften the\n * policy only obtains a signature valid on the claimed chain, useless\n * elsewhere (EIP-712 binds block.chainid at verify time).\n */\n pinContractAddresses: boolean;\n /**\n * When true, a validator may run the price oracle in single-provider plaintext\n * mode (one un-encrypted key) instead of the locked 3-of-3 encrypted set. Only\n * hardhat sets this \u2014 it lets the local mega test run with the one key we hold.\n * sepolia/mainnet keep it false, so a requested dev price flag is REJECTED there;\n * and because a price is signed against this chain's EIP-712 domain, a hardhat-\n * signed single-provider price is unusable on any other chain anyway.\n */\n allowDevSinglePriceProvider: boolean;\n /**\n * Confirmations a UTXO needs before it counts toward \"confirmed vault\n * balance\" (regtest/testnet=1, mainnet=6). This is the single definition of\n * confirmed balance used by EVERY balance-reading flow \u2014 deposit\n * confirmation, mint, address-balance, and the extend/liquidation/payment\n * collateral checks \u2014 so all validators agree on what a vault holds.\n * NEVER use this to gate UTXO spends; that is `minBitcoinSpendConfirmations`.\n */\n minBitcoinBalanceConfirmations: number;\n /**\n * Confirmations a UTXO needs before the protocol may SPEND it\n * (regtest/testnet=1, mainnet=6). Reorg protection on outgoing transactions\n * \u2014 used by the btc-withdrawal spend gate and as the stale-spend recovery\n * floor. Must never be looser than the balance threshold.\n */\n minBitcoinSpendConfirmations: number;\n /**\n * Minimum number of registered Bitcoin providers required before any\n * balance-consensus read may proceed (fail-closed below the floor \u2014 see\n * tasks/security/btc-lit-actions-remediation-plan-2026-07-15.md P1/#1).\n * hardhat: 1 (single local daemon is the legitimate dev baseline).\n * sepolia: 1 (single faucet provider by design \u2014 the consensus floor is a\n * mainnet guarantee; multi-provider paths are covered by unit tests).\n * ethereum: 2 (registry holds Validation Cloud + Blockstream Enterprise\n * after the 2026-09 Maestro retirement; raise to 3 once a third independent\n * operator is registered).\n */\n minConsensusProviders: number;\n}\n\nconst POLICY_BY_CHAIN: Record<EVMChain, ChainPolicy> = {\n [EVMChain.HARDHAT]: {\n chain: EVMChain.HARDHAT,\n chainId: CHAIN_TO_CHAIN_ID[EVMChain.HARDHAT],\n bitcoinNetwork: CHAIN_TO_BITCOIN_NETWORK[EVMChain.HARDHAT],\n allowArbitraryBitcoinProvider: true,\n allowArbitraryEvmRpc: true,\n pinContractAddresses: false,\n allowDevSinglePriceProvider: true,\n minBitcoinBalanceConfirmations: 1,\n minBitcoinSpendConfirmations: 1,\n minConsensusProviders: 1,\n },\n [EVMChain.SEPOLIA]: {\n chain: EVMChain.SEPOLIA,\n chainId: CHAIN_TO_CHAIN_ID[EVMChain.SEPOLIA],\n bitcoinNetwork: CHAIN_TO_BITCOIN_NETWORK[EVMChain.SEPOLIA],\n allowArbitraryBitcoinProvider: false,\n allowArbitraryEvmRpc: false,\n pinContractAddresses: true,\n allowDevSinglePriceProvider: false,\n minBitcoinBalanceConfirmations: 1,\n minBitcoinSpendConfirmations: 1,\n // 2 since 2026-09-23. It was 1 because Sepolia ran a single faucet provider\n // \"by design\", so the consensus floor was documented as a mainnet-only\n // guarantee. The registry now holds two, and leaving the floor at 1 meant\n // Sepolia could never exercise the multi-provider agreement the stale-spend\n // and balance paths rely on \u2014 the one environment where that logic is\n // supposed to be proved before mainnet.\n minConsensusProviders: 2,\n },\n [EVMChain.ETHEREUM]: {\n chain: EVMChain.ETHEREUM,\n chainId: CHAIN_TO_CHAIN_ID[EVMChain.ETHEREUM],\n bitcoinNetwork: CHAIN_TO_BITCOIN_NETWORK[EVMChain.ETHEREUM],\n allowArbitraryBitcoinProvider: false,\n allowArbitraryEvmRpc: false,\n pinContractAddresses: true,\n allowDevSinglePriceProvider: false,\n minBitcoinBalanceConfirmations: 6,\n minBitcoinSpendConfirmations: 6,\n minConsensusProviders: 2,\n },\n};\n\n/**\n * Resolve the security policy for a chain string. Throws on unknown chains.\n */\nexport function getChainPolicy(chain: string): ChainPolicy {\n const validated = validateChain(chain);\n const policy = POLICY_BY_CHAIN[validated];\n if (!policy) {\n // Unreachable: validateChain only ever returns a known EVMChain value.\n throw new Error(`No chain policy registered for \"${chain}\"`);\n }\n return policy;\n}\n\n/**\n * Validate an EVM RPC URL under the given policy.\n *\n * hardhat \u2192 no-op.\n * sepolia / ethereum \u2192 hostname must equal or end with an approved domain\n * from APPROVED_EVM_RPC_DOMAINS. The `endsWith(\".<domain>\")` rule already\n * covers subdomains like `sepolia.drpc.org` / `eth-mainnet.g.alchemy.com`\n * would match `drpc.org` / an `alchemy.com` entry without extra config.\n *\n * Throws on mismatch so the caller doesn't accidentally fall through to an\n * attacker-controlled RPC.\n */\nexport function validateEvmRpcForPolicy(\n policy: ChainPolicy,\n rpcUrl: string,\n): void {\n if (policy.allowArbitraryEvmRpc) {\n return;\n }\n if (!rpcUrl || typeof rpcUrl !== \"string\") {\n throw new Error(\"validateEvmRpcForPolicy: rpcUrl must be a non-empty string\");\n }\n let hostname: string;\n try {\n hostname = new URL(rpcUrl).hostname;\n } catch (e: any) {\n throw new Error(`Invalid rpcUrl: ${e?.message ?? String(e)}`);\n }\n const approved = APPROVED_EVM_RPC_DOMAINS.some(\n (domain) => hostname === domain || hostname.endsWith(`.${domain}`),\n );\n if (!approved) {\n throw new Error(\n `Custom RPC domain \"${hostname}\" is not in the approved list: ${APPROVED_EVM_RPC_DOMAINS.join(\", \")}`,\n );\n }\n}\n", "/**\n * Price Oracle Executor - NOLA (No LIT Action)\n *\n * Standalone executor that wraps PriceOracleModule for Node.js execution.\n * Reuses the same pattern as tests/helpers/setup-lit-env.ts.\n *\n * Purpose: FREE price queries without paying for LIT Action execution.\n * Use case: Display current BTC price, calculate mint previews, show collateral ratios.\n *\n * Architecture:\n * - Same price-oracle.module.ts code (zero changes)\n * - Inject Node.js fetch instead of Lit.Actions.*\n * - Returns identical price data with 8 decimals\n *\n * The previously-exposed `executePriceOracleConsensus` variant was removed in\n * the H-2 audit fix \u2014 the lenient consensus algorithm is gone, so there is now\n * only one strict path.\n */\n\nimport { PriceOracleModule } from \"../../../src/modules/price-oracle.module\";\nimport { PriceSourceConfig } from \"../../../src/interfaces/chunks/price-oracle.i\";\n\n/**\n * Parameters for price oracle execution\n */\nexport interface PriceOracleExecutorParams {\n priceProviders?: Array<{\n name: string;\n apiKey?: string;\n apiSecret?: string;\n }>;\n customSources?: PriceSourceConfig[];\n mode?: \"dev\" | \"prod\";\n}\n\n/**\n * Execute price oracle in Node.js (NOLA - No LIT Action).\n *\n * Strict 3-of-3: caller must supply exactly 3 distinct providers from the\n * locked set (cryptocompare, coinmarketcap, coingecko). Any single provider\n * failure aborts the call; the 3 prices must lie within 1% of each other.\n *\n * @param params - Optional configuration\n * @returns BTC price in USD with 8 decimals (bigint)\n */\nexport async function executePriceOracle(\n params?: PriceOracleExecutorParams\n): Promise<bigint> {\n // Setup Lit.Actions mock (same pattern as tests/helpers/setup-lit-env.ts)\n // Note: We don't cleanup to avoid race conditions with background promises\n (global as any).Lit = {\n Actions: {\n /**\n * Broadcast and collect (NOLA mode: single node, just return value)\n * In LIT Actions environment, this would collect values from all nodes.\n * In NOLA executor, we're running on a single trusted node, so return single value.\n */\n broadcastAndCollect: async ({\n name,\n value,\n }: {\n name: string;\n value: string;\n }): Promise<string[]> => {\n // NOLA: Single node execution, return array with single value\n return [value];\n },\n },\n };\n\n // Initialize price oracle with optional config\n const oracle = params?.customSources\n ? new PriceOracleModule({}, params.customSources, params?.mode)\n : new PriceOracleModule(params?.priceProviders, undefined, params?.mode);\n\n // Execute - returns identical price as LIT Action would\n return await oracle.getBTCPrice();\n}\n", "/**\n * NOLA Executors Catalog\n *\n * Standalone executors for running LIT Action modules in Node.js (NOLA - No LIT Action).\n * These executors wrap existing modules with Node.js providers for FREE data access.\n *\n * Use cases:\n * - Position listing (100 positions = FREE)\n * - Collateral ratio display (FREE)\n * - Mint preview/validation (FREE)\n * - Any data view that doesn't require PKP signature\n *\n * Architecture: Same code as LIT Actions, different execution context.\n */\n\n// Import executors\nimport { executeVaultSnapshot, VaultSnapshotExecutorParams } from './chunks/vault-snapshot-executor';\nimport { executePriceOracle, PriceOracleExecutorParams } from './chunks/price-oracle-executor';\n\n/**\n * NOLA Executors Catalog\n *\n * Registry of all available NOLA executors with metadata.\n */\nexport const NOLA_EXECUTORS = {\n /**\n * Vault Snapshot Executor\n *\n * Returns complete position health metrics:\n * - BTC balance (total, authorized, available)\n * - Collateral ratio and liquidation risk\n * - Term status (duration, expiry, grace period)\n * - Protocol parameters (fees, thresholds)\n *\n * Cost: FREE (no LIT Action execution)\n * Same data as LIT Action would return\n */\n vaultSnapshot: {\n name: 'vault-snapshot',\n description: 'Get complete position health metrics',\n executor: executeVaultSnapshot,\n version: '1.0.0',\n },\n\n /**\n * Price Oracle Executor\n *\n * Returns BTC price in USD (8 decimals) via strict 3-of-3 consensus:\n * - All 3 configured providers must respond\n * - Prices must agree within 1%\n * - Returns the median\n *\n * Cost: FREE (no LIT Action execution)\n * Use for: Price display, mint preview, collateral ratio calculation\n */\n priceOracle: {\n name: 'price-oracle',\n description: 'Get current BTC price (strict 3-of-3 consensus)',\n executor: executePriceOracle,\n version: '2.0.0',\n },\n} as const;\n\n// Re-export executors for direct import\nexport { executeVaultSnapshot } from './chunks/vault-snapshot-executor';\nexport { executePriceOracle } from './chunks/price-oracle-executor';\n\n// Re-export types\nexport type { VaultSnapshotExecutorParams } from './chunks/vault-snapshot-executor';\nexport type { PriceOracleExecutorParams } from './chunks/price-oracle-executor';\n", "/**\n * EIP-712 type definitions for the two **owner-signed BTC-custody** messages:\n * the withdrawal execute step and the stale-spend invalidate step\n * (`contracts/docs/EIP712_DOMAIN_SPEC.md` \u00A73.8; plan\n * `docs/vigil/plans/2026-10-16-A2-eip712-withdrawal-authorization-plan.md`).\n *\n * **Single source of truth** for the verifier side. The SDK carries a copy\n * (`sdk/src/utils/btc-spend-request-712.ts`) until it depends on a\n * `dh-lit-actions` that exports this module; the golden vectors in\n * `tests/vectors/btc-spend-request.v1.json` keep the two byte-identical.\n *\n * ## Why a separate module from `borrower-authorization-types.ts`\n *\n * Different domain: these bind to the **BTCSpendAuthorizer** proxy, the\n * contract that holds the spend record the signature consumes, not to the\n * LoanOperationsManager. It is also deliberately kept out of the\n * `constants/index.ts` barrel that every action imports, so only the two\n * actions that verify these messages change bytes when it changes.\n *\n * ## Naming\n *\n * Owner-signed types are `*Request`. \u00A73.4's `BtcSpendAuth` is the validator\n * PKP's attestation \u2014 a different signer over a different digest.\n */\n\nimport { getPinnedContractAddresses } from \"./chunks/deployment-addresses\";\nimport {\n PROTOCOL_EIP712_DOMAIN_NAME,\n PROTOCOL_EIP712_DOMAIN_VERSION,\n} from \"./message-hash-domains\";\n\n/** One EIP-712 struct member. Shape is compatible with both ethers v5 and v6. */\nexport interface BtcSpendRequestField {\n readonly name: string;\n readonly type: string;\n}\n\nexport const BTC_SPEND_REQUEST_PRIMARY_TYPES = {\n EXECUTE: \"ExecuteBtcWithdrawalRequest\",\n INVALIDATE: \"InvalidateStaleSpendRequest\",\n} as const;\n\nexport type BtcSpendRequestPrimaryType =\n (typeof BTC_SPEND_REQUEST_PRIMARY_TYPES)[keyof typeof BTC_SPEND_REQUEST_PRIMARY_TYPES];\n\n/**\n * Field lists per primary type. **Order is part of the digest** \u2014 appending,\n * reordering, or renaming a member changes every signature and invalidates\n * the ERC-7730 descriptor in the same step.\n *\n * Execute lists what the borrower judges first (destination, what arrives,\n * the fee, the total) ahead of protocol bookkeeping, so a device that\n * truncates still shows the decision-relevant fields.\n */\nexport const BTC_SPEND_REQUEST_FIELDS: Readonly<\n Record<BtcSpendRequestPrimaryType, readonly BtcSpendRequestField[]>\n> = {\n ExecuteBtcWithdrawalRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"withdrawalAddress\", type: \"string\" },\n { name: \"recipientAmount\", type: \"uint256\" },\n { name: \"networkFee\", type: \"uint256\" },\n { name: \"totalDeduction\", type: \"uint256\" },\n { name: \"spendTxid\", type: \"string\" },\n { name: \"spendVout\", type: \"uint32\" },\n { name: \"inputSetHash\", type: \"bytes32\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n InvalidateStaleSpendRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"spendTxid\", type: \"string\" },\n { name: \"spendVout\", type: \"uint32\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n} as const;\n\n/**\n * Frozen `encodeType` strings. Duplicated from the field lists on purpose:\n * they are the exact `display.formats` keys of the ERC-7730 descriptor, and\n * the unit suite asserts an encoder derives these same strings from\n * `BTC_SPEND_REQUEST_FIELDS`.\n */\nexport const BTC_SPEND_REQUEST_ENCODE_TYPES: Readonly<\n Record<BtcSpendRequestPrimaryType, string>\n> = {\n ExecuteBtcWithdrawalRequest:\n \"ExecuteBtcWithdrawalRequest(bytes32 positionId,string withdrawalAddress,uint256 recipientAmount,uint256 networkFee,uint256 totalDeduction,string spendTxid,uint32 spendVout,bytes32 inputSetHash,uint256 quantumTimestamp)\",\n InvalidateStaleSpendRequest:\n \"InvalidateStaleSpendRequest(bytes32 positionId,string spendTxid,uint32 spendVout,uint256 quantumTimestamp)\",\n} as const;\n\n/** EIP-712 domain for BTC-custody owner authorizations. */\nexport interface BtcSpendRequestDomain {\n readonly name: string;\n readonly version: string;\n readonly chainId: number;\n readonly verifyingContract: string;\n}\n\n/**\n * The `types` argument for `TypedDataEncoder.hash(domain, types, message)`.\n * Returns ONLY the requested primary type, so a message shaped like the other\n * type cannot encode without complaint.\n *\n * @throws if `primaryType` is not one of the two.\n */\nexport function btcSpendRequestTypes(\n primaryType: BtcSpendRequestPrimaryType,\n): Record<string, BtcSpendRequestField[]> {\n const fields = BTC_SPEND_REQUEST_FIELDS[primaryType];\n if (!fields) {\n throw new Error(\n `Unknown BTC spend request primary type \"${primaryType}\"; ` +\n `expected one of ${Object.keys(BTC_SPEND_REQUEST_FIELDS).join(\", \")}`,\n );\n }\n return { [primaryType]: fields.map((field) => ({ ...field })) };\n}\n\n/**\n * Build the EIP-712 domain for a chain. `verifyingContract` is the pinned\n * BTCSpendAuthorizer proxy. Same rule as `buildBorrowerAuthorizationDomain`:\n * on a pinned chain an override is CHECKED, never honoured, and a\n * contradicting value throws; on an unpinned chain (hardhat) the override\n * supplies the domain and its absence throws.\n */\nexport function buildBtcSpendRequestDomain(\n chainId: number,\n verifyingContractOverride?: string,\n): BtcSpendRequestDomain {\n if (!Number.isInteger(chainId) || chainId <= 0) {\n throw new Error(\n `BTC spend request domain requires a positive integer chainId, got ${String(chainId)}`,\n );\n }\n\n const pinned = getPinnedContractAddresses(chainId);\n const pinnedAuthorizer = pinned?.BTCSpendAuthorizer;\n\n if (pinnedAuthorizer && verifyingContractOverride) {\n if (pinnedAuthorizer.toLowerCase() !== verifyingContractOverride.toLowerCase()) {\n throw new Error(\n `Refusing a caller-supplied verifyingContract that contradicts the pin for chainId ${chainId}: ` +\n `caller ${verifyingContractOverride}, pinned ${pinnedAuthorizer}`,\n );\n }\n }\n\n const verifyingContract = pinnedAuthorizer ?? verifyingContractOverride;\n if (!verifyingContract) {\n throw new Error(\n `No pinned BTCSpendAuthorizer for chainId ${chainId} and no verifyingContract supplied; ` +\n `refusing to build a BTC spend request domain without one`,\n );\n }\n\n return {\n name: PROTOCOL_EIP712_DOMAIN_NAME,\n version: PROTOCOL_EIP712_DOMAIN_VERSION,\n chainId,\n verifyingContract,\n };\n}\n\n/**\n * Canonical Bitcoin txid for a typed message: lowercase, no `0x`, exactly 64\n * hex characters. BTCSpendAuthorizer stores `txid` as an unvalidated string,\n * so anything else is refused here rather than encoded.\n *\n * @throws if the canonical form is not 64 hex characters.\n */\nexport function canonicalBtcTxid(txid: unknown): string {\n const canonical = String(txid).toLowerCase().replace(/^0x/, \"\");\n if (!/^[0-9a-f]{64}$/.test(canonical)) {\n throw new Error(\n `Invalid Bitcoin txid \"${String(txid)}\": expected 64 hex characters (optionally 0x-prefixed)`,\n );\n }\n return canonical;\n}\n"],
5
- "mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAkCO,SAAS,sBAAsB,QAAoC;AACxE,gBAAc,EAAE,GAAG,aAAa,GAAG,OAAO;AAC5C;AAKA,SAAS,eAAuB;AAC9B,UAAO,oBAAI,KAAK,GAAE,YAAY;AAChC;AAKA,SAAS,cAAc,OAAe,WAAmB,SAAiB,UAAwB;AAChG,QAAM,YAAY,YAAY,mBAAmB,IAAI,aAAa,CAAC,OAAO;AAC1E,QAAM,cAAc,WAAW,IAAI,KAAK,UAAU,QAAQ,CAAC,KAAK;AAChE,SAAO,GAAG,SAAS,IAAI,KAAK,MAAM,SAAS,KAAK,OAAO,GAAG,WAAW;AACvE;AAkHO,SAAS,WAAW,WAAmB,SAAiB,UAAsB;AACnF,MAAI,YAAY,SAAS,eAAgB;AACvC,YAAQ,MAAM,cAAc,SAAS,WAAW,SAAS,QAAQ,CAAC;AAAA,EACpE;AACF;AAEO,SAAS,UAAU,WAAmB,SAAiB,UAAsB;AAClF,MAAI,Y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,EAAE;AAC9D,MAAI,CAAC,iBAAiB,KAAK,SAAS,GAAG;AACrC,UAAM,IAAI;AAAA,MACR,yBAAyB,OAAO,IAAI,CAAC;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AACT;",
3
+ "sources": ["../../pkg-src/utils/chunks/debug-logger.ts", "../../pkg-src/utils/chunks/session-signature-cache.ts", "../../pkg-src/index.ts", "../../node_modules/base-x/src/esm/index.js", "../../node_modules/bs58/src/esm/index.js", "../../pkg-src/utils/chunks/cid-utils.ts", "../../pkg-src/constants/chunks/lit-actions-registry.ts", "../../pkg-src/utils/chunks/lit-action-helpers.ts", "../../pkg-src/utils/chunks/pkp-setup.ts", "../../pkg-src/utils/chunks/connection-helpers.ts", "../../pkg-src/utils/chunks/error-classification.ts", "../../pkg-src/utils/index.ts", "../../pkg-src/executors/chunks/vault-snapshot-executor.ts", "../../src/constants/chunks/liquidation.ts", "../../src/constants/chunks/decimals.ts", "../../src/constants/chunks/bitcoin.ts", "../../src/constants/chunks/quantum-time.ts", "../../src/constants/chunks/time.ts", "../../src/constants/chunks/lit-action-runtime.ts", "../../src/constants/chunks/deployment-addresses.ts", "../../src/constants/message-hash-domains.ts", "../../src/constants/borrower-authorization-types.ts", "../../src/constants/chunks/bitcoin-network-config.ts", "../../src/modules/business-rules-math.module.ts", "../../src/modules/evm-rpc.ts", "../../src/modules/protocol-parameters.module.ts", "../../src/modules/vault-address.ts", "../../src/modules/vault-snapshot.ts", "../../src/modules/lit-action-debug.ts", "../../src/modules/lit-action-logger.module.ts", "../../src/modules/lit-global-bootstrap.ts", "../../src/modules/bitcoin-provider-auth.ts", "../../src/modules/bitcoin-data-provider.module.ts", "../../src/modules/price-oracle.module.ts", "../../src/modules/vault-balance-consensus.module.ts", "../../src/modules/vault-balance.module.ts", "../../src/modules/chain-policy.ts", "../../pkg-src/executors/chunks/price-oracle-executor.ts", "../../pkg-src/executors/index.ts", "../../src/constants/btc-spend-request-types.ts"],
4
+ "sourcesContent": ["/**\n * Enhanced Debug Logger for LIT Protocol Operations\n * Provides detailed logging for debugging network and protocol issues\n */\n\nexport enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3,\n TRACE = 4\n}\n\nexport interface DebugConfig {\n level: LogLevel;\n enableTimestamps: boolean;\n enablePerformanceMetrics: boolean;\n enableRequestLogging: boolean;\n enableNetworkMetrics: boolean;\n}\n\nexport const DEFAULT_DEBUG_CONFIG: DebugConfig = {\n level: LogLevel.INFO,\n enableTimestamps: true,\n enablePerformanceMetrics: true,\n enableRequestLogging: true,\n enableNetworkMetrics: true\n};\n\nlet debugConfig: DebugConfig = { ...DEFAULT_DEBUG_CONFIG };\n\n/**\n * Configure debug logging\n */\nexport function configureDebugLogging(config: Partial<DebugConfig>): void {\n debugConfig = { ...debugConfig, ...config };\n}\n\n/**\n * Get current timestamp string\n */\nfunction getTimestamp(): string {\n return new Date().toISOString();\n}\n\n/**\n * Format log message with metadata\n */\nfunction formatMessage(level: string, component: string, message: string, metadata?: any): string {\n const timestamp = debugConfig.enableTimestamps ? `[${getTimestamp()}] ` : '';\n const metadataStr = metadata ? ` ${JSON.stringify(metadata)}` : '';\n return `${timestamp}[${level}] [${component}] ${message}${metadataStr}`;\n}\n\n/**\n * Performance metrics tracker\n */\nexport class PerformanceTracker {\n private startTime: number;\n private markers: Map<string, number> = new Map();\n\n constructor(private operationName: string) {\n this.startTime = Date.now();\n this.log('PERF', `Started: ${operationName}`);\n }\n\n mark(label: string): void {\n const elapsed = Date.now() - this.startTime;\n this.markers.set(label, elapsed);\n this.log('PERF', `${this.operationName} - ${label}: ${elapsed}ms`);\n }\n\n end(success: boolean = true): number {\n const totalTime = Date.now() - this.startTime;\n const status = success ? 'SUCCESS' : 'FAILED';\n this.log('PERF', `${this.operationName} - ${status}: ${totalTime}ms`);\n\n if (debugConfig.enablePerformanceMetrics && this.markers.size > 0) {\n console.log(`\uD83D\uDCCA Performance Breakdown for ${this.operationName}:`);\n for (const [label, time] of this.markers) {\n console.log(` ${label}: ${time}ms`);\n }\n console.log(` Total: ${totalTime}ms`);\n }\n\n return totalTime;\n }\n\n private log(level: string, message: string): void {\n if (debugConfig.enablePerformanceMetrics) {\n console.log(formatMessage(level, 'PERFORMANCE', message));\n }\n }\n}\n\n/**\n * Network metrics collector\n */\nexport interface NetworkMetrics {\n requestCount: number;\n successCount: number;\n failureCount: number;\n averageLatency: number;\n lastError?: string;\n startTime: number;\n}\n\nclass NetworkMetricsCollector {\n private metrics: Map<string, NetworkMetrics> = new Map();\n\n getMetrics(operation: string): NetworkMetrics {\n if (!this.metrics.has(operation)) {\n this.metrics.set(operation, {\n requestCount: 0,\n successCount: 0,\n failureCount: 0,\n averageLatency: 0,\n startTime: Date.now()\n });\n }\n return this.metrics.get(operation)!;\n }\n\n recordRequest(operation: string, success: boolean, latency: number, error?: string): void {\n const metrics = this.getMetrics(operation);\n metrics.requestCount++;\n\n if (success) {\n metrics.successCount++;\n // Update average latency\n metrics.averageLatency = (metrics.averageLatency * (metrics.successCount - 1) + latency) / metrics.successCount;\n } else {\n metrics.failureCount++;\n if (error) metrics.lastError = error;\n }\n\n if (debugConfig.enableNetworkMetrics) {\n const successRate = ((metrics.successCount / metrics.requestCount) * 100).toFixed(1);\n debugLog('NETWORK', `${operation} - Success: ${success}, Latency: ${latency}ms, Success Rate: ${successRate}%`);\n }\n }\n\n printSummary(): void {\n if (!debugConfig.enableNetworkMetrics) return;\n\n console.log('\\n\uD83D\uDCC8 Network Metrics Summary:');\n for (const [operation, metrics] of this.metrics) {\n const successRate = ((metrics.successCount / metrics.requestCount) * 100).toFixed(1);\n const runtime = Date.now() - metrics.startTime;\n console.log(` ${operation}:`);\n console.log(` Requests: ${metrics.requestCount}`);\n console.log(` Success Rate: ${successRate}%`);\n console.log(` Avg Latency: ${metrics.averageLatency.toFixed(0)}ms`);\n console.log(` Runtime: ${runtime}ms`);\n if (metrics.lastError) {\n console.log(` Last Error: ${metrics.lastError}`);\n }\n }\n }\n}\n\nexport const networkMetrics = new NetworkMetricsCollector();\n\n/**\n * Debug logging functions\n */\nexport function debugError(component: string, message: string, metadata?: any): void {\n if (debugConfig.level >= LogLevel.ERROR) {\n console.error(formatMessage('ERROR', component, message, metadata));\n }\n}\n\nexport function debugWarn(component: string, message: string, metadata?: any): void {\n if (debugConfig.level >= LogLevel.WARN) {\n console.warn(formatMessage('WARN', component, message, metadata));\n }\n}\n\nexport function debugInfo(component: string, message: string, metadata?: any): void {\n if (debugConfig.level >= LogLevel.INFO) {\n console.log(formatMessage('INFO', component, message, metadata));\n }\n}\n\nexport function debugLog(component: string, message: string, metadata?: any): void {\n if (debugConfig.level >= LogLevel.DEBUG) {\n console.log(formatMessage('DEBUG', component, message, metadata));\n }\n}\n\nexport function debugTrace(component: string, message: string, metadata?: any): void {\n if (debugConfig.level >= LogLevel.TRACE) {\n console.log(formatMessage('TRACE', component, message, metadata));\n }\n}\n\n/**\n * Request/Response logger for LIT Protocol operations\n */\nexport function logRequest(component: string, operation: string, params: any): void {\n if (!debugConfig.enableRequestLogging) return;\n\n debugLog(component, `\uD83D\uDD04 Request: ${operation}`, {\n operation,\n params: JSON.stringify(params, null, 2)\n });\n}\n\nexport function logResponse(component: string, operation: string, response: any, duration: number): void {\n if (!debugConfig.enableRequestLogging) return;\n\n debugLog(component, `\u2705 Response: ${operation} (${duration}ms)`, {\n operation,\n duration,\n response: typeof response === 'object' ? JSON.stringify(response, null, 2) : response\n });\n}\n\nexport function logError(component: string, operation: string, error: any, duration?: number): void {\n const durationStr = duration ? ` (${duration}ms)` : '';\n debugError(component, `\u274C Error: ${operation}${durationStr}`, {\n operation,\n duration,\n error: error?.message || error?.toString() || 'Unknown error',\n stack: error?.stack\n });\n}\n\n/**\n * Network connection logger\n */\nexport function logConnectionAttempt(network: string, attempt: number, maxAttempts: number): void {\n debugInfo('CONNECTION', `\uD83D\uDD17 Connecting to ${network} (attempt ${attempt}/${maxAttempts})`);\n}\n\nexport function logConnectionSuccess(network: string, latency: number): void {\n debugInfo('CONNECTION', `\u2705 Connected to ${network} (${latency}ms)`);\n networkMetrics.recordRequest(`connection-${network}`, true, latency);\n}\n\nexport function logConnectionFailure(network: string, error: string, attempt: number): void {\n debugError('CONNECTION', `\u274C Connection failed to ${network} (attempt ${attempt})`, { error });\n networkMetrics.recordRequest(`connection-${network}`, false, 0, error);\n}\n\n/**\n * PKP operation logger\n */\nexport function logPkpOperation(operation: string, pkpId?: string, details?: any): void {\n const pkpStr = pkpId ? ` (PKP: ${pkpId.slice(0, 8)}...)` : '';\n debugInfo('PKP', `\uD83D\uDD11 ${operation}${pkpStr}`, details);\n}\n\n/**\n * Session signature logger\n */\nexport function logSessionSignatures(count: number, expiration: string): void {\n debugInfo('SESSION', `\uD83D\uDD10 Generated ${count} session signatures (expires: ${expiration})`);\n}\n\n/**\n * LIT Action execution logger\n */\nexport function logLitActionExecution(cid: string, params: any): void {\n debugInfo('LIT_ACTION', `\u26A1 Executing LIT Action: ${cid}`, {\n cid,\n params\n });\n}\n\nexport function logLitActionResult(cid: string, success: boolean, duration: number, result?: any): void {\n const status = success ? '\u2705' : '\u274C';\n debugInfo('LIT_ACTION', `${status} LIT Action completed: ${cid} (${duration}ms)`, {\n cid,\n success,\n duration,\n result: success && result ? JSON.stringify(result, null, 2) : undefined\n });\n}\n\n/**\n * Test lifecycle logger\n */\nexport function logTestStart(testName: string): PerformanceTracker {\n debugInfo('TEST', `\uD83E\uDDEA Starting test: ${testName}`);\n return new PerformanceTracker(testName);\n}\n\nexport function logTestEnd(testName: string, success: boolean, duration: number): void {\n const status = success ? '\u2705' : '\u274C';\n debugInfo('TEST', `${status} Test completed: ${testName} (${duration}ms)`);\n networkMetrics.printSummary();\n}", "/**\n * Session Signature Cache for PKP Operations\n * Provides intelligent caching of session signatures to avoid regeneration\n */\n\nimport { debugInfo, debugWarn, debugLog } from './debug-logger';\n\n/**\n * Cache entry for session signatures\n */\ninterface SessionSignatureCacheEntry {\n sessionSigs: any;\n expiration: Date;\n pkpTokenId: string;\n litActionCid: string;\n signerAddress: string;\n network: string;\n createdAt: Date;\n}\n\n/**\n * Session signature cache configuration\n */\nexport interface SessionSignatureCacheConfig {\n maxEntries: number;\n bufferTimeMs: number; // Time before expiration to consider entry stale\n enableLogging: boolean;\n}\n\nexport const DEFAULT_CACHE_CONFIG: SessionSignatureCacheConfig = {\n maxEntries: 50,\n bufferTimeMs: 60000, // 1 minute buffer before expiration\n enableLogging: true\n};\n\n/**\n * In-memory session signature cache\n */\nclass SessionSignatureCache {\n private cache = new Map<string, SessionSignatureCacheEntry>();\n private config: SessionSignatureCacheConfig;\n\n constructor(config: Partial<SessionSignatureCacheConfig> = {}) {\n this.config = { ...DEFAULT_CACHE_CONFIG, ...config };\n }\n\n /**\n * Generate cache key from PKP and context\n */\n private generateCacheKey(\n pkpTokenId: string,\n litActionCid: string,\n signerAddress: string,\n network: string\n ): string {\n return `${signerAddress}-${network}-${pkpTokenId}-${litActionCid}`;\n }\n\n /**\n * Check if cache entry is still valid\n */\n private isEntryValid(entry: SessionSignatureCacheEntry): boolean {\n const now = new Date();\n const expirationWithBuffer = new Date(\n entry.expiration.getTime() - this.config.bufferTimeMs\n );\n\n return now < expirationWithBuffer;\n }\n\n /**\n * Clean expired entries from cache\n */\n private cleanExpiredEntries(): void {\n const now = new Date();\n let cleanedCount = 0;\n\n for (const [key, entry] of this.cache.entries()) {\n if (now >= entry.expiration) {\n this.cache.delete(key);\n cleanedCount++;\n }\n }\n\n if (cleanedCount > 0 && this.config.enableLogging) {\n debugInfo('CACHE', `\uD83E\uDDF9 Cleaned ${cleanedCount} expired session signature entries`);\n }\n }\n\n /**\n * Enforce cache size limits\n */\n private enforceCacheSize(): void {\n if (this.cache.size <= this.config.maxEntries) {\n return;\n }\n\n // Sort entries by creation time and remove oldest\n const entries = Array.from(this.cache.entries())\n .sort(([, a], [, b]) => a.createdAt.getTime() - b.createdAt.getTime());\n\n const toRemove = entries.slice(0, this.cache.size - this.config.maxEntries);\n\n for (const [key] of toRemove) {\n this.cache.delete(key);\n }\n\n if (this.config.enableLogging) {\n debugInfo('CACHE', `\uD83D\uDCE6 Removed ${toRemove.length} oldest cache entries to maintain size limit`);\n }\n }\n\n /**\n * Get cached session signatures if valid\n */\n get(\n pkpTokenId: string,\n litActionCid: string,\n signerAddress: string,\n network: string\n ): any | null {\n this.cleanExpiredEntries();\n\n const cacheKey = this.generateCacheKey(pkpTokenId, litActionCid, signerAddress, network);\n const entry = this.cache.get(cacheKey);\n\n if (!entry) {\n if (this.config.enableLogging) {\n debugLog('CACHE', `\u274C Session signatures cache miss: ${cacheKey}`);\n }\n return null;\n }\n\n if (!this.isEntryValid(entry)) {\n this.cache.delete(cacheKey);\n if (this.config.enableLogging) {\n debugWarn('CACHE', `\u23F0 Session signatures expired: ${cacheKey}`);\n }\n return null;\n }\n\n if (this.config.enableLogging) {\n const timeUntilExpiry = entry.expiration.getTime() - Date.now();\n debugInfo('CACHE', `\u2705 Session signatures cache hit: ${cacheKey} (expires in ${Math.round(timeUntilExpiry/1000)}s)`);\n }\n\n return entry.sessionSigs;\n }\n\n /**\n * Cache session signatures\n */\n set(\n pkpTokenId: string,\n litActionCid: string,\n signerAddress: string,\n network: string,\n sessionSigs: any,\n expiration: Date\n ): void {\n const cacheKey = this.generateCacheKey(pkpTokenId, litActionCid, signerAddress, network);\n\n const entry: SessionSignatureCacheEntry = {\n sessionSigs,\n expiration,\n pkpTokenId,\n litActionCid,\n signerAddress,\n network,\n createdAt: new Date()\n };\n\n this.cache.set(cacheKey, entry);\n\n if (this.config.enableLogging) {\n const timeUntilExpiry = expiration.getTime() - Date.now();\n debugInfo('CACHE', `\uD83D\uDCBE Cached session signatures: ${cacheKey} (expires in ${Math.round(timeUntilExpiry/1000)}s)`);\n }\n\n this.enforceCacheSize();\n }\n\n /**\n * Clear all cached session signatures\n */\n clear(): void {\n const size = this.cache.size;\n this.cache.clear();\n\n if (this.config.enableLogging) {\n debugInfo('CACHE', `\uD83D\uDDD1\uFE0F Cleared ${size} cached session signature entries`);\n }\n }\n\n /**\n * Get cache statistics\n */\n getStats() {\n this.cleanExpiredEntries();\n\n return {\n size: this.cache.size,\n maxEntries: this.config.maxEntries,\n utilizationPercent: Math.round((this.cache.size / this.config.maxEntries) * 100)\n };\n }\n\n /**\n * Remove specific cache entry\n */\n delete(\n pkpTokenId: string,\n litActionCid: string,\n signerAddress: string,\n network: string\n ): boolean {\n const cacheKey = this.generateCacheKey(pkpTokenId, litActionCid, signerAddress, network);\n const deleted = this.cache.delete(cacheKey);\n\n if (deleted && this.config.enableLogging) {\n debugInfo('CACHE', `\uD83D\uDDD1\uFE0F Removed session signatures from cache: ${cacheKey}`);\n }\n\n return deleted;\n }\n}\n\n// Global session signature cache instance\nexport const sessionSignatureCache = new SessionSignatureCache();\n\n/**\n * Enhanced session signature generator with caching\n */\nexport async function generateSessionSignaturesWithCache(\n litNodeClient: any,\n sessionConfig: any,\n pkpTokenId: string,\n litActionCid: string,\n signerAddress: string,\n network: string = 'chipotle'\n): Promise<any> {\n // Check cache first\n const cached = sessionSignatureCache.get(pkpTokenId, litActionCid, signerAddress, network);\n if (cached) {\n return cached;\n }\n\n // Generate new session signatures\n debugInfo('CACHE', '\uD83D\uDD10 Generating new session signatures (cache miss)...');\n const sessionSigs = await litNodeClient.getSessionSigs(sessionConfig);\n\n // Extract expiration from config\n const expiration = new Date(sessionConfig.expiration);\n\n // Cache the result\n sessionSignatureCache.set(pkpTokenId, litActionCid, signerAddress, network, sessionSigs, expiration);\n\n const sigCount = Object.keys(sessionSigs).length;\n debugInfo('CACHE', `\u2705 Generated and cached ${sigCount} session signatures`);\n\n return sessionSigs;\n}\n\n/**\n * Configure the global session signature cache\n */\nexport function configureSessionSignatureCache(config: Partial<SessionSignatureCacheConfig>): void {\n Object.assign(sessionSignatureCache['config'], config);\n}\n\n/**\n * Clear the global session signature cache\n */\nexport function clearSessionSignatureCache(): void {\n sessionSignatureCache.clear();\n}\n\n/**\n * Get session signature cache statistics\n */\nexport function getSessionSignatureCacheStats() {\n return sessionSignatureCache.getStats();\n}", "/**\n * dh-lit-actions Package\n * Diamond Hands Protocol LIT Actions Registry\n *\n * This package exports deployed LIT Action CIDs and metadata\n * for consumption by the Diamond Hands SDK and other applications.\n */\n\n// Export interfaces\nexport * from \"./interfaces\";\n\n// Export constants from registry\nexport * from \"./constants/chunks/lit-actions-registry\";\n\n// Export utilities\nexport * from \"./utils\";\n\n// Export NOLA executors\nexport * from \"./executors\";\n\n/**\n * Borrower authorization EIP-712 types \u2014 the ONE definition the SDK and the\n * LIT Actions share.\n *\n * Exported from `src/` rather than re-declared here: the SDK signs these\n * messages and `modules/authorization.module.ts` verifies them, so a second\n * copy would be a second digest waiting to disagree. `tsconfig.pkg.json`\n * already compiles `src/constants/**`, and the module is plain constants with\n * no LIT-runtime dependency, so bundling it into the package costs nothing.\n *\n * Named exports, not `export *`: the sibling `message-hash-domains` module is\n * NOT re-exported, because its action tags are LIT-internal and would widen\n * this package's public surface for no consumer.\n */\nexport {\n type BorrowerAuthorizationField,\n type BorrowerAuthorizationDomain,\n type BorrowerAuthorizationPrimaryType,\n BORROWER_AUTHORIZATION_PRIMARY_TYPES,\n BORROWER_AUTHORIZATION_FIELDS,\n BORROWER_AUTHORIZATION_ENCODE_TYPES,\n borrowerAuthorizationTypes,\n buildBorrowerAuthorizationDomain,\n} from \"../src/constants/borrower-authorization-types\";\n\n/**\n * EIP-712 types for the BTC-custody owner authorizations (execute and\n * invalidate; `contracts/docs/EIP712_DOMAIN_SPEC.md` \u00A73.8). Same named-export\n * rule as above.\n */\nexport {\n type BtcSpendRequestField,\n type BtcSpendRequestDomain,\n type BtcSpendRequestPrimaryType,\n BTC_SPEND_REQUEST_PRIMARY_TYPES,\n BTC_SPEND_REQUEST_FIELDS,\n BTC_SPEND_REQUEST_ENCODE_TYPES,\n btcSpendRequestTypes,\n buildBtcSpendRequestDomain,\n canonicalBtcTxid,\n} from \"../src/constants/btc-spend-request-types\";\n\n// Default export\nexport { DH_LIT_ACTIONS_CHIPOTLE, CHIPOTLE_DEPLOYMENTS } from \"./constants/chunks/lit-actions-registry\";\n", "// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n const BASE_MAP = new Uint8Array(256)\n for (let j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (let i = 0; i < ALPHABET.length; i++) {\n const x = ALPHABET.charAt(i)\n const xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n const BASE = ALPHABET.length\n const LEADER = ALPHABET.charAt(0)\n const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n // eslint-disable-next-line no-empty\n if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n let zeroes = 0\n let length = 0\n let pbegin = 0\n const pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n const b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n let carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n let i = 0\n for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n let it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n let str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n let psz = 0\n // Skip and count leading '1's.\n let zeroes = 0\n let length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n const b256 = new Uint8Array(size)\n // Process the characters.\n while (psz < source.length) {\n // Find code of next character\n const charCode = source.charCodeAt(psz)\n // Base map can not be indexed using char code\n if (charCode > 255) { return }\n // Decode character\n let carry = BASE_MAP[charCode]\n // Invalid character\n if (carry === 255) { return }\n let i = 0\n for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n let it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n const vch = new Uint8Array(zeroes + (size - it4))\n let j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n const buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode,\n decodeUnsafe,\n decode\n }\n}\nexport default base\n", "import basex from 'base-x';\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';\nexport default basex(ALPHABET);\n", "import bs58 from \"bs58\";\n\n/**\n * Convert IPFS CID from base58 to hex format for contract authorization\n * This matches the format expected by LIT Protocol smart contracts\n */\nexport function cidToHex(cid: string): string {\n try {\n if (cid.startsWith(\"Qm\")) {\n // v0 CID - convert base58 to hex\n const bytes = bs58.decode(cid);\n return \"0x\" + Buffer.from(bytes).toString(\"hex\");\n } else if (cid.startsWith(\"0x\")) {\n // Already in hex format\n return cid;\n } else {\n // Unknown format - FAIL FAST\n throw new Error(`Unsupported CID format: ${cid}. Only CIDv0 (Qm...) and hex (0x...) formats are supported.`);\n }\n } catch (error) {\n if (error instanceof Error && error.message.includes('Unsupported CID format')) {\n // Re-throw our own errors\n throw error;\n }\n // bs58 decode or other conversion errors\n throw new Error(`Failed to convert CID ${cid} to hex: ${error instanceof Error ? error.message : String(error)}`);\n }\n}\n", "import { DiamondHandsLitActions } from \"../../interfaces\";\nimport { cidToHex } from \"../../utils/chunks/cid-utils\";\n\nexport type SupportedLitNetwork = \"chipotle\";\n\n/**\n * Diamond Hands LIT Actions Registry \u2014 Chipotle (new REST API)\n * Contains all deployed LIT Actions with their IPFS CIDs and PKP metadata\n */\nexport const DH_LIT_ACTIONS_CHIPOTLE: Partial<DiamondHandsLitActions> = {\n authorizationDummy: {\n cid: \"QmeeYQ3zfDPKJQg3JG5p4TpxKHEnDRLXZbT79KxzwC3xjc\",\n authorizedCidHex: cidToHex(\n \"QmeeYQ3zfDPKJQg3JG5p4TpxKHEnDRLXZbT79KxzwC3xjc\",\n ),\n name: \"Authorization Dummy\",\n description: \"Production Authorization Dummy\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1780400482915,\n size: 2216,\n hash: \"5f862b4635f2e04b033c4ff652addc017c3c0a325f81309a24d701c90e0bc950\",\n },\n authorizationDummyB: {\n cid: \"QmQHKDp5GDBp2XoStcm3SE6EvdJpK5RJ5ij4ZkQFn6dcMU\",\n authorizedCidHex: cidToHex(\n \"QmQHKDp5GDBp2XoStcm3SE6EvdJpK5RJ5ij4ZkQFn6dcMU\",\n ),\n name: \"Authorization Dummy B\",\n description: \"Production Authorization Dummy B\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1780400494581,\n size: 1885,\n hash: \"d6eb8665fa4f1fe19b6a2bc81fbf729af68a1daf30117f40e37705381978a7ce\",\n },\n pkpValidator: {\n cid: \"QmRfPvd7R7MoEnShds28Y4ovdV8RoDCGkYWTcF1JHZVTQa\",\n authorizedCidHex: cidToHex(\n \"QmRfPvd7R7MoEnShds28Y4ovdV8RoDCGkYWTcF1JHZVTQa\",\n ),\n name: \"Pkp Validator\",\n description: \"Production Pkp Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1784569687492,\n size: 4140,\n hash: \"4c0d65bf1f33cdac22a78fd8c4764319cc3fe00650e0fe7fa8a6090d9a318a7b\",\n validatorWalletAddress: \"0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c\",\n pkp: {\n publicKey:\n \"0x04ec0e3acc40884e3f366ca469d08899eb640ad5259fa196b0238075086208a9f8732a3175704f35f0bcc28e07406cfb24c254efd1e7355640577330f0d2dd755f\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n btcTransactionSigner: {\n cid: \"QmUR2dSs4H6ajpk577PiDYA2cW6pucrEufWCrxhoKBajxi\",\n authorizedCidHex: cidToHex(\n \"QmUR2dSs4H6ajpk577PiDYA2cW6pucrEufWCrxhoKBajxi\",\n ),\n name: \"Btc Transaction Signer\",\n description: \"Production Btc Transaction Signer\",\n version: \"1.3.2\",\n deployed: true,\n deployedAt: 1793188476723,\n size: 78341,\n hash: \"a8ebd6426c4e34c0d67457ce7e6b682ebb6619f75067a3a1895f6028a4fede34\",\n },\n ucdMintValidator: {\n cid: \"QmXr4PBqadVon2HrkmSrHwdXGvx1kaNNdVJGqBZ5wjmYFw\",\n authorizedCidHex: cidToHex(\n \"QmXr4PBqadVon2HrkmSrHwdXGvx1kaNNdVJGqBZ5wjmYFw\",\n ),\n name: \"Ucd Mint Validator\",\n description: \"Production Ucd Mint Validator\",\n version: \"1.4.5\",\n deployed: true,\n deployedAt: 1793188485424,\n size: 92150,\n hash: \"91b74714f71acf01875ffb81b829ada1fe0a3b3a94d3ad9cd6ea37c17a2c6193\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x041ab17cd91fc5c0b761eea6092d032807561b621b82c488826776e04a9158d61ba64d809a4729f0501289d980732cb06d8dfd06999dd9c8efd2f495dad78b31bb\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n processPaymentValidator: {\n cid: \"QmcJcjahQStMB4Ggy5d47HoCG1X2HUFcRfMRbcU33Pc4bz\",\n authorizedCidHex: cidToHex(\n \"QmcJcjahQStMB4Ggy5d47HoCG1X2HUFcRfMRbcU33Pc4bz\",\n ),\n name: \"Process Payment Validator\",\n description: \"Production Process Payment Validator\",\n version: \"1.3.5\",\n deployed: true,\n deployedAt: 1793188494032,\n size: 87803,\n hash: \"7e6989fc31fdb53d343ac6a5372844d7b58ada2ded780c5d01ffa5e2163cba6c\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x04cfccb9b6c7addc79469c0e9fafebef4c70801302c62cdb26b610723a9b8527d23f98a40158c7340d83fd0e62d02b5ec74c12f7a86d98e8c6973b4811110f19ad\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n extendPositionValidator: {\n cid: \"QmTS9C7UjAEi1JvZu5tQHy7McRUmverXyw8v8gNjidroSg\",\n authorizedCidHex: cidToHex(\n \"QmTS9C7UjAEi1JvZu5tQHy7McRUmverXyw8v8gNjidroSg\",\n ),\n name: \"Extend Position Validator\",\n description: \"Production Extend Position Validator\",\n version: \"1.3.5\",\n deployed: true,\n deployedAt: 1793188503339,\n size: 85079,\n hash: \"384a232d8ec6605ce5404ea0737931f102dc2740b1c6dbf3230940e6159b1ca2\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x04e52338f6a0c3362800f1a94c4c8f08be5030dde0fa217388c53d1c1a4790f4443c9f2886b2d2d8f4b75a9a156e9b028011b1a1cf7648da0e556aa980ec692836\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n btcWithdrawal: {\n cid: \"QmPeTMPk8j4pYSrDPKwjUUUNXUWA4uxn2X4CKUGDMYJnFx\",\n authorizedCidHex: cidToHex(\n \"QmPeTMPk8j4pYSrDPKwjUUUNXUWA4uxn2X4CKUGDMYJnFx\",\n ),\n name: \"Btc Withdrawal\",\n description: \"Production Btc Withdrawal\",\n version: \"1.3.5\",\n deployed: true,\n deployedAt: 1793188512221,\n size: 103479,\n hash: \"1cb77be2c3999f45d609d50ec1dcd262770c01b19c4d911f4a0698a3f400e3c6\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n liquidationValidator: {\n cid: \"QmfPdvyBjKCffCmpSPg19mReBUTV7jbLyvavBNh4TrDiuA\",\n authorizedCidHex: cidToHex(\n \"QmfPdvyBjKCffCmpSPg19mReBUTV7jbLyvavBNh4TrDiuA\",\n ),\n name: \"Liquidation Validator\",\n description: \"Production Liquidation Validator\",\n version: \"1.3.5\",\n deployed: true,\n deployedAt: 1793188520927,\n size: 72776,\n hash: \"6ab50f3087181fe61a02c515a738835f76492a3557995982b5e5642150e8e391\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x041a241de58976c13e3d7ca5a18e494f7330151e3818706135d50176e78ffb673e58b11f0b67a87c73fade6c6b27d6e7a7377ea9f4c10bf31880f1d725f18cc6f8\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n priceOracle: {\n cid: \"QmZwH2JzXpLPdtUiM52PLyfuCGphz82CCs54Y6fCbzxpri\",\n authorizedCidHex: cidToHex(\n \"QmZwH2JzXpLPdtUiM52PLyfuCGphz82CCs54Y6fCbzxpri\",\n ),\n name: \"Price Oracle\",\n description: \"Production Price Oracle (Chipotle main+getPrivateKey)\",\n version: \"1.1.0\",\n deployed: true,\n deployedAt: 1781116663270,\n size: 8695,\n hash: \"ba20ade60a7fa5acd80dadfafa179c507388cfe6ce48a22a672d70b317ffcc74\",\n validatorWalletAddress: \"0xefb258d455a31d061bbeb3de3d2143bdfcb67a6c\",\n pkp: {\n publicKey:\n \"0x043beaa1da47875601a8d6f430b1438ee2d4732eefd06e5c63a474bbdaf9e7df1797b1b951e041b627c2bf839788164825324c9cbd1e2d6f740fdd4bff69b1900b\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n loanVaultBtcBalance: {\n cid: \"QmZJQ5yKXkPc6azGg6AhXe4cyTmd617m12VMLao6KtL38T\",\n authorizedCidHex: cidToHex(\n \"QmZJQ5yKXkPc6azGg6AhXe4cyTmd617m12VMLao6KtL38T\",\n ),\n name: \"Loan Vault Btc Balance\",\n description: \"Production Loan Vault Btc Balance\",\n version: \"1.3.5\",\n deployed: true,\n deployedAt: 1793188529377,\n size: 62511,\n hash: \"225ea242dfbf74a2cd15ef83da4ecd63f0284e101f4a5182afeab731dca588d6\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n // btc-address-balance (Option B) \u2014 address-only signed total balance via\n // BitcoinProviderRegistry consensus (no positionId, no price). The deploy\n // step (deploy:chipotle:action) fills cid/authorizedCidHex/deployedAt/size/\n // hash + a DEDICATED validatorWalletAddress + pkp and flips deployed:true.\n // Requires BitcoinProviderRegistry.addAllowedCid(chainId, keccak256(utf8(cid)))\n // on each target chain (the action decrypts registry slots). No OAR entry.\n btcAddressBalance: {\n cid: \"QmbwCiwE3KjK8LZ8uML9HMjibbNtGonQGvueDEGq7NSZix\",\n authorizedCidHex: cidToHex(\n \"QmbwCiwE3KjK8LZ8uML9HMjibbNtGonQGvueDEGq7NSZix\",\n ),\n name: \"Btc Address Balance\",\n description: \"Address-only signed total BTC balance via registry consensus (no positionId, no price)\",\n version: \"0.3.3\",\n deployed: true,\n deployedAt: 1793188537801,\n size: 32072,\n hash: \"bdd1356d959916d427094b77877c6337477ae84d6a7a54e600b93e66c01b5ae5\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x0498cbb31facfa26e3ec83ccdabfe4fe341ca0282e0c3cb81da7113723b9726e1e49efa92165cc3faa66ced4454cea56dbab12267852d6525a55d7c4f128b912cd\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n alwaysSigner: {\n cid: \"Qmbf27pDimUe5GAdTYYd7poV7rHqUgctxtWd7HTui3Amig\",\n authorizedCidHex: cidToHex(\n \"Qmbf27pDimUe5GAdTYYd7poV7rHqUgctxtWd7HTui3Amig\",\n ),\n name: \"Always Signer\",\n description: \"Production Always Signer\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1780400578692,\n size: 4333,\n hash: \"1a7101c026a638f2f7cbdce02c6b8b0a55e44cc5cfc7e9440fe029b5c5be693e\",\n },\n\n ethersVersionProbe: {\n cid: \"QmYEfBWgTYc1pPH6vqazNGfnShfMKCVeiwcXGrWgehqK5A\",\n authorizedCidHex: cidToHex(\n \"QmYEfBWgTYc1pPH6vqazNGfnShfMKCVeiwcXGrWgehqK5A\",\n ),\n name: \"Ethers Version Probe\",\n description: \"Diagnostic: reports which ethers version the Chipotle runtime injects\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1778509493396,\n size: 1046,\n hash: \"03ee5be239c91c735d2c95db89a0d1b77e602cfc18af8eb64b3281fddcd90a72\",\n },\n agentModuleExecutor: {\n cid: \"QmPTQm5CtKnN3PLAitDRNQCuAeegATMWVWQbRrKiMCTz6V\",\n authorizedCidHex: cidToHex(\n \"QmPTQm5CtKnN3PLAitDRNQCuAeegATMWVWQbRrKiMCTz6V\",\n ),\n name: \"Agent Module Executor\",\n description: \"Production Agent Module Executor\",\n version: \"1.3.0\",\n deployed: true,\n deployedAt: 1792419196606,\n size: 17562,\n hash: \"a10d463ffd48f2392401efe3dde566faa1869e5e089db830632873a5b9528ee0\",\n },\n\n staleSpendRecoveryValidator: {\n cid: \"QmRxk2qJL64wy1wgJynR3aL9hzTXdPBBw8ZZK177EdVHp4\",\n authorizedCidHex: cidToHex(\n \"QmRxk2qJL64wy1wgJynR3aL9hzTXdPBBw8ZZK177EdVHp4\",\n ),\n name: \"Stale Spend Recovery Validator\",\n description: \"Production Stale Spend Recovery Validator\",\n version: \"1.2.4\",\n deployed: true,\n deployedAt: 1793188544264,\n size: 50029,\n hash: \"6d68c574bf1af2bcb0c4afb51fdd9151f920827b81477ab762eec08332c77de3\",\n validatorWalletAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n pkp: {\n publicKey:\n \"0x046da0ad6da7dd4a0063cbeac6f2bdb6a9889c2178b23470833356a8ee5630f7f0eee0db348d9d9aaaadd23eccf0063c8f68ee5e446abe30b882bf1de4c932bc21\",\n ethAddress: \"0xEfb258D455a31d061Bbeb3DE3D2143BdFCB67a6C\",\n },\n },\n\n btcUtxoInvalidator: {\n cid: \"QmSGjgPuNgw2EB6yLZ9PmDtKWCCC6ELyUZie5ksSm8dE5E\",\n authorizedCidHex: cidToHex(\n \"QmSGjgPuNgw2EB6yLZ9PmDtKWCCC6ELyUZie5ksSm8dE5E\",\n ),\n name: \"Btc Utxo Invalidator\",\n description: \"Production Btc Utxo Invalidator\",\n version: \"1.2.2\",\n deployed: true,\n deployedAt: 1793188552704,\n size: 73530,\n hash: \"d58b17d36cd133b353ce79d3c6caca57989a5a3ab15e8256f297013aaa34d5b3\",\n },\n\n // 1.2.1 (audit 2026-11-14, H-3): pinned and attached to the Sepolia carry group (8) on 2026-11-15.\n // The 1.2.0 CID QmbGLm5rivPBLeGTuiWyCLAio4WHt8XnmMGxxY3fuEEsxs signs the LIVE vault's domain for `chain: \"hardhat\"`:\n // it is STILL in group 8 while the api keeper runs it, and MUST be removed from the group as soon as the api is\n // deployed on this CID (tasks/todo.md, H-3 step 4 (a)).\n carryCollateralAttestation: {\n cid: \"QmbA5KafuYExTmKwPXKKGDVUGS5WwZedM3onLnbgni5ftj\",\n authorizedCidHex: cidToHex(\n \"QmbA5KafuYExTmKwPXKKGDVUGS5WwZedM3onLnbgni5ftj\",\n ),\n name: \"Carry Collateral Attestation\",\n description: \"LoanCarryVault collateral attestation (borrower, BTC vault, confirmed BTC)\",\n version: \"1.2.1\",\n deployed: true,\n deployedAt: 1794763884081,\n size: 26364,\n hash: \"d8ed063ef94a2545db53f3f704a6da3d076f51b871e4db007d4388964acffdc7\",\n },\n\n backingAttestation: {\n cid: \"QmRkWKprbhP865uALCjfp8gC34JJtZZuD5UFZxqB2jJ8Hi\",\n authorizedCidHex: cidToHex(\n \"QmRkWKprbhP865uALCjfp8gC34JJtZZuD5UFZxqB2jJ8Hi\",\n ),\n name: \"Backing Attestation\",\n description: \"BackingOracle report: BTC collateral over loan UCD at a pinned block, from a keeper snapshot the action verifies\",\n version: \"1.0.2\",\n deployed: true,\n deployedAt: 1793955517792,\n size: 20733,\n hash: \"9b87800369aa37b12496cfaf8247e5e52eb82ad292519e75e799274046cf214a\",\n },\n\n // Carry capital lock plan, Step 4: its own wallet in the Sepolia carry group (8), registered in OAR for the\n // makePaymentFrom selector. 1.0.1 (audit 2026-11-14: the RPC must report the policy chain) pinned and attached to\n // group 8 on 2026-11-15; the wallet is unchanged, so the OAR entry is too. The 1.0.0 CID\n // QmR26eenFKZhcSfNSoVn9vAQviTPF1d9t6oyvaamHTScjJ leaves the group once the api is deployed on this one.\n carryRepayValidator: {\n cid: \"QmbP4SVceKXxnFcHFsM5bc11us9RirDE639EQxYcHPAKro\",\n authorizedCidHex: cidToHex(\n \"QmbP4SVceKXxnFcHFsM5bc11us9RirDE639EQxYcHPAKro\",\n ),\n name: \"Carry Repay Validator\",\n description: \"Signs PayerPayment for PositionManager.makePaymentFrom: the carry receiver repays min(credit, debt)\",\n version: \"1.0.1\",\n deployed: true,\n deployedAt: 1794763929053,\n size: 34667,\n hash: \"1ed1a999238f5475963cb809c330f6fdb4f4a14305c1ae75a2b8e52341dfc8b3\",\n validatorWalletAddress: \"0x3bddbef92170443f833f03d9f6c87897b19de61c\",\n pkp: {\n publicKey:\n \"0x04ac62b109938e372dd628258da5f2ed128d4f737193349e289529fac2714f98c6acdc7703e4a96377ccda76f5e4e0d40dcc10cb13d539ed81ec3af57709dde784\",\n ethAddress: \"0x3BDdBEf92170443F833F03D9F6c87897b19de61C\",\n },\n },\n};\n\nexport function getDeploymentsForNetwork(\n network: SupportedLitNetwork,\n): Partial<DiamondHandsLitActions> {\n if (network === \"chipotle\") return DH_LIT_ACTIONS_CHIPOTLE;\n throw new Error(`Unsupported LIT network: ${network}`);\n}\n\nexport const CHIPOTLE_DEPLOYMENTS = DH_LIT_ACTIONS_CHIPOTLE;\n", "import { LitActionConfig, LitActionName } from \"../../interfaces\";\nimport {\n getDeploymentsForNetwork,\n SupportedLitNetwork,\n} from \"../../constants/chunks/lit-actions-registry\";\n\n/**\n * Get LIT Action CID by name\n * @param actionName - Name of the LIT Action\n * @returns IPFS CID of the deployed action\n * @throws Error if action is not deployed\n */\nexport function getLitActionCID(\n litNetwork: SupportedLitNetwork = \"chipotle\",\n actionName: LitActionName,\n): string {\n const deployments = getDeploymentsForNetwork(litNetwork);\n const action = deployments[actionName];\n\n if (!action || !action.deployed || !action.cid) {\n throw new Error(\n `LIT Action '${actionName}' not deployed on network '${litNetwork}'. Check deployment status.`,\n );\n }\n return action.cid;\n}\n\n/**\n * Get LIT Action configuration by name\n * @param actionName - Name of the LIT Action\n * @returns Complete LIT Action configuration\n */\nexport function getLitActionConfig(\n actionName: LitActionName,\n litNetwork: SupportedLitNetwork = \"chipotle\",\n): LitActionConfig {\n const deployments = getDeploymentsForNetwork(litNetwork);\n const action = deployments[actionName];\n if (!action) {\n throw new Error(\n `LIT Action '${actionName}' not found in registry for network '${litNetwork}'.`,\n );\n }\n return action;\n}\n\n/**\n * Check if a LIT Action is deployed and ready to use\n * @param actionName - Name of the LIT Action\n * @returns True if deployed, false otherwise\n */\nexport function isLitActionDeployed(\n actionName: LitActionName,\n litNetwork: SupportedLitNetwork = \"chipotle\",\n): boolean {\n const deployments = getDeploymentsForNetwork(litNetwork);\n const action = deployments[actionName];\n return !!(action && action.deployed && action.cid);\n}\n\n/**\n * Validate that all required actions are deployed\n * @param requiredActions - Array of required action names\n * @returns True if all actions are deployed\n */\nexport function validateDeployedActions(\n requiredActions: LitActionName[],\n litNetwork: SupportedLitNetwork = \"chipotle\",\n): boolean {\n return requiredActions.every((actionName) =>\n isLitActionDeployed(actionName, litNetwork),\n );\n}\n\n/**\n * Get all deployed LIT Actions\n * @returns Array of deployed LIT Action configurations\n */\nexport function getDeployedActions(\n litNetwork: SupportedLitNetwork = \"chipotle\",\n): LitActionConfig[] {\n const deployments = getDeploymentsForNetwork(litNetwork);\n return Object.values(deployments).filter(\n (action) => action && action.deployed,\n );\n}\n", "import {\n getDeploymentsForNetwork,\n SupportedLitNetwork,\n} from \"../../constants/chunks/lit-actions-registry\";\n/**\n * Get the complete setup for PKP Validator testing\n * Returns both the LIT Action config and its associated PKP\n */\nexport function getPKPValidatorSetup(\n litNetwork: SupportedLitNetwork = \"chipotle\"\n) {\n const deployments = getDeploymentsForNetwork(litNetwork);\n const litAction = deployments.pkpValidator;\n\n if (!litAction || !litAction.pkp) {\n throw new Error(\n `PKP validator setup is not available for litNetwork='${litNetwork}'. ` +\n `Ensure the pkpValidator action (with pkp attached) is defined in the registry.`\n );\n }\n\n return {\n litAction,\n pkp: litAction.pkp!,\n };\n}\n", "/**\n * LIT Protocol Connection Helpers\n * Provides retry logic, error handling, and connection validation utilities\n * for robust LIT Protocol operations\n */\n\nimport {\n debugInfo,\n debugWarn,\n debugError,\n logConnectionAttempt,\n logConnectionSuccess,\n logConnectionFailure,\n logRequest,\n logResponse,\n logError,\n logPkpOperation,\n logLitActionExecution,\n logLitActionResult,\n networkMetrics,\n PerformanceTracker\n} from './debug-logger';\nimport {\n classifyError,\n getRetryConfigFromClassification,\n createErrorReport,\n litProtocolErrors\n} from './error-classification';\n\n/**\n * Retry configuration options\n */\nexport interface RetryConfig {\n maxAttempts: number;\n initialDelayMs: number;\n maxDelayMs: number;\n backoffMultiplier: number;\n retryableErrors: string[];\n}\n\n/**\n * Default retry configuration optimized for LIT Protocol operations\n */\nexport const DEFAULT_RETRY_CONFIG: RetryConfig = {\n maxAttempts: 5, // Increased from 3 for PKP operations\n initialDelayMs: 2000, // Increased from 1000ms for PKP operations\n maxDelayMs: 60000, // Increased from 30000ms for PKP operations\n backoffMultiplier: 2,\n retryableErrors: [\n 'request_timeout',\n 'network error',\n 'connection failed',\n 'ENOTFOUND',\n 'ECONNREFUSED',\n 'ETIMEDOUT',\n 'socket hang up',\n 'timeout',\n // PKP-specific errors\n 'signing shares',\n 'There was an error getting the signing shares',\n 'PKP validation',\n 'pkp validation failed',\n 'resource validation',\n 'ipfs propagation',\n 'session.*expired',\n 'NodeError',\n 'Response from the nodes',\n 'consensus',\n 'threshold'\n ]\n};\n\n/**\n * Connection validation result\n */\nexport interface ConnectionValidationResult {\n isValid: boolean;\n error?: string;\n latencyMs?: number;\n}\n\n/**\n * Sleep utility for retry delays\n */\nexport function sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n}\n\n/**\n * Check if an error is retryable using enhanced classification system\n */\nexport function isRetryableError(error: any, retryableErrors: string[] = DEFAULT_RETRY_CONFIG.retryableErrors): boolean {\n if (!error) return false;\n\n // Use enhanced error classification for LIT Protocol specific errors\n const classification = classifyError(error);\n\n // If classification determined retryability, use that\n if (classification.isRetryable !== undefined) {\n debugInfo('ERROR_CLASSIFICATION', `Error classified as: ${classification.category} (retryable: ${classification.isRetryable})`);\n return classification.isRetryable;\n }\n\n // Fallback to legacy pattern matching\n const errorMessage = error.message || error.toString() || '';\n const errorLower = errorMessage.toLowerCase();\n\n return retryableErrors.some(pattern =>\n errorLower.includes(pattern.toLowerCase())\n );\n}\n\n/**\n * Calculate exponential backoff delay with jitter\n */\nexport function calculateDelay(attempt: number, config: RetryConfig): number {\n const exponentialDelay = Math.min(\n config.initialDelayMs * Math.pow(config.backoffMultiplier, attempt - 1),\n config.maxDelayMs\n );\n\n // Add jitter (\u00B125%) to avoid thundering herd\n const jitter = exponentialDelay * 0.25 * (Math.random() - 0.5);\n return Math.max(100, exponentialDelay + jitter);\n}\n\n/**\n * Enhanced retry wrapper with intelligent error classification\n */\nexport async function withRetry<T>(\n operation: () => Promise<T>,\n config: Partial<RetryConfig> = {},\n operationName: string = 'operation'\n): Promise<T> {\n let finalConfig = { ...DEFAULT_RETRY_CONFIG, ...config };\n const tracker = new PerformanceTracker(`Retry ${operationName}`);\n let lastError: any;\n let errorClassification: any = null;\n\n for (let attempt = 1; attempt <= finalConfig.maxAttempts; attempt++) {\n try {\n debugInfo('RETRY', `\uD83D\uDD04 [${operationName}] Attempt ${attempt}/${finalConfig.maxAttempts}`);\n const startTime = Date.now();\n const result = await operation();\n const duration = Date.now() - startTime;\n\n debugInfo('RETRY', `\u2705 [${operationName}] Success after ${duration}ms (attempt ${attempt})`);\n networkMetrics.recordRequest(operationName, true, duration);\n tracker.end(true);\n return result;\n } catch (error) {\n lastError = error;\n const errorMessage = (error as any)?.message || (error as any)?.toString() || 'Unknown error';\n\n // Classify error and potentially adjust retry strategy\n errorClassification = classifyError(error);\n\n // Update config with intelligent retry settings if this is the first error\n if (attempt === 1 && errorClassification) {\n const intelligentConfig = getRetryConfigFromClassification(errorClassification);\n finalConfig = {\n ...finalConfig,\n ...intelligentConfig,\n maxAttempts: Math.min(finalConfig.maxAttempts, intelligentConfig.maxAttempts)\n };\n\n debugInfo('RETRY', `\uD83E\uDDE0 Intelligent retry strategy applied: ${errorClassification.category} (${errorClassification.retryStrategy})`);\n debugInfo('RETRY', `\uD83D\uDCCA Adjusted config: max=${finalConfig.maxAttempts}, delay=${finalConfig.initialDelayMs}ms`);\n }\n\n debugWarn('RETRY', `\u26A0\uFE0F [${operationName}] Attempt ${attempt} failed:`, {\n error: errorMessage,\n attempt,\n category: errorClassification.category,\n retryable: errorClassification.isRetryable\n });\n networkMetrics.recordRequest(operationName, false, 0, errorMessage);\n\n // Check if we've exceeded the (possibly adjusted) max attempts\n if (attempt >= finalConfig.maxAttempts) {\n debugError('RETRY', `\u274C [${operationName}] All attempts failed. Last error:`, { error: errorMessage });\n\n // Generate detailed error report\n if (errorClassification) {\n const errorReport = createErrorReport(error);\n debugError('RETRY', `\uD83D\uDCCB Error Analysis Report:\\n${errorReport}`);\n }\n\n tracker.end(false);\n break;\n }\n\n if (!errorClassification.isRetryable) {\n debugError('RETRY', `\uD83D\uDEAB [${operationName}] Non-retryable error (${errorClassification.category}):`, { error: errorMessage });\n\n // Show troubleshooting tips for non-retryable errors\n if (errorClassification.troubleshooting) {\n debugInfo('RETRY', `\uD83D\uDCA1 Troubleshooting suggestions:\\n ${errorClassification.troubleshooting.join('\\n ')}`);\n }\n\n tracker.end(false);\n break;\n }\n\n const delayMs = calculateDelay(attempt, finalConfig);\n debugInfo('RETRY', `\u23F3 [${operationName}] Waiting ${delayMs}ms before retry... (${errorClassification.retryStrategy} strategy)`);\n await sleep(delayMs);\n }\n }\n\n throw lastError;\n}\n\n/**\n * Enhanced LIT Node Client connector with retry logic and readiness validation\n */\nexport async function connectLitNodeClient(\n litNodeClient: any,\n config: Partial<RetryConfig> = {}\n): Promise<void> {\n const network = litNodeClient?.config?.litNetwork || 'unknown';\n\n return withRetry(\n async () => {\n if (!litNodeClient) {\n throw new Error('LIT Node Client is null or undefined');\n }\n\n const startTime = Date.now();\n logConnectionAttempt(network, 1, config.maxAttempts || DEFAULT_RETRY_CONFIG.maxAttempts);\n\n // First connect to the network\n await litNodeClient.connect();\n\n // Wait for client to be ready\n debugInfo('CONNECTION', `\u23F3 Waiting for LIT Node Client to be ready...`);\n const readyTimeout = 30000; // 30 seconds timeout for readiness\n const readyStartTime = Date.now();\n\n while (!litNodeClient.ready && (Date.now() - readyStartTime) < readyTimeout) {\n await sleep(500); // Check every 500ms\n }\n\n if (!litNodeClient.ready) {\n throw new Error(`LIT Node Client failed to become ready within ${readyTimeout}ms`);\n }\n\n const latency = Date.now() - startTime;\n debugInfo('CONNECTION', `\u2705 LIT Node Client is ready (${litNodeClient.ready})`);\n logConnectionSuccess(network, latency);\n },\n config,\n 'LIT Node Client Connection'\n );\n}\n\n/**\n * Enhanced LIT Contracts connector with retry logic\n */\nexport async function connectLitContracts(\n litContracts: any,\n config: Partial<RetryConfig> = {}\n): Promise<void> {\n return withRetry(\n async () => {\n if (!litContracts) {\n throw new Error('LIT Contracts is null or undefined');\n }\n\n console.log(`\uD83D\uDD17 Connecting to LIT Contracts: ${litContracts.network || 'unknown'}`);\n await litContracts.connect();\n console.log('\u2705 LIT Contracts connected successfully');\n },\n config,\n 'LIT Contracts Connection'\n );\n}\n\n/**\n * Validate LIT Node Client connection health\n */\nexport async function validateLitNodeConnection(litNodeClient: any): Promise<ConnectionValidationResult> {\n try {\n const startTime = Date.now();\n\n if (!litNodeClient) {\n return { isValid: false, error: 'LIT Node Client is null or undefined' };\n }\n\n // Try to get the latest block hash as a health check\n await litNodeClient.getLatestBlockhash();\n\n const latencyMs = Date.now() - startTime;\n return { isValid: true, latencyMs };\n } catch (error) {\n return {\n isValid: false,\n error: (error as any)?.message || (error as any)?.toString() || 'Unknown validation error'\n };\n }\n}\n\n/**\n * Enhanced session signature generator with retry logic and caching\n */\nexport async function generateSessionSignatures(\n litNodeClient: any,\n sessionConfig: any,\n config: Partial<RetryConfig> = {},\n pkpTokenId?: string,\n litActionCid?: string,\n signerAddress?: string,\n network: string = 'chipotle'\n): Promise<any> {\n // If caching parameters are provided, try cache first\n if (pkpTokenId && litActionCid && signerAddress) {\n const { sessionSignatureCache } = await import('./session-signature-cache');\n\n const cached = sessionSignatureCache.get(pkpTokenId, litActionCid, signerAddress, network);\n if (cached) {\n const sigCount = Object.keys(cached).length;\n debugInfo('SESSION', `\uD83D\uDD04 Using cached session signatures (${sigCount} sigs)`);\n return cached;\n }\n }\n\n return withRetry(\n async () => {\n debugInfo('SESSION', '\uD83D\uDD10 Generating new session signatures...');\n const sessionSigs = await litNodeClient.getSessionSigs(sessionConfig);\n const sigCount = Object.keys(sessionSigs).length;\n\n // Cache if parameters provided\n if (pkpTokenId && litActionCid && signerAddress) {\n const { sessionSignatureCache } = await import('./session-signature-cache');\n const expiration = new Date(sessionConfig.expiration);\n sessionSignatureCache.set(pkpTokenId, litActionCid, signerAddress, network, sessionSigs, expiration);\n }\n\n debugInfo('SESSION', `\u2705 Generated ${sigCount} session signatures`);\n return sessionSigs;\n },\n config,\n 'Session Signature Generation'\n );\n}\n\n/**\n * Validate LIT Node Client readiness before operations\n */\nexport async function validateLitNodeReadiness(litNodeClient: any): Promise<void> {\n if (!litNodeClient) {\n throw new Error('LIT Node Client is null or undefined');\n }\n\n // Check if client is connected\n if (!litNodeClient.ready) {\n debugWarn('CONNECTION', '\u26A0\uFE0F LIT Node Client not ready, attempting to reconnect...');\n await litNodeClient.connect();\n\n // Wait for readiness with timeout\n const readyTimeout = 15000; // 15 seconds\n const startTime = Date.now();\n\n while (!litNodeClient.ready && (Date.now() - startTime) < readyTimeout) {\n await sleep(500);\n }\n\n if (!litNodeClient.ready) {\n throw new Error('LIT Node Client is not ready for operations');\n }\n }\n\n debugInfo('CONNECTION', '\u2705 LIT Node Client readiness validated');\n}\n\n/**\n * Enhanced LIT Action executor with retry logic and readiness validation\n */\nexport async function executeLitAction(\n litNodeClient: any,\n executionConfig: any,\n config: Partial<RetryConfig> = {}\n): Promise<any> {\n const cid = executionConfig.ipfsId;\n\n return withRetry(\n async () => {\n const startTime = Date.now();\n\n // Validate client readiness before execution\n await validateLitNodeReadiness(litNodeClient);\n\n logLitActionExecution(cid, executionConfig.jsParams);\n logRequest('LIT_ACTION', 'executeJs', executionConfig);\n\n const result = await litNodeClient.executeJs(executionConfig);\n const duration = Date.now() - startTime;\n\n if (!result.response) {\n logError('LIT_ACTION', 'executeJs', new Error('No response from LIT Action'), duration);\n throw new Error('No response from LIT Action');\n }\n\n logResponse('LIT_ACTION', 'executeJs', result, duration);\n logLitActionResult(cid, true, duration, result);\n return result;\n },\n config,\n 'LIT Action Execution'\n );\n}\n\n/**\n * PKP operation wrapper with enhanced error handling\n */\nexport async function executePkpOperation<T>(\n operation: () => Promise<T>,\n operationName: string,\n config: Partial<RetryConfig> = {}\n): Promise<T> {\n const pkpConfig = {\n ...DEFAULT_RETRY_CONFIG,\n ...config,\n retryableErrors: [\n ...DEFAULT_RETRY_CONFIG.retryableErrors,\n 'pkp validation',\n 'signing shares',\n 'resource validation',\n 'ipfs propagation'\n ]\n };\n\n return withRetry(operation, pkpConfig, `PKP ${operationName}`);\n}\n\n/**\n * Network-specific timeout configurations\n */\nexport const NETWORK_TIMEOUTS = {\n chipotle: {\n connection: 60000,\n operation: 120000,\n pkpValidation: 180000,\n },\n} as const;\n\nexport function getNetworkTimeouts(network: string) {\n return NETWORK_TIMEOUTS[network as keyof typeof NETWORK_TIMEOUTS] || NETWORK_TIMEOUTS['chipotle'];\n}", "/**\n * Enhanced Error Classification for LIT Protocol Operations\n * Provides detailed error categorization and specific retry strategies\n */\n\n/**\n * Error categories for different types of failures\n */\nexport enum ErrorCategory {\n NETWORK = 'network',\n PROTOCOL = 'protocol',\n AUTHENTICATION = 'authentication',\n RESOURCE = 'resource',\n VALIDATION = 'validation',\n TIMEOUT = 'timeout',\n RATE_LIMIT = 'rate_limit',\n CONFIGURATION = 'configuration',\n UNKNOWN = 'unknown'\n}\n\n/**\n * Retry strategy types\n */\nexport enum RetryStrategy {\n AGGRESSIVE = 'aggressive', // Fast retries for transient issues\n CONSERVATIVE = 'conservative', // Slower retries for resource issues\n EXPONENTIAL = 'exponential', // Standard exponential backoff\n LINEAR = 'linear', // Linear delay increase\n NONE = 'none' // No retries\n}\n\n/**\n * Error classification result\n */\nexport interface ErrorClassification {\n category: ErrorCategory;\n retryStrategy: RetryStrategy;\n isRetryable: boolean;\n maxAttempts: number;\n baseDelayMs: number;\n maxDelayMs: number;\n description: string;\n troubleshooting?: string[];\n}\n\n/**\n * LIT Protocol specific error patterns\n */\nconst LIT_ERROR_PATTERNS = {\n // Network and connection errors\n network: [\n /network error/i,\n /connection failed/i,\n /connection refused/i,\n /connection timeout/i,\n /socket hang up/i,\n /enotfound/i,\n /econnrefused/i,\n /etimedout/i,\n /dns resolution failed/i,\n /request failed/i\n ],\n\n // Protocol specific errors\n protocol: [\n /lit protocol/i,\n /lit node/i,\n /signing shares/i,\n /node communication/i,\n /consensus/i,\n /threshold/i,\n /decryption/i,\n /signature verification/i,\n /There was an error getting the signing shares/i,\n /Response from the nodes/i,\n /NodeError/i,\n /PKP validation/i,\n /pkp validation failed/i\n ],\n\n // Authentication and authorization errors\n authentication: [\n /authentication/i,\n /authorization/i,\n /session.*expired/i,\n /invalid.*signature/i,\n /unauthorized/i,\n /access.*denied/i,\n /permission/i,\n /auth.*failed/i,\n /siwe/i,\n /session.*sig/i\n ],\n\n // Resource and validation errors\n resource: [\n /resource.*not.*found/i,\n /ipfs.*not.*found/i,\n /cid.*invalid/i,\n /pkp.*not.*found/i,\n /pkp.*validation/i,\n /resource.*validation/i,\n /action.*not.*permitted/i,\n /lit.*action.*not.*found/i\n ],\n\n // Validation errors\n validation: [\n /validation.*failed/i,\n /invalid.*input/i,\n /invalid.*parameter/i,\n /malformed/i,\n /schema.*validation/i,\n /type.*error/i,\n /missing.*required/i\n ],\n\n // Timeout specific errors\n timeout: [\n /timeout/i,\n /request.*timed.*out/i,\n /operation.*timed.*out/i,\n /deadline.*exceeded/i,\n /time.*limit.*exceeded/i\n ],\n\n // Rate limiting errors\n rateLimit: [\n /rate.*limit/i,\n /too.*many.*requests/i,\n /quota.*exceeded/i,\n /throttled/i,\n /429/,\n /rate.*exceeded/i\n ],\n\n // Configuration errors\n configuration: [\n /configuration/i,\n /config.*error/i,\n /environment/i,\n /missing.*env/i,\n /invalid.*config/i,\n /setup.*error/i\n ]\n};\n\n/**\n * Predefined retry strategies\n */\nconst RETRY_STRATEGIES = {\n [RetryStrategy.AGGRESSIVE]: {\n maxAttempts: 5,\n baseDelayMs: 500,\n maxDelayMs: 5000,\n multiplier: 1.5\n },\n [RetryStrategy.CONSERVATIVE]: {\n maxAttempts: 3,\n baseDelayMs: 3000,\n maxDelayMs: 30000,\n multiplier: 2.5\n },\n [RetryStrategy.EXPONENTIAL]: {\n maxAttempts: 4,\n baseDelayMs: 1000,\n maxDelayMs: 15000,\n multiplier: 2.0\n },\n [RetryStrategy.LINEAR]: {\n maxAttempts: 3,\n baseDelayMs: 2000,\n maxDelayMs: 10000,\n multiplier: 1.0\n },\n [RetryStrategy.NONE]: {\n maxAttempts: 1,\n baseDelayMs: 0,\n maxDelayMs: 0,\n multiplier: 1.0\n }\n};\n\n/**\n * Error classification rules\n */\nconst CLASSIFICATION_RULES: Record<ErrorCategory, ErrorClassification> = {\n [ErrorCategory.NETWORK]: {\n category: ErrorCategory.NETWORK,\n retryStrategy: RetryStrategy.AGGRESSIVE,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.AGGRESSIVE],\n description: 'Network connectivity or communication error',\n troubleshooting: [\n 'Check internet connection',\n 'Verify LIT Protocol network status',\n 'Check firewall and proxy settings',\n 'Try connecting to different node endpoints'\n ]\n },\n\n [ErrorCategory.PROTOCOL]: {\n category: ErrorCategory.PROTOCOL,\n retryStrategy: RetryStrategy.CONSERVATIVE,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.CONSERVATIVE],\n description: 'LIT Protocol specific operational error',\n troubleshooting: [\n 'Check LIT Protocol network status',\n 'Verify PKP configuration',\n 'Check signing shares availability',\n 'Wait for network consensus'\n ]\n },\n\n [ErrorCategory.AUTHENTICATION]: {\n category: ErrorCategory.AUTHENTICATION,\n retryStrategy: RetryStrategy.EXPONENTIAL,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.EXPONENTIAL],\n maxAttempts: 2, // Override: limited retries for auth issues\n description: 'Authentication or authorization error',\n troubleshooting: [\n 'Check session signatures validity',\n 'Regenerate authentication tokens',\n 'Verify wallet permissions',\n 'Check PKP authorization status'\n ]\n },\n\n [ErrorCategory.RESOURCE]: {\n category: ErrorCategory.RESOURCE,\n retryStrategy: RetryStrategy.LINEAR,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.LINEAR],\n maxAttempts: 2, // Override: limited retries for resource issues\n description: 'Resource not found or validation error',\n troubleshooting: [\n 'Verify resource CIDs are correct',\n 'Check IPFS availability',\n 'Confirm PKP exists and is accessible',\n 'Wait for resource propagation'\n ]\n },\n\n [ErrorCategory.VALIDATION]: {\n category: ErrorCategory.VALIDATION,\n retryStrategy: RetryStrategy.NONE,\n isRetryable: false,\n ...RETRY_STRATEGIES[RetryStrategy.NONE],\n description: 'Input validation or schema error',\n troubleshooting: [\n 'Check input parameters format',\n 'Verify required fields are provided',\n 'Validate data types and ranges',\n 'Review API documentation'\n ]\n },\n\n [ErrorCategory.TIMEOUT]: {\n category: ErrorCategory.TIMEOUT,\n retryStrategy: RetryStrategy.CONSERVATIVE,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.CONSERVATIVE],\n description: 'Operation timeout error',\n troubleshooting: [\n 'Increase timeout values',\n 'Check network latency',\n 'Verify system resources',\n 'Split operations into smaller chunks'\n ]\n },\n\n [ErrorCategory.RATE_LIMIT]: {\n category: ErrorCategory.RATE_LIMIT,\n retryStrategy: RetryStrategy.CONSERVATIVE,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.CONSERVATIVE],\n maxAttempts: 2, // Override: limited retries to avoid further rate limiting\n baseDelayMs: 5000, // Override: longer delays for rate limits\n description: 'Rate limit or quota exceeded',\n troubleshooting: [\n 'Reduce request frequency',\n 'Implement request batching',\n 'Check rate limit headers',\n 'Wait for quota reset'\n ]\n },\n\n [ErrorCategory.CONFIGURATION]: {\n category: ErrorCategory.CONFIGURATION,\n retryStrategy: RetryStrategy.NONE,\n isRetryable: false,\n ...RETRY_STRATEGIES[RetryStrategy.NONE],\n description: 'Configuration or setup error',\n troubleshooting: [\n 'Check environment variables',\n 'Verify configuration files',\n 'Review setup documentation',\n 'Check required dependencies'\n ]\n },\n\n [ErrorCategory.UNKNOWN]: {\n category: ErrorCategory.UNKNOWN,\n retryStrategy: RetryStrategy.EXPONENTIAL,\n isRetryable: true,\n ...RETRY_STRATEGIES[RetryStrategy.EXPONENTIAL],\n maxAttempts: 2, // Override: conservative retries for unknown errors\n description: 'Unknown or unclassified error',\n troubleshooting: [\n 'Check logs for more details',\n 'Verify system status',\n 'Try again with debug logging',\n 'Contact support if persists'\n ]\n }\n};\n\n/**\n * Classify an error and determine retry strategy\n */\nexport function classifyError(error: any): ErrorClassification {\n const errorMessage = error?.message || error?.toString() || '';\n const errorLower = errorMessage.toLowerCase();\n\n // Check each error category\n for (const [category, patterns] of Object.entries(LIT_ERROR_PATTERNS)) {\n for (const pattern of patterns) {\n if (pattern.test(errorMessage) || pattern.test(errorLower)) {\n const classification = CLASSIFICATION_RULES[category as ErrorCategory];\n return {\n ...classification,\n description: `${classification.description}: ${errorMessage.slice(0, 100)}`\n };\n }\n }\n }\n\n // Default to unknown category\n const unknownClassification = CLASSIFICATION_RULES[ErrorCategory.UNKNOWN];\n return {\n ...unknownClassification,\n description: `${unknownClassification.description}: ${errorMessage.slice(0, 100)}`\n };\n}\n\n/**\n * Get retry configuration from error classification\n */\nexport function getRetryConfigFromClassification(classification: ErrorClassification) {\n return {\n maxAttempts: classification.maxAttempts,\n initialDelayMs: classification.baseDelayMs,\n maxDelayMs: classification.maxDelayMs,\n backoffMultiplier: RETRY_STRATEGIES[classification.retryStrategy].multiplier,\n retryableErrors: ['*'] // Classification already determined retryability\n };\n}\n\n/**\n * Enhanced error analyzer for detailed error information\n */\nexport function analyzeError(error: any) {\n const classification = classifyError(error);\n\n return {\n ...classification,\n originalError: error,\n errorMessage: error?.message || error?.toString() || 'Unknown error',\n errorStack: error?.stack,\n timestamp: new Date().toISOString(),\n retryConfig: getRetryConfigFromClassification(classification)\n };\n}\n\n/**\n * Create a human-readable error report\n */\nexport function createErrorReport(error: any) {\n const analysis = analyzeError(error);\n\n const report = [\n `\uD83D\uDD0D Error Analysis Report`,\n `=====================================`,\n `Category: ${analysis.category.toUpperCase()}`,\n `Retryable: ${analysis.isRetryable ? '\u2705 Yes' : '\u274C No'}`,\n `Strategy: ${analysis.retryStrategy}`,\n `Max Attempts: ${analysis.maxAttempts}`,\n `Description: ${analysis.description}`,\n `Timestamp: ${analysis.timestamp}`,\n ``,\n `Original Error: ${analysis.errorMessage}`,\n ``\n ];\n\n if (analysis.troubleshooting && analysis.troubleshooting.length > 0) {\n report.push(`\uD83D\uDEE0\uFE0F Troubleshooting Steps:`);\n analysis.troubleshooting.forEach((step, index) => {\n report.push(` ${index + 1}. ${step}`);\n });\n report.push('');\n }\n\n return report.join('\\n');\n}\n\n/**\n * LIT Protocol specific error matchers\n */\nexport const litProtocolErrors = {\n isNetworkError: (error: any) => classifyError(error).category === ErrorCategory.NETWORK,\n isProtocolError: (error: any) => classifyError(error).category === ErrorCategory.PROTOCOL,\n isAuthenticationError: (error: any) => classifyError(error).category === ErrorCategory.AUTHENTICATION,\n isResourceError: (error: any) => classifyError(error).category === ErrorCategory.RESOURCE,\n isTimeoutError: (error: any) => classifyError(error).category === ErrorCategory.TIMEOUT,\n isRateLimitError: (error: any) => classifyError(error).category === ErrorCategory.RATE_LIMIT,\n isConfigurationError: (error: any) => classifyError(error).category === ErrorCategory.CONFIGURATION,\n isRetryable: (error: any) => classifyError(error).isRetryable\n};", "/**\n * Diamond Hands LIT Actions Utilities\n * All utility functions for working with deployed LIT Actions\n */\n\nexport * from \"./chunks/lit-action-helpers\";\nexport * from \"./chunks/pkp-setup\";\nexport * from \"./chunks/cid-utils\";\nexport * from \"./chunks/connection-helpers\";\nexport * from \"./chunks/debug-logger\";\nexport * from \"./chunks/error-classification\";\nexport * from \"./chunks/session-signature-cache\";\n", "/**\n * Vault Snapshot Executor - NOLA (No LIT Action)\n *\n * Standalone executor that wraps VaultSnapshotModule for Node.js execution.\n * Reuses the same pattern as tests/helpers/setup-lit-env.ts.\n *\n * Purpose: FREE data access without paying for LIT Action execution.\n * Use case: Position listing, collateral ratio display, mint preview.\n *\n * Architecture:\n * - Same vault-snapshot.ts code (zero changes)\n * - Inject Node.js providers (ethers, axios) instead of Lit.Actions.*\n * - Returns identical VaultSnapshot data structure\n */\n\nimport { ethers } from \"ethers\";\nimport { createVaultSnapshotModule } from \"../../../src/modules/vault-snapshot\";\nimport { BitcoinDataProvider } from \"../../../src/modules/bitcoin-data-provider.module\";\nimport { PriceOracleModule } from \"../../../src/modules/price-oracle.module\";\nimport { createVaultBalanceModule } from \"../../../src/modules/vault-balance.module\";\nimport { getChainPolicy } from \"../../../src/modules/chain-policy\";\nimport { VaultSnapshot } from \"../../../src/interfaces/chunks/vault-snapshot.i\";\n\n/**\n * Parameters for vault snapshot execution\n */\nexport interface VaultSnapshotExecutorParams {\n positionId: string;\n contractAddress: string; // PositionManager address\n termManagerAddress: string;\n loanOpsManagerAddress: string;\n liquidationManagerAddress: string;\n chain: string; // 'sepolia', 'ethereum', etc.\n chainId?: number;\n rpcUrl: string; // Ethereum RPC URL\n bitcoinProviderUrl: string; // Bitcoin Esplora API URL\n /**\n * Balance-confirmation threshold override. Defaults to the chain policy's\n * `minBitcoinBalanceConfirmations` (mainnet 6, dev chains 1).\n */\n minConfirmations?: number;\n}\n\n/**\n * Execute vault snapshot in Node.js (NOLA - No LIT Action)\n *\n * This function wraps VaultSnapshotModule with Node.js providers,\n * allowing the same code to run outside LIT Actions runtime.\n *\n * @param params - Execution parameters\n * @returns Complete VaultSnapshot\n */\nexport async function executeVaultSnapshot(\n params: VaultSnapshotExecutorParams\n): Promise<VaultSnapshot> {\n // No mainnet default (same rule as VaultSnapshotModule): refuse before touching globals.\n const chainId = params.chainId;\n if (chainId === undefined || !Number.isInteger(chainId) || chainId <= 0) {\n throw new Error(`executeVaultSnapshot requires a positive integer chainId, got ${String(chainId)}`);\n }\n\n // Setup global ethers with v5 compatibility shim for modules\n // Ethers v6 changed API: providers.StaticJsonRpcProvider \u2192 JsonRpcProvider\n (global as any).ethers = {\n ...ethers,\n providers: {\n StaticJsonRpcProvider: ethers.JsonRpcProvider,\n },\n Contract: ethers.Contract,\n utils: ethers, // v6 moved utils to top level\n };\n\n // Setup Lit.Actions mock (same pattern as tests)\n (global as any).Lit = {\n Actions: {\n /**\n * Get RPC URL - returns provided URL\n */\n getRpcUrl: async ({ chain }: { chain: string }): Promise<string> => {\n return params.rpcUrl;\n },\n\n /**\n * Set response (not used in vault-snapshot, but needed for compatibility)\n */\n setResponse: ({ response }: { response: string }): void => {\n // No-op in executor\n },\n\n /**\n * Broadcast and collect (NOLA mode: single node, just return value)\n * In LIT Actions environment, this would collect values from all nodes.\n * In NOLA executor, we're running on a single trusted node, so return single value.\n */\n broadcastAndCollect: async ({ name, value }: { name: string; value: string }): Promise<string[]> => {\n // NOLA: Single node execution, return array with single value\n return [value];\n },\n },\n };\n\n // Initialize Bitcoin data provider\n const bitcoinProvider = new BitcoinDataProvider({\n providerUrl: params.bitcoinProviderUrl,\n });\n\n // Initialize price oracle\n // Note: vault-snapshot-executor doesn't receive priceProviders in params, so uses defaults\n const priceOracle = new PriceOracleModule();\n\n // Initialize vault balance module\n const vaultBalance = createVaultBalanceModule({\n contractAddress: params.loanOpsManagerAddress,\n chain: params.chain,\n chainId,\n rpcUrl: params.rpcUrl,\n bitcoinProvider,\n minConfirmations:\n params.minConfirmations ??\n getChainPolicy(params.chain).minBitcoinBalanceConfirmations,\n });\n\n // Initialize vault snapshot module\n const vaultSnapshot = createVaultSnapshotModule({\n contractAddress: params.contractAddress,\n termManagerAddress: params.termManagerAddress,\n loanOpsManagerAddress: params.loanOpsManagerAddress,\n liquidationManagerAddress: params.liquidationManagerAddress,\n chain: params.chain,\n chainId,\n rpcUrl: params.rpcUrl,\n vaultBalance,\n priceOracle,\n });\n\n // Execute - returns identical VaultSnapshot as LIT Action would\n const snapshot = await vaultSnapshot.getVaultSnapshot(params.positionId);\n\n // Cleanup globals\n delete (global as any).ethers;\n delete (global as any).Lit;\n\n return snapshot;\n}\n", "/**\n * Liquidation Protocol Constants\n *\n * These constants define the liquidation thresholds and grace period escalation\n * for the Diamond Hands Protocol. They are governance-adjustable parameters.\n *\n * CRITICAL: Changes to these values affect protocol security and user positions.\n */\n\n/**\n * Active Loan Liquidation Threshold\n *\n * Minimum collateral ratio required for active (non-expired) loans.\n * Value: 110% (11000 basis points)\n *\n * Canonical source: LoanOperationsManager.liquidationThreshold() on-chain.\n * This constant reflects the protocol-configured value; always prefer fetching\n * from the contract at runtime rather than relying on this constant.\n *\n * Governance-adjustable: YES\n */\nexport const ACTIVE_LOAN_LIQUIDATION_THRESHOLD_BPS = 11000;\n\n/**\n * Expired Loan Minimum Liquidation Threshold\n *\n * Liquidation threshold from expiry through the on-chain grace period, and the seed\n * of the compound escalation after it. Mirrors `ExpiredLoanCalculator.BASE_LIQUIDATION_THRESHOLD`.\n * Value: 110% (11000 basis points)\n *\n * Governance-adjustable: NO (contract constant)\n */\nexport const EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11000;\n\n/**\n * Expired-loan escalation iteration cap\n *\n * Mirrors `ExpiredLoanCalculator.MAX_ESCALATION_ITERATIONS`: once a loan is this many\n * escalation days past its grace period it is unconditionally at the max escalated\n * threshold. The grace period and daily increment themselves are read on-chain from\n * LiquidationManager (`expiredLoanGracePeriodDays`, `expiryLiquidationIncrementBps`).\n *\n * Governance-adjustable: NO (contract constant)\n */\nexport const EXPIRED_LOAN_MAX_ESCALATION_ITERATIONS = 365;\n\n/**\n * Basis-points denominator (100% = 10 000 bps). Mirrors `ExpiredLoanCalculator.BASIS_POINTS`.\n */\nexport const BASIS_POINTS_DENOMINATOR = 10000;\n", "/**\n * Decimal Precision Constants\n *\n * These constants define the decimal precision for various assets and calculations\n * in the Diamond Hands Protocol. They ensure consistent precision across all modules.\n *\n * CRITICAL: These values MUST match contract implementations.\n */\n\n/**\n * Satoshis per Bitcoin\n *\n * Bitcoin's smallest unit is a satoshi (sat).\n * 1 BTC = 100,000,000 satoshis\n *\n * This constant is used for BTC <-> satoshi conversions.\n *\n * Governance-adjustable: NO (Bitcoin protocol constant)\n */\nexport const SATOSHIS_PER_BITCOIN = 100_000_000n;\n\n/**\n * Price Oracle Decimal Precision\n *\n * BTC/USD price is stored with 8 decimal places.\n * Example: $100,000.00 = 10000000000000n (100000 * 10^8)\n *\n * This matches Bitcoin's satoshi precision and allows for sub-cent pricing.\n *\n * Governance-adjustable: NO (System design constant)\n */\nexport const PRICE_ORACLE_DECIMALS = 100_000_000n;\n\n/**\n * UCD Token Decimal Precision\n *\n * UCD is an ERC20 token with 18 decimals (standard for stablecoins).\n * 1 UCD = 10^18 wei\n *\n * This constant is used for all UCD amount calculations.\n *\n * CRITICAL: Must match UCD token contract decimals.\n *\n * Governance-adjustable: NO (Contract constant)\n */\nexport const UCD_TOKEN_DECIMALS = 1_000_000_000_000_000_000n;\n", "/**\n * Bitcoin Network Protocol Constants\n *\n * These constants define Bitcoin network parameters used by the protocol\n * for UTXO validation and security.\n *\n * CRITICAL: Changes to these values affect Bitcoin security guarantees.\n */\n\n/**\n * Maximum BTC Amount Validation\n *\n * Maximum reasonable BTC amount in satoshis.\n * Value: 25,000,000 BTC * 1e8 satoshis = 2.5e15 satoshis\n *\n * Bitcoin total supply is 21M BTC. Setting to 25M provides safety margin\n * to account for future protocol needs while preventing overflow attacks.\n *\n * This validation prevents:\n * - Malicious/corrupted data from oracle manipulation\n * - Integer overflow attacks\n * - Unrealistic balance claims\n *\n * Governance-adjustable: YES (requires contract upgrade)\n */\nexport const MAX_BTC_AMOUNT = 25_000_000 * 1e8; // 2.5e15 satoshis\n\n/**\n * BTC/USD Price Validation Bounds\n *\n * Acceptable range for BTC price in oracle 8-decimal format.\n * Values outside this range indicate oracle manipulation or stale data.\n *\n * MIN: $10,000 (protective floor \u2014 BTC has never traded below this in protocol's lifetime)\n * MAX: $1,000,000 (protective ceiling \u2014 safeguard against oracle inflation attacks)\n *\n * Governance-adjustable: YES (requires review of oracle security model)\n */\nexport const BTC_PRICE_MIN_USD = 10_000_00000000n; // $10k (8 decimals)\nexport const BTC_PRICE_MAX_USD = 1_000_000_00000000n; // $1M (8 decimals)\n\n/**\n * Bitcoin Dust Limit (satoshis)\n *\n * Standard dust threshold for P2PKH outputs (546 satoshis).\n * Outputs below this amount are non-standard and may be rejected by the Bitcoin network.\n *\n * Governance-adjustable: NO (Bitcoin network protocol rule)\n */\nexport const BITCOIN_DUST_LIMIT_SATS = 546n;\n\n/**\n * Bitcoin Transaction Fee Bounds (satoshis)\n *\n * MIN is the floor for any protocol Bitcoin transaction. MAX_BTC_FEE_SATS is a\n * FLAT absolute ceiling still used by the fixed-size single-purpose actions\n * (btc-utxo-invalidator, stale-spend-recovery-validator). The variable-size\n * WITHDRAWAL path does NOT use MAX_BTC_FEE_SATS \u2014 a flat cap is an implicit\n * fee-rate ceiling that shrinks as inputs grow, blocking large consolidations;\n * it uses the size-aware bound in `modules/bitcoin/fee.ts` instead.\n *\n * Adjustability: these are Lit Action constants \u2014 changing a value requires a\n * bundle rebundle + CID rotation ceremony (NOT a runtime/governance toggle).\n */\nexport const MIN_BTC_FEE_SATS = 100; // Minimum viable Bitcoin fee\nexport const MAX_BTC_FEE_SATS = 100_000; // 0.001 BTC \u2014 flat cap for fixed-size (non-withdrawal) actions\n\n/**\n * UTXO Query Retry Parameters\n *\n * Number of attempts and delay between retries when querying UTXOs from\n * the Bitcoin data provider. Applied uniformly across all retry loops.\n *\n * Governance-adjustable: NO (operational tuning constant)\n */\nexport const UTXO_QUERY_MAX_RETRIES = 3;\nexport const UTXO_QUERY_RETRY_DELAY_MS = 500; // 500ms between retries\n", "/**\n * Quantum Time Window Protocol Constants\n *\n * These constants define the quantum time window system used for temporal\n * validation of signed operations across the protocol.\n *\n * CRITICAL: Changes to these values affect replay attack protection and\n * validator synchronization. All validators must use identical values.\n */\n\n/**\n * Quantum Window Duration (seconds)\n *\n * Each quantum window is 60 seconds long.\n * Quantum timestamps always end in :00 seconds: 0, 60, 120, 180...\n *\n * Value: 60 seconds \u2014 MUST match `OperationAuthorizationRegistry.QUANTUM_WINDOW_SECONDS`\n * on every chain. Drift here causes spurious `QuantumOutsideWindow()` reverts because\n * the Lit Action signs a `quantumTimestamp` aligned to its window while the contract\n * floors it to its own window. A bad merge briefly bumped this to 100 \u2014 never again.\n *\n * Purpose:\n * - Improved UX with immediate signing (no waiting)\n * - 3-quantum validation window (past, current, next) = 180s total validity\n * - Prevents replay attacks across quantum boundaries\n * - Users can operate once per 60 seconds per position\n *\n * Security guarantee: Signatures valid across 3 quantums with replay prevention.\n *\n * Governance-adjustable: NO (protocol-level constant)\n */\nexport const QUANTUM_WINDOW_SECONDS = 60;\n\n/**\n * Dead Zone Duration (seconds)\n *\n * The dead zone spans the quantum boundary: 8 seconds before + 8 seconds after.\n * During this period, LIT Actions WAIT and Smart Contracts REJECT.\n *\n * Dead zone structure:\n * - Seconds 92-99: Last 8 seconds of quantum (before boundary)\n * - Seconds 0-7: First 8 seconds of quantum (after boundary)\n * - Total: 16 seconds\n *\n * Value: 16 seconds (8+8)\n *\n * Protects against:\n * 1. Clock desynchronization (NTP drift, network delays)\n * 2. Ethereum miner timestamp manipulation (validators can shift \u00B115 seconds)\n * 3. Quantum boundary confusion\n *\n * Security guarantee: 16-second buffer > 15-second miner manipulation = complete protection.\n *\n * Governance-adjustable: NO (protocol-level constant, security-critical)\n */\nexport const DEAD_ZONE_SECONDS = 16;\n\n/**\n * Safe Execution Window (seconds)\n *\n * Actual usable time in each quantum after excluding the dead zone.\n *\n * Value: 44 seconds (QUANTUM_WINDOW_SECONDS - DEAD_ZONE_SECONDS)\n * With 60s quantum: safe period is seconds 8-51 of each quantum\n *\n * Governance-adjustable: NO (derived from other constants)\n */\nexport const SAFE_EXECUTION_WINDOW_SECONDS =\n QUANTUM_WINDOW_SECONDS - DEAD_ZONE_SECONDS;\n\n/**\n * Quantum Timestamp Offset (seconds)\n *\n * The offset added to the current quantum timestamp when building signed\n * message hashes. Set to the next quantum boundary to ensure the signature\n * remains valid through the current quantum and into the next.\n *\n * Value: 10 seconds \u2014 places the signed timestamp safely inside the upcoming\n * quantum window, matching the contract-side validation window.\n *\n * CRITICAL: Must match the offset expected by the smart contract validators.\n *\n * Governance-adjustable: NO (protocol-level constant, must match contract)\n */\nexport const QUANTUM_TIMESTAMP_OFFSET = 10;\n", "/**\n * Time Protocol Constants\n *\n * Canonical time unit constants used for term duration calculations\n * throughout the protocol. Centralised here to avoid silent drift if\n * any value ever needs to change.\n *\n * NOTE: The protocol models months as exactly 30 days and years as exactly\n * 365 days. This is intentional \u2014 simplicity and consistency with the\n * on-chain term calculations take precedence over calendar accuracy.\n */\n\n/**\n * Seconds per day\n *\n * Value: 86400 (24 * 60 * 60)\n *\n * Governance-adjustable: NO (physical constant)\n */\nexport const SECONDS_PER_DAY = 86400;\n\n/**\n * Days per month (protocol approximation)\n *\n * Value: 30\n *\n * The protocol uses a fixed 30-day month for all term calculations,\n * matching the on-chain TermManager configuration.\n *\n * Governance-adjustable: NO (must match contract term definitions)\n */\nexport const DAYS_PER_MONTH = 30;\n\n/**\n * Months per year\n *\n * Value: 12\n *\n * Governance-adjustable: NO (calendar constant)\n */\nexport const MONTHS_PER_YEAR = 12;\n\n/**\n * Days per year (protocol approximation)\n *\n * Value: 365\n *\n * Used specifically for 12-month term duration calculations where the\n * protocol uses 365 days instead of 12 * 30 = 360 days.\n *\n * Governance-adjustable: NO (must match contract term definitions)\n */\nexport const DAYS_PER_YEAR = 365;\n", "/**\n * Lit Actions run under a strict JS execution budget on Lit nodes (~30\u201335s observed).\n * Unbounded `eth_call` / JSON-RPC waits can hang until the node kills the action with\n * `request_timeout`. Keep per-request RPC timeouts well below that budget.\n */\nexport const LIT_ACTION_ETH_RPC_TIMEOUT_MS = 8_000;\n", "/**\n * Auto-generated pinned deployment addresses for LIT Actions.\n * Generated by sdk/scripts/sync-deployments.js \u2014 DO NOT EDIT MANUALLY.\n *\n * Security-critical contract anchors, keyed by EVM chainId, that the\n * btc-transaction-signer LIT Action uses to REFUSE caller-supplied addresses on\n * enforced chains (sepolia/ethereum) \u2014 F1 remediation. Same deployment source\n * as the SDK's deployment-addresses.ts, so the two can never drift. Only chains\n * whose FULL anchor set is present are emitted; a chain absent here makes the\n * signer fail-closed (it throws rather than trusting caller-supplied values).\n */\n\nexport interface PinnedContractAddresses {\n /** PositionManager Diamond PROXY (stable across facet upgrades). */\n PositionManager: string;\n LoanOperationsManagerModule: string;\n BTCSpendAuthorizer: string;\n BitcoinProviderRegistry: string;\n LITActionValidator: string;\n PositionDelegateRegistry: string;\n /** Rate/term source for every signed loan attestation (pinned 2026-09-23). */\n TermManagerModule: string;\n /** UCD debt token controller (pinned 2026-09-23). */\n UCDController: string;\n /** Liquidation state the validators read and sign against (pinned 2026-09-23). */\n LiquidationManagerModule: string;\n}\n\nexport const PINNED_CONTRACT_ADDRESSES: Record<\n number,\n PinnedContractAddresses\n> = {\n 1: {\n PositionManager: \"0x12A1836e56139ccaD8722B89519d84233efc224B\",\n LoanOperationsManagerModule: \"0x2561974A40F1AEed1251d0A090A83cF8536FB9E9\",\n BTCSpendAuthorizer: \"0xfBbF108486fa07F1B06a811C5b66ed68DD9c508a\",\n BitcoinProviderRegistry: \"0x4ab3Fb96e02893Ed6FAa61bad1918390c8DbbFFC\",\n LITActionValidator: \"0xD2c5d59c2CC5c409AC65ce0A817236aeC6869512\",\n PositionDelegateRegistry: \"0xf0aa2678aD4F60f49e8F7725089B5E86B7F8FE4C\",\n TermManagerModule: \"0xDB99CdF883ffa38acD099bC39F8d1f4508c9239E\",\n UCDController: \"0x4b4f8063048bCD59D469219E3f07C6aaDF4f6157\",\n LiquidationManagerModule: \"0x74B28695352E7bf736D6c9F76ccb7B4439477De9\",\n },\n 11155111: {\n PositionManager: \"0x68e0507D982AEBF1D1C1Af8FBbd842327e2deeFF\",\n LoanOperationsManagerModule: \"0x3e05e760a87715207b7F4e8fD35EF7559BcA72C0\",\n BTCSpendAuthorizer: \"0xd7E9Eb5eE53f1d9ee55Dc162bBC7486bE437B6bD\",\n BitcoinProviderRegistry: \"0xbfA0c48B070D0a9A9CD27469AeacFD2d4261cEE2\",\n LITActionValidator: \"0x54eECd7C90F8A8fac27749Ba30BbE8AFBAccc856\",\n PositionDelegateRegistry: \"0x482369De283622E7b05731875ec137d4E3D208F9\",\n TermManagerModule: \"0x94Adc6F9558368B1482197584f1fc7133Ecf835b\",\n UCDController: \"0x360Bde4e489ee94E26601B206932De09EE60FF04\",\n LiquidationManagerModule: \"0xC4AB00f39e7ceD812F5C67058C9fa44e15d40e76\",\n },\n};\n\n/**\n * Pinned security-critical addresses for a chainId, or null when the chain has\n * no complete pinned set. A null result MUST make the caller fail-closed on an\n * enforced chain \u2014 never fall through to caller-supplied addresses.\n */\nexport function getPinnedContractAddresses(\n chainId: number,\n): PinnedContractAddresses | null {\n return PINNED_CONTRACT_ADDRESSES[chainId] ?? null;\n}\n\n/**\n * Agent-path trust anchors (Safe-delegated withdrawal hardening, 2026-08-05)\n * \u2014 SEPARATE from PinnedContractAddresses above and NEVER merged into it.\n * `AgentModuleFactory` has no mainnet deployment yet (decision D-1,\n * deferred), so this map is emitted BEST EFFORT per chain: a chain may carry\n * only a partial (or empty) entry. An absent key MUST make the caller (the\n * Safe-agent authorization arm) fail closed \u2014 never fall through to a\n * caller-supplied value \u2014 but MUST NOT affect the ordinary borrower\n * withdrawal path, which reads only PinnedContractAddresses above.\n */\nexport interface AgentPathPinnedAddresses {\n /** CREATE2 factory a Safe uses to deploy its own AgentModule. Absent on mainnet until D-1 ships. */\n AgentModuleFactory?: string;\n /** Per-position agent grant registry (SCOPE_WITHDRAW, floor, TTL). */\n AgentDelegationRegistry?: string;\n /**\n * Per-wallet allowlist of approved BTC withdrawal destinations (24h time-lock).\n * The destination bound the Safe-agent withdrawal arm ENFORCES: a leaked agent\n * key can only pay out to an owner-approved address. Absent \u21D2 the agent arm\n * refuses (fail closed) \u2014 it must never be taken from the caller.\n */\n BitcoinWithdrawalAddressRegistry?: string;\n}\n\nexport const AGENT_PATH_PINNED_ADDRESSES: Record<\n number,\n AgentPathPinnedAddresses\n> = {\n 1: {\n AgentDelegationRegistry: \"0x54853b7E91ce2Be34ce65655D80c4447e67187Fa\",\n BitcoinWithdrawalAddressRegistry: \"0xf667f77FDba7458345f227eB6Bfe4148243E7270\",\n },\n 11155111: {\n AgentModuleFactory: \"0x1Fd3aCa2C030Cf77ce28Af9694D3Bb3034ACa2E5\",\n AgentDelegationRegistry: \"0x6AE7fc6bE0925126b9D25b1B7Ce5AD5d127ec025\",\n BitcoinWithdrawalAddressRegistry: \"0x6376D392097F0A81e51BD83960A97EA20eaf1dbe\",\n },\n};\n\n/**\n * Agent-path trust anchors for a chainId, BEST EFFORT. Never throws and\n * never gates the ordinary borrower withdrawal path \u2014 an absent key (or an\n * absent chain, returning `{}`) means the Safe-agent authorization arm\n * must refuse on this chain.\n */\nexport function getAgentPathPinnedAddresses(\n chainId: number,\n): AgentPathPinnedAddresses {\n return AGENT_PATH_PINNED_ADDRESSES[chainId] ?? {};\n}\n", "/**\n * Domain strings for `MessageHashBuilder.sol` (OperationAuthorizationRegistry / PositionManager).\n *\n * **Single source of truth** for UTF-8 labels hashed to `bytes32` domain tags in LIT Actions.\n * Changing a value requires updating Solidity (`MessageHashBuilder.sol`) and re-running\n * `contracts` tests: `MessageHashBuilder.constants.unit.test.ts`.\n *\n * @see contracts/src/libraries/MessageHashBuilder.sol\n * @see contracts/docs/EIP712_DOMAIN_SPEC.md (EIP-712 domain.name / version / verifyingContract)\n */\n\n/** Matches `PAYMENT_ACTION_HASH` / `buildPaymentHash` */\nexport const MESSAGE_HASH_DOMAIN_PARTIAL_PAYMENT = \"partial-payment\";\n\n/** Matches `LIQUIDATION_ACTION_HASH` / `buildLiquidationHash` */\nexport const MESSAGE_HASH_DOMAIN_LIQUIDATION = \"liquidation\";\n\n/**\n * Shared EIP-712 `EIP712Domain.name` for protocol verifiers (PKPValidation, LiquidationManager, future LOM).\n * Distinct `DOMAIN_SEPARATOR` per `verifyingContract` proxy. @see contracts/docs/EIP712_DOMAIN_SPEC.md\n */\nexport const PROTOCOL_EIP712_DOMAIN_NAME = \"DiamondHands.Protocol\";\n\n/** Shared EIP-712 `EIP712Domain.version` until a breaking primary-type / field-order change. */\nexport const PROTOCOL_EIP712_DOMAIN_VERSION = \"1\";\n\n/** @deprecated Use PROTOCOL_EIP712_DOMAIN_NAME \u2014 identical. */\nexport const LIQUIDATION_MANAGER_EIP712_NAME = PROTOCOL_EIP712_DOMAIN_NAME;\n\n/** @deprecated Use PROTOCOL_EIP712_DOMAIN_VERSION \u2014 identical. */\nexport const LIQUIDATION_MANAGER_EIP712_VERSION = PROTOCOL_EIP712_DOMAIN_VERSION;\n\n/** Matches `EXTENSION_ACTION_HASH` / `buildExtensionHash` */\nexport const MESSAGE_HASH_DOMAIN_EXTEND_POSITION = \"extend-position\";\n\n/** Matches `BALANCE_CONFIRMATION_ACTION_HASH` / `buildBalanceConfirmationHash` */\nexport const MESSAGE_HASH_DOMAIN_BALANCE_CONFIRMATION = \"balance-confirmation\";\n\n/**\n * Action tag for the address-only `AddressBalanceAttestation` (btc-address-balance LIT Action).\n *\n * Deliberately DISTINCT from `MESSAGE_HASH_DOMAIN_BALANCE_CONFIRMATION`: that attestation is\n * position-bound and consumed on-chain by `PositionManager.updateBalance`. This one signs a raw\n * total chain balance for a bare Bitcoin address (no positionId, no authorized-spend subtraction)\n * and has NO Solidity counterpart in `MessageHashBuilder.sol` \u2014 there is no on-chain consumer. The\n * separate tag + a non-LOM `verifyingContract` guarantee the two digests can never collide, so an\n * address-balance signature can never be replayed as a protocol BalanceConfirmation.\n */\nexport const MESSAGE_HASH_DOMAIN_ADDRESS_BALANCE = \"address-balance\";\n\n/** Matches `MessageHashBuilder.MINT_ACTION_HASH` / `buildMintHash` */\nexport const MINT_ACTION_STRING = \"mint-ucd\";\n\n/** User authorization message action for BTC withdrawal (not a MessageHashBuilder domain tag). */\nexport const WITHDRAW_BTC_ACTION_STRING = \"withdraw-btc\";\n\n/**\n * User authorization message action for partial payment (not a MessageHashBuilder domain tag).\n *\n * Distinct from `MESSAGE_HASH_DOMAIN_PARTIAL_PAYMENT = \"partial-payment\"`, which is the EIP-712\n * inner-domain tag the Lit Action signs for on-chain consumption. The string below is what the\n * SDK writes into `authMessage.action` and what `process-payment-validator` pins before\n * accepting a user signature. Audit CRIT-5: the previous payment path called the agnostic base\n * verifier without pinning this string, which made `make-payment` signatures cross-action-\n * fungible with anything else built over the same digest shape.\n *\n * Wire-compat: the SDK has been signing `\"make-payment\"` since launch; do not change the value\n * here without a coordinated SDK release.\n */\nexport const PARTIAL_PAYMENT_ACTION_STRING = \"make-payment\";\n\n/**\n * User authorization message action for stale-spend recovery (audit #62210 Phase 2).\n *\n * Distinct action string so a leaked `withdraw-btc` signature cannot be replayed as a\n * recovery intent, and vice versa. Bound by `verifyRecoveryAuthorization` (in\n * `modules/authorization.module.ts`) into the borrower-signed message that the\n * `btc-utxo-invalidator` LIT Action consumes.\n */\nexport const RECOVERY_INVALIDATE_ACTION_STRING = \"btc-utxo-invalidator\";\n\n/**\n * Submission action string for the on-chain `cancelStaleSpendWithProof` call (audit #62210).\n * Used inside the LIT-signed `StaleSpendRecovery` attestation domain \u2014 purely informational\n * (the EIP-712 type provides the cryptographic binding); kept for debug/log greppability.\n */\nexport const RECOVERY_ATTEST_ACTION_STRING = \"stale-spend-recovery\";\n", "/**\n * EIP-712 type definitions for **borrower** authorization messages.\n *\n * **Single source of truth.** The SDK builds these messages and the LIT Actions\n * verify them; both import from this module so the two can never drift. A digest\n * kept in sync by comment is a digest that will eventually disagree \u2014 and a\n * disagreement here does not degrade, it rejects every signature in flight.\n *\n * ## What these are\n *\n * The prompt a borrower sees BEFORE the on-chain transaction. Today the SDK\n * collapses the field set into one `keccak256` digest and calls `personal_sign`\n * over the 32 bytes, so the wallet renders an opaque hash and no ERC-7730\n * descriptor can help it \u2014 the preimage never reaches the wallet. Encoding the\n * same fields as typed data is what makes the values renderable.\n *\n * ## No Solidity counterpart \u2014 deliberately\n *\n * Unlike `./message-hash-domains`, nothing here mirrors a constant in\n * `MessageHashBuilder.sol`, and no contract recomputes these digests. The\n * borrower signature is consumed entirely in `modules/authorization.module.ts`\n * and never reaches Solidity: `PositionManager.mintUCD` takes exactly one\n * signature \u2014 `mintValidatorSignature` \u2014 checked against\n * `loanOps.eip712DigestMintUcd(...)` (`PositionManager.sol:1071`), which is the\n * **validator PKP's** attestation, a different signer over a different digest.\n * That is why this lives in its own module rather than alongside the\n * MessageHashBuilder domain tags: someone reading those constants is entitled\n * to assume a Solidity counterpart exists, and for these there is none to find.\n *\n * ## Naming: `*Request` vs the validator types\n *\n * Owner-signed types are `*Request`; validator-signed types keep their existing\n * names. `WithdrawRequest` sits one letter from\n * `LoanOperationsManager.WITHDRAWAL_AUTHORIZATION_TYPEHASH`'s\n * `WithdrawalAuthorization` **on purpose** \u2014 different signer, different digest,\n * deliberately non-colliding. Do not \"tidy\" the two into one name.\n *\n * @see clear-signing/registry/diamond-hands/eip712-LoanOperationsManager.json \u2014 the ERC-7730\n * descriptor, whose format keys are these `encodeType` strings verbatim.\n * Changing a type string here invalidates that descriptor.\n * @see contracts/docs/EIP712_DOMAIN_SPEC.md \u00A74.1 \u2014 descriptor maintenance coupling.\n */\n\nimport { getPinnedContractAddresses } from \"./chunks/deployment-addresses\";\nimport {\n PROTOCOL_EIP712_DOMAIN_NAME,\n PROTOCOL_EIP712_DOMAIN_VERSION,\n} from \"./message-hash-domains\";\n\n/** One EIP-712 struct member. Shape is compatible with both ethers v5 and v6. */\nexport interface BorrowerAuthorizationField {\n readonly name: string;\n readonly type: string;\n}\n\n/**\n * The four owner-signed primary types, one per loan operation.\n *\n * `execute-btc-withdrawal` and `btc-utxo-invalidator` are absent on purpose:\n * they belong to the BTCSpendAuthorizer domain, not LoanOperationsManager, so\n * they cannot share this `verifyingContract`.\n */\nexport const BORROWER_AUTHORIZATION_PRIMARY_TYPES = {\n MINT: \"MintRequest\",\n REPAY: \"RepayRequest\",\n RENEW: \"RenewRequest\",\n WITHDRAW: \"WithdrawRequest\",\n} as const;\n\nexport type BorrowerAuthorizationPrimaryType =\n (typeof BORROWER_AUTHORIZATION_PRIMARY_TYPES)[keyof typeof BORROWER_AUTHORIZATION_PRIMARY_TYPES];\n\n/**\n * Field lists per primary type. **Order is part of the digest** \u2014 appending,\n * reordering, or renaming a member changes every signature this protocol\n * produces and invalidates the ERC-7730 descriptor in the same step.\n *\n * `quantumTimestamp` is last in all four so the fields a user actually chose\n * (amount, destination) render before protocol bookkeeping on a device that\n * truncates.\n */\nexport const BORROWER_AUTHORIZATION_FIELDS: Readonly<\n Record<BorrowerAuthorizationPrimaryType, readonly BorrowerAuthorizationField[]>\n> = {\n MintRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"mintAmount\", type: \"uint256\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n RepayRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"paymentAmount\", type: \"uint256\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n RenewRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"selectedTerm\", type: \"uint256\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n WithdrawRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"totalDeduction\", type: \"uint256\" },\n { name: \"withdrawalAddress\", type: \"string\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n} as const;\n\n/**\n * Frozen `encodeType` strings \u2014 the EIP-712 typehash preimages.\n *\n * Duplicated from the field lists ON PURPOSE. These are the exact keys of\n * `display.formats` in `eip712-LoanOperationsManager.json`, so writing them out\n * literally lets a test compare descriptor to code as plain strings, with no\n * derivation step that could be wrong in both places at once. The unit suite\n * asserts these match what an encoder derives from\n * `BORROWER_AUTHORIZATION_FIELDS`; they are not trusted to agree by inspection.\n */\nexport const BORROWER_AUTHORIZATION_ENCODE_TYPES: Readonly<\n Record<BorrowerAuthorizationPrimaryType, string>\n> = {\n MintRequest:\n \"MintRequest(bytes32 positionId,uint256 mintAmount,uint256 quantumTimestamp)\",\n RepayRequest:\n \"RepayRequest(bytes32 positionId,uint256 paymentAmount,uint256 quantumTimestamp)\",\n RenewRequest:\n \"RenewRequest(bytes32 positionId,uint256 selectedTerm,uint256 quantumTimestamp)\",\n WithdrawRequest:\n \"WithdrawRequest(bytes32 positionId,uint256 totalDeduction,string withdrawalAddress,uint256 quantumTimestamp)\",\n} as const;\n\n/** EIP-712 domain for borrower authorizations. `verifyingContract` is the LOM proxy. */\nexport interface BorrowerAuthorizationDomain {\n readonly name: string;\n readonly version: string;\n readonly chainId: number;\n readonly verifyingContract: string;\n}\n\n/**\n * The `types` argument for `TypedDataEncoder.hash(domain, types, message)`.\n *\n * Returns ONLY the requested primary type. Handing an encoder a map containing\n * all four would still hash correctly, but it would let a caller pass a message\n * shaped like a different operation and have it encode without complaint \u2014 so\n * the narrow map is the safer default, not a convenience.\n *\n * Returns mutable copies: ethers v6 types `TypedDataField[]` as mutable, and a\n * `readonly` array is not assignable to it.\n *\n * @throws if `primaryType` is not one of the four. No fallback \u2014 an unknown\n * operation must not silently acquire a digest.\n */\nexport function borrowerAuthorizationTypes(\n primaryType: BorrowerAuthorizationPrimaryType,\n): Record<string, BorrowerAuthorizationField[]> {\n const fields = BORROWER_AUTHORIZATION_FIELDS[primaryType];\n if (!fields) {\n throw new Error(\n `Unknown borrower authorization primary type \"${primaryType}\"; ` +\n `expected one of ${Object.keys(BORROWER_AUTHORIZATION_FIELDS).join(\", \")}`,\n );\n }\n return { [primaryType]: fields.map((field) => ({ ...field })) };\n}\n\n/**\n * Build the EIP-712 domain for a chain.\n *\n * `verifyingContract` resolves from `PINNED_CONTRACT_ADDRESSES`, the map\n * `sdk/scripts/sync-deployments.js` generates from the deployment files \u2014 the\n * same source the SDK uses, so a redeploy cannot desync the two sides of the\n * digest. It is deliberately NOT a caller-supplied parameter by default: a\n * domain taken from `jsParams` is a domain an attacker chooses, and the\n * verifying side would then validate a signature the borrower never scoped to\n * this protocol.\n *\n * `verifyingContractOverride` exists for chains with no pinned set \u2014 hardhat in\n * the test suite. On a pinned chain it is CHECKED, not honoured: supplying a\n * value that contradicts the pin throws, mirroring\n * `resolveSecurityCriticalAddresses` (`modules/pinned-addresses.ts`), which\n * surfaces a malicious or misconfigured caller instead of quietly ignoring them.\n *\n * @throws if the chain has no pinned LOM address and no override is supplied.\n * @throws if an override contradicts the pinned address for that chain.\n */\nexport function buildBorrowerAuthorizationDomain(\n chainId: number,\n verifyingContractOverride?: string,\n): BorrowerAuthorizationDomain {\n if (!Number.isInteger(chainId) || chainId <= 0) {\n throw new Error(\n `Borrower authorization domain requires a positive integer chainId, got ${String(chainId)}`,\n );\n }\n\n const pinned = getPinnedContractAddresses(chainId);\n const pinnedLom = pinned?.LoanOperationsManagerModule;\n\n if (pinnedLom && verifyingContractOverride) {\n if (pinnedLom.toLowerCase() !== verifyingContractOverride.toLowerCase()) {\n throw new Error(\n `Refusing a caller-supplied verifyingContract that contradicts the pin for chainId ${chainId}: ` +\n `caller ${verifyingContractOverride}, pinned ${pinnedLom}`,\n );\n }\n }\n\n const verifyingContract = pinnedLom ?? verifyingContractOverride;\n if (!verifyingContract) {\n throw new Error(\n `No pinned LoanOperationsManagerModule for chainId ${chainId} and no verifyingContract supplied; ` +\n `refusing to build a borrower authorization domain without one`,\n );\n }\n\n return {\n name: PROTOCOL_EIP712_DOMAIN_NAME,\n version: PROTOCOL_EIP712_DOMAIN_VERSION,\n chainId,\n verifyingContract,\n };\n}\n", "/**\n * Bitcoin Network Configuration\n *\n * Defines approved Bitcoin RPC providers and network mappings for the protocol.\n * This ensures LIT actions only use vetted, reliable Bitcoin data sources.\n *\n * CRITICAL: Only approved providers should be added to this configuration.\n */\n\n/**\n * Supported EVM chains\n */\nexport enum EVMChain {\n /** Ethereum Sepolia testnet */\n SEPOLIA = \"sepolia\",\n\n /** Ethereum mainnet */\n ETHEREUM = \"ethereum\",\n\n /** Hardhat local testnet */\n HARDHAT = \"hardhat\",\n}\n\n/**\n * Bitcoin network types\n */\nexport enum BitcoinNetwork {\n /** Bitcoin testnet */\n TESTNET = \"testnet\",\n\n /** Bitcoin mainnet */\n MAINNET = \"mainnet\",\n\n /** Bitcoin regtest (local/testing) */\n REGTEST = \"regtest\",\n}\n\nimport type { ProviderAuth } from \"../../modules/bitcoin-provider-auth\";\n\n/**\n * Bitcoin provider configuration\n */\nexport interface BitcoinProviderConfig {\n /** Provider API URL */\n url: string;\n\n /** Bitcoin network (testnet or mainnet) */\n network: BitcoinNetwork;\n\n /**\n * Balance-confirmation threshold stamped from\n * `policy.minBitcoinBalanceConfirmations` by the provider registry. NEVER use\n * this to gate UTXO spends \u2014 spends must use\n * `policy.minBitcoinSpendConfirmations` directly.\n */\n minConfirmations: number;\n\n /** Human-readable provider name */\n name: string;\n\n /**\n * Auth descriptor for the provider's Esplora API. Absent \u21D2 no auth (public\n * Esplora / regtest faucet). Populated from the decrypted registry blob for\n * commercial providers (Maestro api-key, Blockstream Enterprise OAuth).\n */\n auth?: ProviderAuth;\n}\n\n/**\n * Mapping from EVM chain to Bitcoin network\n *\n * - Sepolia \u2192 Bitcoin Regtest (Diamond Hands uses a private regtest faucet for Sepolia testing)\n * - Ethereum (mainnet) \u2192 Bitcoin Mainnet\n *\n * NOTE: Sepolia maps to REGTEST (not TESTNET) because Diamond Hands uses a private\n * regtest Bitcoin node (regtest.diamondhands.credit) for Sepolia E2E testing.\n * Vault addresses are bcrt1q\u2026 (regtest prefix). Changing to TESTNET would cause\n * deriveBitcoinAddress to produce tb1q\u2026 addresses instead of the vault's bcrt1q\u2026 format,\n * and PSBT assembly to use bitcoin.networks.testnet which can silently corrupt the\n * broadcast flow when the endpoint returns an empty 200 body.\n */\nexport const CHAIN_TO_BITCOIN_NETWORK: Record<EVMChain, BitcoinNetwork> = {\n [EVMChain.SEPOLIA]: BitcoinNetwork.REGTEST,\n [EVMChain.ETHEREUM]: BitcoinNetwork.MAINNET,\n [EVMChain.HARDHAT]: BitcoinNetwork.REGTEST, // Local development\n};\n\n/**\n * Approved EVM RPC provider domains\n *\n * Only RPC providers whose hostnames match one of these domain suffixes are\n * permitted inside LIT Actions for Ethereum/EVM calls. Adding a provider\n * here requires a security review \u2014 untrusted RPCs can return manipulated\n * state and compromise validator logic.\n *\n * Governance-adjustable: YES (add/remove after security review)\n *\n * `drpc.live` added 2026-10-18 after review: it is dRPC's optimized load\n * balancer (ownership confirmed by the Master); `drpc.org` is its legacy host.\n */\nexport const APPROVED_EVM_RPC_DOMAINS = [\"infura.io\", \"drpc.org\", \"drpc.live\"];\n\n/**\n * Mapping from EVM chain to chain ID\n *\n * - Ethereum mainnet: 1\n * - Sepolia testnet: 11155111\n * - Hardhat local: 1337 (matches contracts/hardhat.config.ts)\n */\nexport const CHAIN_TO_CHAIN_ID: Record<EVMChain, number> = {\n [EVMChain.ETHEREUM]: 1,\n [EVMChain.SEPOLIA]: 11155111,\n [EVMChain.HARDHAT]: 1337,\n};\n\n/**\n * Approved Bitcoin RPC providers per network\n *\n * Only providers in this whitelist can be used by LIT actions.\n * Each provider has specific min confirmation requirements.\n *\n * TESTNET: Lower confirmation requirements (1 block)\n * REGTEST: Lower confirmation requirements (1 block)\n * MAINNET: Higher confirmation requirements (6 blocks - industry standard)\n */\nexport const APPROVED_BITCOIN_PROVIDERS: Record<\n BitcoinNetwork,\n BitcoinProviderConfig[]\n> = {\n [BitcoinNetwork.REGTEST]: [\n {\n url: \"https://regtest.diamondhands.credit/api/esplora\",\n network: BitcoinNetwork.REGTEST,\n minConfirmations: 1,\n name: \"Diamond Hands\",\n },\n {\n url: \"http://127.0.0.1:18443\",\n network: BitcoinNetwork.REGTEST,\n minConfirmations: 1,\n name: \"Local Regtest\",\n },\n {\n url: \"https://313561dc30c5.ngrok-free.app\",\n network: BitcoinNetwork.REGTEST,\n minConfirmations: 1,\n name: \"Ngrok Bitcoin Tunnel\",\n },\n ],\n // TESTNET and MAINNET allowlists are intentionally empty in source.\n // Provider URLs are stored encrypted on-chain in BitcoinProviderRegistry\n // and fetched at runtime via `Lit.Actions.Decrypt` (see\n // modules/bitcoin-provider-registry.ts). Hardcoding URLs here would leak\n // internal infrastructure \u2014 the faucet URLs that were previously in this\n // file were visible in the IPFS-pinned LIT Action bundle and in GitHub.\n // (audit C-1 / H-6 fix)\n [BitcoinNetwork.TESTNET]: [],\n [BitcoinNetwork.MAINNET]: [],\n};\n\n/**\n * Validate and normalize EVM chain input\n *\n * @param chain Chain identifier (case-insensitive)\n * @returns Validated EVMChain enum value\n * @throws Error if chain is not supported\n */\nexport function validateChain(chain: string): EVMChain {\n const normalized = chain.toLowerCase().trim();\n\n if (normalized === \"sepolia\") {\n return EVMChain.SEPOLIA;\n }\n\n if (normalized === \"ethereum\" || normalized === \"mainnet\") {\n return EVMChain.ETHEREUM;\n }\n\n if (normalized === \"hardhat\") {\n return EVMChain.HARDHAT;\n }\n\n throw new Error(\n `Unsupported EVM chain: \"${chain}\". ` +\n `Supported chains: ${Object.values(EVMChain).join(\", \")}`\n );\n}\n\n/**\n * Get Bitcoin network for EVM chain\n *\n * @param chain EVM chain\n * @returns Corresponding Bitcoin network\n */\nexport function getBitcoinNetworkForChain(chain: EVMChain): BitcoinNetwork {\n return CHAIN_TO_BITCOIN_NETWORK[chain];\n}\n\n/**\n * Get chain ID for EVM chain\n *\n * @param chain EVM chain\n * @returns Corresponding chain ID\n */\nexport function getChainIdForChain(chain: EVMChain): number {\n return CHAIN_TO_CHAIN_ID[chain];\n}\n\n/**\n * Validate Bitcoin provider is approved for network\n *\n * @param providerUrl Bitcoin provider URL\n * @param bitcoinNetwork Bitcoin network (testnet or mainnet)\n * @returns Provider configuration if approved\n * @throws Error if provider is not approved for network\n */\nexport function validateBitcoinProvider(\n providerUrl: string,\n bitcoinNetwork: BitcoinNetwork\n): BitcoinProviderConfig {\n const providers = APPROVED_BITCOIN_PROVIDERS[bitcoinNetwork];\n const config = providers.find((p) => p.url === providerUrl);\n\n if (!config) {\n const approvedUrls = providers\n .map((p) => `${p.name} (${p.url})`)\n .join(\", \");\n throw new Error(\n `Bitcoin provider not approved for ${bitcoinNetwork}. ` +\n `Provided URL: ${providerUrl}. ` +\n `Approved providers: ${approvedUrls}`\n );\n }\n\n return config;\n}\n\n/**\n * Validate Bitcoin provider is approved\n *\n * Searches across all networks to find the provider.\n * In development mode, the caller should create their own config directly\n * (see mint/withdraw validators for the pattern).\n *\n * @param providerUrl Bitcoin provider URL\n * @returns Provider configuration with network auto-detected\n * @throws Error if provider is not approved for any network\n */\nexport function getBitcoinProviderConfig(\n providerUrl: string\n): BitcoinProviderConfig {\n // Search across ALL networks to find this provider\n for (const network of Object.values(BitcoinNetwork)) {\n const providers = APPROVED_BITCOIN_PROVIDERS[network];\n const config = providers.find((p) => p.url === providerUrl);\n\n if (config) {\n // Found it - return with network detected\n return config;\n }\n }\n\n // Provider not found in any network\n const allProviders = Object.entries(APPROVED_BITCOIN_PROVIDERS)\n .flatMap(([network, providers]) =>\n providers.map((p) => `${network}: ${p.name} (${p.url})`)\n )\n .join(\", \");\n\n throw new Error(\n `Bitcoin provider not approved. ` +\n `Provided URL: ${providerUrl}. ` +\n `Approved providers: ${allProviders}`\n );\n}\n\n/**\n * Get list of approved provider URLs for a chain\n *\n * Useful for displaying options to users or validating inputs.\n *\n * @param chain EVM chain\n * @returns Array of approved provider URLs for that chain's Bitcoin network\n */\nexport function getApprovedProvidersForChain(chain: EVMChain): string[] {\n const bitcoinNetwork = getBitcoinNetworkForChain(chain);\n return APPROVED_BITCOIN_PROVIDERS[bitcoinNetwork].map((p) => p.url);\n}\n\n/**\n * Get human-readable provider name from URL\n *\n * @param providerUrl Provider URL\n * @param bitcoinNetwork Bitcoin network\n * @returns Provider name or URL if not found\n */\nexport function getProviderName(\n providerUrl: string,\n bitcoinNetwork: BitcoinNetwork\n): string {\n const config = APPROVED_BITCOIN_PROVIDERS[bitcoinNetwork].find(\n (p) => p.url === providerUrl\n );\n return config ? config.name : providerUrl;\n}\n", "/**\n * Business Rules Math Module\n *\n * Pure calculation functions for Diamond Hands Protocol business logic.\n * These functions contain no side effects - they only perform calculations.\n *\n * Used by vault-snapshot and other modules for consistent math across the system.\n */\n\nimport {\n BASIS_POINTS_DENOMINATOR,\n EXPIRED_LOAN_MAX_ESCALATION_ITERATIONS,\n EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS,\n SATOSHIS_PER_BITCOIN,\n PRICE_ORACLE_DECIMALS,\n UCD_TOKEN_DECIMALS,\n SECONDS_PER_DAY,\n DAYS_PER_MONTH,\n} from \"../constants\";\n\n/**\n * Calculate term start timestamp from expiry timestamp and term length\n *\n * Contract stores expiryAt but not termStartTimestamp.\n * We derive it: termStart = expiry - (termLength * 30 days)\n *\n * Uses constants to avoid magic numbers and ensure accuracy.\n *\n * @param expiryTimestamp - Unix timestamp when term expires (0 if no term)\n * @param termLengthMonths - Term length in months\n * @returns Unix timestamp when term started (0 if no term)\n */\nexport function calculateTermStartFromExpiry(\n expiryTimestamp: number,\n termLengthMonths: number\n): number {\n // No term started if expiryAt is 0\n if (expiryTimestamp === 0) {\n return 0;\n }\n\n\n // Calculate term start\n // termStart = expiry - (months * 30 days/month * 86400 seconds/day)\n const termDurationSeconds =\n termLengthMonths * DAYS_PER_MONTH * SECONDS_PER_DAY;\n\n return expiryTimestamp - termDurationSeconds;\n}\n\n/**\n * Calculate term status from timestamps\n *\n * Determines:\n * - How long into the term we are\n * - Whether term is expired\n * - Days until expiry or days into grace period\n *\n * @param termStartTimestamp - Unix timestamp when term started (0 if not started)\n * @param selectedTermMonths - Term length in months\n * @returns Complete term status metrics\n */\nexport function calculateTermStatus(\n termStartTimestamp: number,\n selectedTermMonths: number\n): {\n termDurationDays: number;\n termLengthDays: number;\n isExpired: boolean;\n daysUntilExpiry: number;\n daysIntoGracePeriod: number;\n} {\n // If no term started yet (no debt), return zeros\n if (termStartTimestamp === 0) {\n return {\n termDurationDays: 0,\n termLengthDays: selectedTermMonths * 30,\n isExpired: false,\n daysUntilExpiry: selectedTermMonths * 30,\n daysIntoGracePeriod: 0,\n };\n }\n\n const now = Math.floor(Date.now() / 1000);\n const termLengthDays = selectedTermMonths * DAYS_PER_MONTH;\n const termDurationSeconds = now - termStartTimestamp;\n const termDurationDays = Math.floor(termDurationSeconds / SECONDS_PER_DAY);\n\n const isExpired = termDurationDays > termLengthDays;\n const daysUntilExpiry = Math.max(0, termLengthDays - termDurationDays);\n const daysIntoGracePeriod = Math.max(0, termDurationDays - termLengthDays);\n\n return {\n termDurationDays,\n termLengthDays,\n isExpired,\n daysUntilExpiry,\n daysIntoGracePeriod,\n };\n}\n\n/**\n * Expired-loan escalation parameters, read from LiquidationManager on-chain.\n */\nexport interface ExpiredLoanEscalationParams {\n /** `LiquidationManager.expiryLiquidationIncrementBps` \u2014 compound daily increment. */\n dailyIncrementBps: number;\n /** `LiquidationManager.expiredLoanGracePeriodDays` \u2014 days after expiry before escalation starts. */\n gracePeriodDays: number;\n /** `LiquidationManager.maxEscalatedThreshold` \u2014 cap in basis points. */\n maxEscalatedThresholdBps: number;\n}\n\nfunction requireNonNegativeInteger(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(\n `calculateLiquidationThreshold: ${name} must be a non-negative integer, got ${String(value)}`,\n );\n }\n}\n\n/**\n * Calculate the liquidation threshold in effect for a position.\n *\n * Active loan: the on-chain `LoanOperationsManager.liquidationThreshold()`.\n *\n * Expired loan: a transcription of the contract's\n * `ExpiredLoanCalculator.isExpiredLoanLiquidatableDynamic` (aligned 2026-10-27;\n * the previous quadratic 30-day curve signed liquidations the contract then\n * rejected, and refused ones it would have allowed):\n * - up to and including `gracePeriodDays` after expiry: the hardcoded 110% base;\n * - then, per escalation day, `t = floor(t * (1e4 + inc) / 1e4)`, capped at max;\n * - 365 or more escalation days clamp straight to max.\n * The Lean model `DH/Collateral.lean` (`litThreshold`) evaluates the same loop\n * and `tests/unit/lean-vectors.unit.test.ts` replays its vectors against this.\n *\n * @param isExpired - Whether the loan term has expired\n * @param daysSinceExpiry - Whole days past expiry (0 if not expired)\n * @param activeLoanThresholdBps - On-chain active-loan threshold\n * @param escalation - On-chain escalation parameters\n * @returns Liquidation threshold in basis points\n */\nexport function calculateLiquidationThreshold(\n isExpired: boolean,\n daysSinceExpiry: number,\n activeLoanThresholdBps: number,\n escalation: ExpiredLoanEscalationParams\n): number {\n if (!isExpired) {\n return activeLoanThresholdBps;\n }\n\n requireNonNegativeInteger(\"daysSinceExpiry\", daysSinceExpiry);\n requireNonNegativeInteger(\"dailyIncrementBps\", escalation.dailyIncrementBps);\n requireNonNegativeInteger(\"gracePeriodDays\", escalation.gracePeriodDays);\n requireNonNegativeInteger(\"maxEscalatedThresholdBps\", escalation.maxEscalatedThresholdBps);\n\n if (daysSinceExpiry <= escalation.gracePeriodDays) {\n return EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS;\n }\n\n const escalationDays = daysSinceExpiry - escalation.gracePeriodDays;\n if (escalationDays >= EXPIRED_LOAN_MAX_ESCALATION_ITERATIONS) {\n return escalation.maxEscalatedThresholdBps;\n }\n\n // Integer arithmetic throughout: every intermediate is below 2^53\n // (threshold <= max <= 1e9 and multiplier <= 2e4 keep the product under 2e13).\n const multiplier = BASIS_POINTS_DENOMINATOR + escalation.dailyIncrementBps;\n let threshold = EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS;\n for (let i = 0; i < escalationDays; i++) {\n threshold = Math.floor((threshold * multiplier) / BASIS_POINTS_DENOMINATOR);\n if (threshold >= escalation.maxEscalatedThresholdBps) {\n return escalation.maxEscalatedThresholdBps;\n }\n }\n return threshold;\n}\n\n/**\n * Calculate collateral metrics from BTC balance and debt\n *\n * Converts BTC balance to USD value and calculates collateral ratio.\n * Uses BigInt for all calculations to avoid JavaScript number precision issues.\n *\n * @param availableBTCSats - Available BTC balance in satoshis\n * @param btcPriceUsd - BTC price with 8 decimals (e.g., 10000000000000 = $100,000)\n * @param ucdDebt - UCD debt in wei (18 decimals)\n * @returns Collateral value in USD and ratio in basis points\n */\nexport function calculateCollateralMetrics(\n availableBTCSats: bigint,\n btcPriceUsd: bigint,\n ucdDebt: bigint\n): {\n collateralValueUsd: bigint;\n collateralRatioBps: number;\n} {\n // Convert available BTC to USD value using BigInt math\n // btcPriceUsd has 8 decimals: $100,000 = 10000000000000n\n // availableBTCSats is in satoshis: 1 BTC = 100_000_000n sats\n // ucdDebt has 18 decimals (ERC20 wei)\n //\n // Formula: (sats * priceWith8Decimals) / (SATOSHIS_PER_BITCOIN * PRICE_ORACLE_DECIMALS)\n // This gives us USD value with 0 decimals (whole dollars)\n\n // Calculate collateral value in USD (no decimals) - ALWAYS calculate, even with no debt\n const collateralValueUsd =\n (availableBTCSats * btcPriceUsd) /\n (SATOSHIS_PER_BITCOIN * PRICE_ORACLE_DECIMALS);\n\n // If no debt, return max safe collateral ratio\n if (ucdDebt === 0n) {\n return {\n collateralValueUsd,\n collateralRatioBps: Number.MAX_SAFE_INTEGER,\n };\n }\n\n // Calculate collateral ratio in basis points\n // Ratio = (collateral / debt) * 10000\n // Example: $20,000 collateral / $10,000 debt = 2.0 = 20000 bps (200%)\n //\n // CRITICAL: We must preserve precision by doing multiplication BEFORE division\n // Use debt in wei (18 decimals) directly, adjust for collateral being in whole dollars\n //\n // Formula: (collateralUSD * UCD_TOKEN_DECIMALS * 10000) / ucdDebt\n\n const ratioBigInt =\n (collateralValueUsd * UCD_TOKEN_DECIMALS * 10000n) / ucdDebt;\n\n // Convert to number - safe because ratio will be small (typically 10000-30000)\n const collateralRatioBps = Number(ratioBigInt);\n\n return {\n collateralValueUsd,\n collateralRatioBps,\n };\n}\n\n/**\n * Check if adding additional debt would maintain required collateral ratio\n *\n * Used by minting authorization to validate new mints.\n *\n * @param collateralValueUsd - Current collateral value in USD (whole dollars)\n * @param currentDebt - Current UCD debt in wei (18 decimals)\n * @param additionalDebt - Additional UCD debt to add in wei (18 decimals)\n * @param requiredRatioBps - Required collateral ratio in basis points (e.g., 11000 for 110%)\n * @returns True if sufficient collateral exists after adding debt\n */\nexport function hasSufficientCollateralForDebt(\n collateralValueUsd: bigint,\n currentDebt: bigint,\n additionalDebt: bigint,\n requiredRatioBps: number\n): boolean {\n // Calculate new total debt\n const newTotalDebt = currentDebt + additionalDebt;\n\n // If no debt after addition, always sufficient\n if (newTotalDebt === 0n) {\n return true;\n }\n\n // Calculate new collateral ratio using precise BigInt math\n // Must multiply BEFORE dividing to preserve precision (same as calculateCollateralMetrics)\n const newCollateralRatioBps = Number(\n (collateralValueUsd * UCD_TOKEN_DECIMALS * 10000n) / newTotalDebt\n );\n\n return newCollateralRatioBps >= requiredRatioBps;\n}\n\n/**\n * Calculate fee from amount using basis points\n *\n * Bulletproof fee calculation with validation.\n * Multiply before divide to maintain precision.\n *\n * @param amount - Principal amount (in wei or sats)\n * @param feeBps - Fee in basis points (e.g., 50 = 0.5%)\n * @returns Fee amount in same units as input\n *\n * @example\n * calculateFeeBps(1000000000000000000n, 50) // 0.5% of 1 ETH\n * // Returns: 5000000000000000n (0.005 ETH)\n */\nexport function calculateFeeBps(amount: bigint, feeBps: number): bigint {\n if (amount < 0n) {\n throw new Error(\"Amount cannot be negative\");\n }\n if (feeBps < 0 || feeBps > 10000) {\n throw new Error(\n \"Fee basis points must be between 0 and 10000 (0% to 100%)\"\n );\n }\n\n // Multiply first to preserve precision, then divide\n const fee = (amount * BigInt(feeBps)) / 10000n;\n return fee;\n}\n\n/**\n * Calculate USD value of BTC amount\n *\n * Converts satoshis to USD using price with 8 decimals.\n * Result maintains 8 decimal precision.\n *\n * @param btcSats - Bitcoin amount in satoshis\n * @param btcPriceUsd8Decimals - BTC price with 8 decimals (e.g., 9800000000000n = $98,000)\n * @returns USD value with 8 decimals\n *\n * @example\n * calculateBtcValueUsd(100000000n, 9800000000000n) // 1 BTC at $98,000\n * // Returns: 9800000000000n ($98,000 with 8 decimals)\n */\nexport function calculateBtcValueUsd(\n btcSats: bigint,\n btcPriceUsd8Decimals: bigint\n): bigint {\n if (btcSats < 0n) {\n throw new Error(\"BTC amount cannot be negative\");\n }\n if (btcPriceUsd8Decimals <= 0n) {\n throw new Error(\"BTC price must be positive\");\n }\n\n // btcSats: satoshis (no decimals)\n // btcPriceUsd8Decimals: price with 8 decimals\n // Formula: (sats * priceWith8Decimals) / SATOSHIS_PER_BITCOIN\n // Result: USD value with 8 decimals\n const valueUsd = (btcSats * btcPriceUsd8Decimals) / SATOSHIS_PER_BITCOIN;\n return valueUsd;\n}\n\n/**\n * Calculate collateral ratio in basis points (with 8-decimal collateral and 18-decimal debt)\n *\n * Used for UCD mint validation where collateral is in USD (8 decimals)\n * and debt is in UCD wei (18 decimals).\n *\n * @param collateralValueUsd8Decimals - Collateral value in USD with 8 decimals\n * @param debtUsd18Decimals - Debt amount in USD with 18 decimals (UCD wei)\n * @returns Collateral ratio in basis points (e.g., 20000 = 200%)\n *\n * @example\n * calculateCollateralRatioBps(9800000000000n, 4000000000000000000000n)\n * // $98,000 collateral / $4,000 debt = 24.5 = 2450% = 24500 bps\n * // Returns: 24500\n *\n * Note: Returns MAX_SAFE_INTEGER for extreme over-collateralization cases\n */\nexport function calculateCollateralRatioBps(\n collateralValueUsd8Decimals: bigint,\n debtUsd18Decimals: bigint\n): number {\n if (collateralValueUsd8Decimals < 0n) {\n throw new Error(\"Collateral value cannot be negative\");\n }\n if (debtUsd18Decimals <= 0n) {\n throw new Error(\"Debt must be positive to calculate ratio\");\n }\n\n // Scale collateral from 8 decimals to 18 decimals: multiply by 10^10\n const scaledCollateral = collateralValueUsd8Decimals * 10000000000n;\n\n // Ratio in basis points = (collateral / debt) * 10000\n // Multiply first to preserve precision\n const ratioBps = (scaledCollateral * 10000n) / debtUsd18Decimals;\n\n // Convert to number for comparison\n const ratioBpsNumber = Number(ratioBps);\n\n // Sanity check: ratio should be non-negative\n // Cap at MAX_SAFE_INTEGER for extreme over-collateralization (prevents Infinity)\n if (ratioBpsNumber < 0) {\n throw new Error(\n `Collateral ratio out of bounds: ${ratioBpsNumber} bps (${\n ratioBpsNumber / 100\n }%)`\n );\n }\n\n // Cap at MAX_SAFE_INTEGER to prevent Infinity edge cases\n if (!isFinite(ratioBpsNumber) || ratioBpsNumber > Number.MAX_SAFE_INTEGER) {\n return Number.MAX_SAFE_INTEGER;\n }\n\n return ratioBpsNumber;\n}\n\n/**\n * Check if collateral ratio meets minimum requirement\n *\n * @param collateralValueUsd8Decimals - Collateral value in USD with 8 decimals\n * @param debtUsd18Decimals - Debt amount in USD with 18 decimals\n * @param minimumRatioBps - Minimum required ratio in basis points (e.g., 20000 = 200%)\n * @returns True if collateral is sufficient\n *\n * @example\n * isCollateralSufficient(20000000000000n, 10000000000000000000000n, 20000)\n * // $200,000 collateral / $10,000 debt = 2000% >= 200%\n * // Returns: true\n */\nexport function isCollateralSufficient(\n collateralValueUsd8Decimals: bigint,\n debtUsd18Decimals: bigint,\n minimumRatioBps: number\n): boolean {\n if (minimumRatioBps < 0 || minimumRatioBps > 1000000) {\n throw new Error(\n \"Minimum ratio must be between 0 and 1000000 bps (0% to 10000%)\"\n );\n }\n\n const actualRatioBps = calculateCollateralRatioBps(\n collateralValueUsd8Decimals,\n debtUsd18Decimals\n );\n\n return actualRatioBps >= minimumRatioBps;\n}\n\n/**\n * Convert basis points to percentage (for display)\n *\n * @param basisPoints - Value in basis points\n * @returns Percentage as number (e.g., 20000 bps => 200)\n *\n * @example\n * bpsToPercent(20000) // Returns: 200\n * bpsToPercent(50) // Returns: 0.5\n */\nexport function bpsToPercent(basisPoints: number): number {\n return basisPoints / 100;\n}\n\n/**\n * Refuse an AGENT-authorized withdrawal that would take the position below the borrower's\n * delegation floor.\n *\n * WHY THIS IS A NAMED FUNCTION. It is the enforcement point whose absence makes\n * `agent-module-executor` refuse `mode=\"execute\"` for `op=\"withdraw\"` outright. That guard's\n * removal condition is *\"amount-vs-floor enforcement is actually wired somewhere in the chain and\n * covered by a test that proves a floor-violating amount is refused\"* \u2014 so the invariant needs a\n * name and a test, not an inline `if` inside a 900-line action.\n *\n * SCOPE. `effectiveFloorBps` is the borrower's own limit on how far an AGENT may take the\n * position, clamped by the governance minimum, and it is populated ONLY when the Safe-agent arm\n * authorized the call (`checkSafeAgentWithdrawAuthorization` sets `path.outcome`). A\n * borrower-signed or EIP-1271 withdrawal leaves it 0 and is governed by the protocol's\n * liquidation threshold alone \u2014 hence the `<= 0` early return, which is the non-agent path and\n * not a bypass.\n *\n * ZERO DEBT IS OUT OF SCOPE, deliberately. The caller applies this only where `ucdDebt > 0`,\n * because the floor is a RATIO and the post-withdrawal ratio is infinite for any amount once debt\n * is zero \u2014 there is nothing for it to bound, the protocol has no claim on the collateral, and\n * gating the scope on debt would leave a repaid multi-sig unable to retrieve its own BTC inside\n * the 60s `strictCurrentQuantum` window. What bounds the zero-debt case is the quorum-gated\n * destination allowlist. Never describe this floor to a user as a cap on withdrawal size.\n *\n * @param effectiveFloorBps Post-withdrawal collateral-ratio floor from the delegation record.\n * 0 (or negative) means \"no agent floor applies\" \u2014 see SCOPE above.\n * @param postWithdrawalCollateralRatioBps The ratio the position would hold AFTER this withdrawal.\n * @throws When an agent floor applies and the withdrawal would breach it.\n */\nexport function assertAgentWithdrawFloor(\n effectiveFloorBps: number,\n postWithdrawalCollateralRatioBps: number\n): void {\n if (!Number.isFinite(effectiveFloorBps) || effectiveFloorBps <= 0) return;\n\n // A non-finite ratio here would compare false and silently permit the withdrawal, so it is\n // refused explicitly: an unknown post-withdrawal position is not a safe one to act on.\n if (!Number.isFinite(postWithdrawalCollateralRatioBps)) {\n throw new Error(\n `Agent withdrawal refused: post-withdrawal collateral ratio is not a finite number ` +\n `(${String(postWithdrawalCollateralRatioBps)}) \u2014 refusing to evaluate the delegation ` +\n `floor of ${bpsToPercent(effectiveFloorBps)}% against it`\n );\n }\n\n // Strictly below: a withdrawal landing exactly ON the floor is permitted, matching\n // `isCollateralSufficient` (`>= minimumRatioBps`) and the registry's own `canWithdraw`\n // comparison. The two must not disagree by one basis point.\n if (postWithdrawalCollateralRatioBps < effectiveFloorBps) {\n throw new Error(\n `Agent withdrawal refused: post-withdrawal collateral ratio ${bpsToPercent(\n postWithdrawalCollateralRatioBps\n )}% is below the delegation floor ${bpsToPercent(effectiveFloorBps)}%`\n );\n }\n}\n", "/**\n * The one place a LIT Action turns an RPC URL into an ethers connection.\n *\n * dRPC authenticates either with the key in the URL (`?dkey=<key>`) or with a\n * `Drpc-Key` header on a keyless URL. ethers puts the request URL into every\n * provider error, and a LIT Action's errors travel back through Chipotle into\n * server logs and API responses \u2014 so a keyed URL is a key in every failed read.\n * The header form keeps the key out of the URL, and therefore out of the errors.\n *\n * The caller supplies the key as the `drpcKey` jsParam. It is a secret aimed at\n * one provider, so this module only ever attaches it to a dRPC host: the host\n * check sits in `evmRpcConnection`, where the header is built, so no code path\n * can send the key anywhere else, and only over https. A keyed `?dkey=` URL is\n * still accepted on its own (callers move over after the new CIDs are live), but\n * its key is moved into the header too; sending both is refused.\n */\n\n/** dRPC's hosts. Both are on APPROVED_EVM_RPC_DOMAINS; `drpc.live` is the faster load balancer. */\nconst DRPC_DOMAINS = [\"drpc.org\", \"drpc.live\"];\n\n/** dRPC's header for the API key. */\nexport const DRPC_KEY_HEADER = \"Drpc-Key\";\n\n/** dRPC keys are URL-safe base64-like strings (44 chars today). Never echoed in errors. */\nconst DRPC_KEY_PATTERN = /^[A-Za-z0-9_-]{16,128}$/;\n\n/** The ethers v5 `ConnectionInfo` subset the actions use. */\nexport interface EvmRpcConnection {\n url: string;\n headers?: Record<string, string>;\n timeout?: number;\n}\n\nfunction isDrpcHost(hostname: string): boolean {\n return DRPC_DOMAINS.some(\n (domain) => hostname === domain || hostname.endsWith(`.${domain}`),\n );\n}\n\nfunction assertKeyFormat(key: unknown, label: string): asserts key is string {\n if (typeof key !== \"string\" || !DRPC_KEY_PATTERN.test(key)) {\n throw new Error(\n `Invalid ${label}: expected 16-128 characters of [A-Za-z0-9_-]`,\n );\n }\n}\n\n/** A key only ever travels encrypted: a plaintext `http://` dRPC URL is refused. */\nfunction assertHttps(url: URL): void {\n if (url.protocol !== \"https:\") {\n throw new Error(\n `A dRPC key is only sent over https, but the RPC URL scheme is \"${url.protocol}\"`,\n );\n }\n}\n\n/**\n * Validate a caller-supplied `drpcKey` against the RPC URL it will authenticate.\n *\n * Returns `undefined` when no key was supplied. Throws when the key is malformed,\n * when `rpcUrl` is not an https dRPC URL, or when `rpcUrl` already carries\n * `?dkey=`. Call it right after the URL itself has been validated, so a bad key\n * fails the action before any read.\n */\nexport function resolveDrpcKey(\n rpcUrl: string,\n drpcKey: unknown,\n): string | undefined {\n if (drpcKey === undefined) {\n return undefined;\n }\n assertKeyFormat(drpcKey, '\"drpcKey\"');\n const url = new URL(rpcUrl);\n if (!isDrpcHost(url.hostname)) {\n throw new Error(\n `\"drpcKey\" is only sent to dRPC, but the RPC host is \"${url.hostname}\" (expected ${DRPC_DOMAINS.join(\" or \")})`,\n );\n }\n assertHttps(url);\n if (url.searchParams.has(\"dkey\")) {\n throw new Error(\n '\"drpcKey\" and a keyed rpcUrl (?dkey=) are mutually exclusive \u2014 send one',\n );\n }\n return drpcKey;\n}\n\n/**\n * The Lit node's own RPC endpoint for `chain` \u2014 the fallback when the caller\n * sent no `rpcUrl`. A `drpcKey` authenticates the caller's dRPC URL only, so it\n * is refused here rather than attached to an endpoint the caller did not choose\n * (which may itself be a dRPC host).\n */\nexport async function litNodeRpcUrl(\n chain: string,\n drpcKey: unknown,\n): Promise<string> {\n if (drpcKey !== undefined) {\n throw new Error(\n '\"drpcKey\" was supplied without an \"rpcUrl\" \u2014 the key only authenticates a caller-supplied dRPC rpcUrl, never the Lit node\\'s own endpoint',\n );\n }\n // @ts-ignore - Lit.Actions available in LIT runtime\n return Lit.Actions.getRpcUrl({ chain });\n}\n\n/**\n * The ethers connection for `rpcUrl`: the dRPC key, if any, goes in the\n * `Drpc-Key` header. Re-validates the key here so the header can only ever be\n * attached to an https dRPC URL, whatever the call site did before.\n *\n * A legacy keyed dRPC URL (`?dkey=<key>`) is still accepted, but its key is\n * moved out of the URL into the header, so a failed read's error carries a\n * keyless URL either way. A `dkey` on a non-dRPC host, or more than one `dkey`,\n * is refused rather than passed through.\n */\nexport function evmRpcConnection(\n rpcUrl: string,\n drpcKey?: string,\n timeout?: number,\n): EvmRpcConnection {\n const connection: EvmRpcConnection = { url: rpcUrl };\n const key = resolveDrpcKey(rpcUrl, drpcKey);\n if (key !== undefined) {\n connection.headers = { [DRPC_KEY_HEADER]: key };\n } else {\n const url = new URL(rpcUrl);\n const legacyKeys = url.searchParams.getAll(\"dkey\");\n if (legacyKeys.length > 1) {\n throw new Error(\n `rpcUrl carries ${legacyKeys.length} \"dkey\" parameters \u2014 send exactly one dRPC key`,\n );\n }\n if (legacyKeys.length === 1 && !isDrpcHost(url.hostname)) {\n throw new Error(\n `rpcUrl carries a dRPC key (?dkey=) but the RPC host is \"${url.hostname}\" \u2014 a dRPC key is only sent to ${DRPC_DOMAINS.join(\" or \")}`,\n );\n }\n if (legacyKeys.length === 1) {\n const legacyKey = legacyKeys[0];\n assertKeyFormat(legacyKey, \"dRPC key in rpcUrl (?dkey=)\");\n assertHttps(url);\n url.searchParams.delete(\"dkey\");\n connection.url = url.toString();\n connection.headers = { [DRPC_KEY_HEADER]: legacyKey };\n }\n }\n if (timeout !== undefined) {\n connection.timeout = timeout;\n }\n return connection;\n}\n", "/**\n * Protocol Parameters Module\n *\n * Fetches protocol parameters directly from smart contracts.\n * This ensures LIT actions always use current values set by protocol governance.\n *\n * Parameters fetched:\n * - Liquidation threshold (from LoanOperationsManager)\n * - Term-specific fees (from TermManager)\n */\n\nimport { LIT_ACTION_ETH_RPC_TIMEOUT_MS } from \"../constants\";\nimport { evmRpcConnection, litNodeRpcUrl } from \"./evm-rpc\";\n\n/**\n * Configuration for protocol parameters module\n */\nexport interface ProtocolParametersConfig {\n termManagerAddress: string;\n loanOpsManagerAddress: string;\n liquidationManagerAddress: string;\n chain: string;\n chainId: number;\n rpcUrl?: string; // Optional: for testing with local Hardhat/Anvil\n drpcKey?: string; // dRPC key for rpcUrl, sent in the Drpc-Key header (see evm-rpc)\n}\n\n/**\n * Term fees structure\n */\nexport interface TermFees {\n originationFeeBps: number;\n extensionFeeBps: number;\n}\n\n/**\n * Protocol Parameters Module\n *\n * Fetches governance-controlled parameters from smart contracts\n */\nexport class ProtocolParametersModule {\n private termManagerAddress: string;\n private loanOpsManagerAddress: string;\n private liquidationManagerAddress: string;\n private chain: string;\n private chainId: number;\n private rpcUrl?: string;\n private drpcKey?: string;\n\n constructor(config: ProtocolParametersConfig) {\n this.termManagerAddress = config.termManagerAddress;\n this.loanOpsManagerAddress = config.loanOpsManagerAddress;\n this.liquidationManagerAddress = config.liquidationManagerAddress;\n this.chain = config.chain;\n this.chainId = config.chainId;\n this.rpcUrl = config.rpcUrl;\n this.drpcKey = config.drpcKey;\n }\n\n /**\n * Get liquidation threshold from LoanOperationsManager\n *\n * @returns Liquidation threshold in basis points\n */\n async getLiquidationThreshold(): Promise<number> {\n try {\n // Get RPC URL - either from config (for local testing) or from Lit runtime\n let rpcUrl: string;\n if (this.rpcUrl) {\n rpcUrl = this.rpcUrl;\n } else {\n rpcUrl = await litNodeRpcUrl(this.chain, this.drpcKey);\n }\n // @ts-ignore - ethers available in LIT runtime\n // StaticJsonRpcProvider with explicit network bypasses auto-detection (required for ngrok URLs)\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n {\n name: \"any\",\n chainId: this.chainId,\n },\n );\n const abi = [\n {\n inputs: [],\n name: \"liquidationThreshold\",\n outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n ];\n // @ts-ignore - ethers available in LIT runtime\n const contract = new ethers.Contract(\n this.loanOpsManagerAddress,\n abi,\n provider\n );\n const result = await contract.liquidationThreshold();\n return Number(result.toString());\n } catch (error: any) {\n console.error(\n \"[ProtocolParameters] Error fetching liquidation threshold:\",\n error.message\n );\n throw new Error(\n `Failed to fetch liquidation threshold: ${error.message}`\n );\n }\n }\n\n /**\n * Get term-specific fees from TermManager\n *\n * @param termMonths Loan term in months\n * @returns Term fees (origination and extension) in basis points\n */\n async getTermFees(termMonths: number): Promise<TermFees> {\n try {\n // Get RPC URL - either from config (for local testing) or from Lit runtime\n let rpcUrl: string;\n if (this.rpcUrl) {\n rpcUrl = this.rpcUrl;\n } else {\n rpcUrl = await litNodeRpcUrl(this.chain, this.drpcKey);\n }\n // @ts-ignore - ethers available in LIT runtime\n // StaticJsonRpcProvider with explicit network bypasses auto-detection (required for ngrok URLs)\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n {\n name: \"any\",\n chainId: this.chainId,\n },\n );\n const abi = [\n {\n inputs: [\n { internalType: \"uint256\", name: \"_termMonths\", type: \"uint256\" },\n ],\n name: \"getTermFees\",\n outputs: [\n { internalType: \"uint88\", name: \"originationFee\", type: \"uint88\" },\n { internalType: \"uint88\", name: \"extensionFee\", type: \"uint88\" },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n ];\n // @ts-ignore - ethers available in LIT runtime\n const contract = new ethers.Contract(\n this.termManagerAddress,\n abi,\n provider\n );\n const result = await contract.getTermFees(termMonths);\n return {\n originationFeeBps: Number(\n result.originationFee?.toString?.() ??\n result[0]?.toString?.() ??\n result[0]\n ),\n extensionFeeBps: Number(\n result.extensionFee?.toString?.() ??\n result[1]?.toString?.() ??\n result[1]\n ),\n };\n } catch (error: any) {\n console.error(\n \"[ProtocolParameters] Error fetching term fees:\",\n error.message\n );\n throw new Error(`Failed to fetch term fees: ${error.message}`);\n }\n }\n\n /**\n * Get authorized spends hash from contract\n *\n * Fetches the cryptographic hash of authorized Bitcoin spends for a position.\n * This hash is used in authorization messages to prevent race conditions.\n *\n * @param positionId - Position identifier (bytes32)\n * @returns Authorized spends hash (bytes32)\n */\n async getAuthorizedSpendsHash(positionId: string): Promise<string> {\n try {\n const rpcUrl =\n this.rpcUrl || (await litNodeRpcUrl(this.chain, this.drpcKey));\n\n // @ts-ignore - ethers available in LIT runtime\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n {\n name: \"any\",\n chainId: this.chainId,\n },\n );\n\n // Convert positionId to bytes32\n const positionIdBytes32 = positionId.startsWith(\"0x\")\n ? positionId\n : `0x${positionId.padStart(64, \"0\")}`;\n\n // Call getAuthorizedSpendsHash(bytes32 positionId) on LoanOperationsManager\n // @ts-ignore - ethers available in LIT runtime\n const contract = new ethers.Contract(\n this.loanOpsManagerAddress,\n [\n {\n inputs: [{ name: \"positionId\", type: \"bytes32\" }],\n name: \"getAuthorizedSpendsHash\",\n outputs: [{ name: \"\", type: \"bytes32\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n ],\n provider\n );\n\n const hash = await contract.getAuthorizedSpendsHash(positionIdBytes32);\n return hash;\n } catch (error: any) {\n console.error(\n \"[ProtocolParameters] Error fetching authorized spends hash:\",\n error.message\n );\n throw new Error(\n `Failed to fetch authorized spends hash: ${error.message}`\n );\n }\n }\n\n /**\n * Read one `uint256` view from LiquidationManager.\n */\n private async readLiquidationManagerUint(\n fnName: \"maxEscalatedThreshold\" | \"expiryLiquidationIncrementBps\" | \"expiredLoanGracePeriodDays\",\n description: string,\n ): Promise<number> {\n try {\n let rpcUrl: string;\n if (this.rpcUrl) {\n rpcUrl = this.rpcUrl;\n } else {\n rpcUrl = await litNodeRpcUrl(this.chain, this.drpcKey);\n }\n // @ts-ignore - ethers available in LIT runtime\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n {\n name: \"any\",\n chainId: this.chainId,\n },\n );\n const abi = [\n {\n inputs: [],\n name: fnName,\n outputs: [{ internalType: \"uint256\", name: \"\", type: \"uint256\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n ];\n // @ts-ignore - ethers available in LIT runtime\n const contract = new ethers.Contract(\n this.liquidationManagerAddress,\n abi,\n provider\n );\n const result = await contract[fnName]();\n return Number(result.toString());\n } catch (error: any) {\n console.error(\n `[ProtocolParameters] Error fetching ${description}:`,\n error.message\n );\n throw new Error(\n `Failed to fetch ${description}: ${error.message}`\n );\n }\n }\n\n /**\n * Get max escalated threshold from LiquidationManager\n *\n * This is the governance-controlled ceiling for expired loan liquidation thresholds.\n *\n * @returns Max escalated threshold in basis points\n */\n async getMaxEscalatedThreshold(): Promise<number> {\n return this.readLiquidationManagerUint(\"maxEscalatedThreshold\", \"max escalated threshold\");\n }\n\n /**\n * Get the compound daily increment applied to an expired loan's liquidation\n * threshold (`LiquidationManager.expiryLiquidationIncrementBps`).\n *\n * @returns Daily increment in basis points\n */\n async getExpiryLiquidationIncrementBps(): Promise<number> {\n return this.readLiquidationManagerUint(\"expiryLiquidationIncrementBps\", \"expiry liquidation increment\");\n }\n\n /**\n * Get the number of days after expiry before escalation begins\n * (`LiquidationManager.expiredLoanGracePeriodDays`).\n *\n * @returns Grace period in days\n */\n async getExpiredLoanGracePeriodDays(): Promise<number> {\n return this.readLiquidationManagerUint(\"expiredLoanGracePeriodDays\", \"expired loan grace period\");\n }\n}\n\n/**\n * Factory function to create protocol parameters module\n */\nexport function createProtocolParametersModule(\n config: ProtocolParametersConfig\n): ProtocolParametersModule {\n return new ProtocolParametersModule(config);\n}\n", "/**\n * Vault-address parsing \u2014 single source of truth for turning the raw on-chain\n * `Position.vaultAddress` string into the Bitcoin address for a chain.\n *\n * The contract stores either a plain address string or a JSON object keyed by\n * Bitcoin network (`{\"mainnet\":\"bc1\u2026\",\"testnet\":\"m\u2026\",\"regtest\":\"bcrt1\u2026\"}`).\n * Extracted from `vault-snapshot.ts` (remediation P6/#7b) so the phase-2\n * signer can bind its derived PKP address to the on-chain vault address using\n * exactly the same parse the snapshot layer uses.\n */\n\nimport {\n BitcoinNetwork,\n EVMChain,\n getBitcoinNetworkForChain,\n} from \"../constants\";\n\n/**\n * Strip a storage network prefix (`REGTEST_` / `TESTNET_` / `MAINNET_`) from a\n * Bitcoin address. Parity with BitcoinDataProvider's private helper.\n */\nexport function stripNetworkPrefix(address: string): string {\n const prefixPattern = /^(REGTEST_|TESTNET_|MAINNET_)/;\n return address.replace(prefixPattern, \"\");\n}\n\n/**\n * Parse vault address based on format and network.\n *\n * Supports two formats:\n * 1. Single string: \"mqM3ZR2N6DzZkafSdFqxEAkWovAU3uYTAN\"\n * 2. JSON object: {\"mainnet\":\"bc1q...\",\"testnet\":\"mqM3...\"}\n *\n * @param rawVaultAddress Raw vault address from contract\n * @param chain Validated EVM chain (sepolia, ethereum, hardhat)\n * @returns Parsed Bitcoin address for the appropriate network\n */\nexport function parseVaultAddress(\n rawVaultAddress: string,\n chain: string,\n): string | undefined {\n // Try parsing as JSON first\n try {\n const parsed = JSON.parse(rawVaultAddress);\n\n // If it's an object with network keys\n if (typeof parsed === \"object\" && parsed !== null) {\n // Test chains never fall back to the mainnet key: that would bind a test\n // position to a mainnet address (review 2026-07-15 P1). With no test-network\n // key the result is undefined, which callers refuse.\n // Special case: Sepolia uses regtest Bitcoin addresses for local development\n const chainLower = chain.toLowerCase();\n if (chainLower === \"sepolia\") {\n return parsed.regtest || parsed.testnet || undefined;\n }\n\n // For other chains, map by the chain's Bitcoin network.\n const bitcoinNetwork = getBitcoinNetworkForChain(chain as EVMChain);\n if (bitcoinNetwork === BitcoinNetwork.REGTEST) {\n return parsed.regtest || parsed.testnet || undefined;\n }\n if (bitcoinNetwork === BitcoinNetwork.TESTNET) {\n return parsed.testnet || parsed.regtest || undefined;\n }\n // Mainnet: only the mainnet key is acceptable \u2014 a testnet/regtest\n // address must never bind a mainnet position. May be undefined; callers\n // MUST check (a JSON vault record without the required network key is a\n // data error, not something to paper over).\n return parsed.mainnet;\n }\n } catch (e) {\n // Not JSON, continue to return as plain string\n }\n\n // Return as-is if it's a plain string\n return rawVaultAddress;\n}\n", "/**\n * Vault Snapshot Module - The Brain\n *\n * This module calculates ALL vault intelligence from simple contract state.\n * It is the single source of truth for vault health metrics.\n *\n * Architecture:\n * - Smart Contract: Stores simple state (ucdDebt, termStartTimestamp, btcCollateralSats)\n * - This Module: Calculates everything else (ratios, thresholds, risk metrics)\n *\n * The vault-snapshot is used by:\n * - Minting authorization (check if sufficient collateral)\n * - Liquidation detection (check if under threshold)\n * - UI display (show vault health to user)\n * - Repayment calculations (how much can be repaid)\n */\n\nimport {\n VaultSnapshot,\n VaultSnapshotConfig,\n} from \"../interfaces/chunks/vault-snapshot.i\";\nimport {\n calculateTermStatus,\n calculateLiquidationThreshold,\n calculateCollateralMetrics,\n hasSufficientCollateralForDebt,\n calculateTermStartFromExpiry,\n} from \"./business-rules-math.module\";\nimport { createProtocolParametersModule } from \"./protocol-parameters.module\";\nimport { parseVaultAddress } from \"./vault-address\";\nimport {\n validateChain,\n LIT_ACTION_ETH_RPC_TIMEOUT_MS,\n} from \"../constants\";\nimport { evmRpcConnection, litNodeRpcUrl } from \"./evm-rpc\";\n\n/**\n * NOTE: In the LIT Actions runtime, `ethers` is provided as a global.\n * We declare it here so TypeScript can type-check this module when building\n * the package without bundling ethers or importing it as a module.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\n\n/**\n * Vault Snapshot Module\n *\n * The intelligence layer that transforms simple contract state into\n * comprehensive vault health metrics.\n */\nexport class VaultSnapshotModule {\n private config: VaultSnapshotConfig;\n\n constructor(config: VaultSnapshotConfig) {\n // No default: a missing chainId used to become 1 (mainnet) for the protocol-parameter\n // reads and \"detect it\" for the position read \u2014 loan-vault-btc-balance omitted it on\n // every chain. Fail at construction instead.\n if (!Number.isInteger(config.chainId) || config.chainId <= 0) {\n throw new Error(`VaultSnapshotModule requires a positive integer chainId, got ${String(config.chainId)}`);\n }\n this.config = config;\n }\n\n /**\n * Get complete vault snapshot\n *\n * This is the main entry point. Returns everything you need to know\n * about a vault's health in a single call.\n *\n * @param positionId - Position to snapshot\n * @returns Complete VaultSnapshot with all metrics\n */\n async getVaultSnapshot(positionId: string): Promise<VaultSnapshot> {\n // 1. Query contract for position state\n const positionState = await this.queryPositionState(positionId);\n\n console.log(\n `[Vault Snapshot] Raw vault address from contract: \"${positionState.vaultAddress}\"`\n );\n\n // 2 & 3. Get available balance and BTC price in parallel (saves ~10s on cold starts)\n const [balanceResult, btcPriceUsd] = await Promise.all([\n this.config.vaultBalance.calculateTrustedBalance(\n positionId,\n positionState.vaultAddress\n ),\n this.config.priceOracle.getBTCPrice(),\n ]);\n\n // 4. Fetch protocol parameters from smart contracts\n const protocolParams = createProtocolParametersModule({\n termManagerAddress: this.config.termManagerAddress,\n loanOpsManagerAddress: this.config.loanOpsManagerAddress,\n liquidationManagerAddress: this.config.liquidationManagerAddress,\n chain: this.config.chain,\n chainId: this.config.chainId,\n rpcUrl: this.config.rpcUrl,\n drpcKey: this.config.drpcKey,\n });\n\n // Fetch liquidation threshold, max escalated threshold, and term fees in parallel\n // Use termOverride if provided (for extensions), otherwise use position's current term\n const termForFees = this.config.termOverride ?? positionState.selectedTerm;\n const [\n liquidationThresholdBps,\n maxEscalatedThresholdBps,\n expiryLiquidationIncrementBps,\n expiredLoanGracePeriodDays,\n termFees,\n ] = await Promise.all([\n protocolParams.getLiquidationThreshold(),\n protocolParams.getMaxEscalatedThreshold(),\n protocolParams.getExpiryLiquidationIncrementBps(),\n protocolParams.getExpiredLoanGracePeriodDays(),\n protocolParams.getTermFees(termForFees),\n ]);\n\n // 5. Calculate term status\n const termStatus = calculateTermStatus(\n positionState.termStartTimestamp,\n positionState.selectedTerm\n );\n\n // 6. Calculate liquidation threshold \u2014 on-chain values for both active and expired\n // loans; the expired curve is the contract's own compound escalation.\n const currentLiquidationThreshold = calculateLiquidationThreshold(\n termStatus.isExpired,\n termStatus.daysIntoGracePeriod,\n liquidationThresholdBps,\n {\n dailyIncrementBps: expiryLiquidationIncrementBps,\n gracePeriodDays: expiredLoanGracePeriodDays,\n maxEscalatedThresholdBps,\n }\n );\n\n // 7. Calculate collateral ratio (using BigInt for precision)\n const collateralMetrics = calculateCollateralMetrics(\n balanceResult.availableBalance,\n btcPriceUsd,\n positionState.ucdDebt\n );\n\n // 8. Calculate liquidation risk\n const isLiquidatable =\n collateralMetrics.collateralRatioBps < currentLiquidationThreshold;\n const marginToLiquidationBps =\n collateralMetrics.collateralRatioBps - currentLiquidationThreshold;\n\n // 9. Assemble complete snapshot\n return {\n // Raw state\n positionId: positionState.positionId,\n pkpId: positionState.pkpId,\n borrower: positionState.borrower,\n vaultAddress: positionState.vaultAddress,\n ucdDebt: positionState.ucdDebt,\n termStartTimestamp: positionState.termStartTimestamp,\n selectedTerm: positionState.selectedTerm,\n status: positionState.status, // Loan status enum value (0-7)\n expiryAt: positionState.expiryAt, // Loan expiry timestamp\n previousExpiryAt: positionState.previousExpiryAt, // expiryAt before last renewal; 0 if never renewed\n totalTerm: positionState.totalTerm, // total accumulated loan months; 0 before first renewal\n lastRenewedAt: positionState.lastRenewedAt, // timestamp of most recent renewal; createdAt at origination; 0 for pre-H-5 positions\n\n // Bitcoin state\n totalBTCSats: balanceResult.totalBalance,\n totalUTXOs: balanceResult.totalUTXOs,\n authorizedSpendsSats: balanceResult.authorizedBalance,\n authorizedSpendsHash: balanceResult.authorizedSpendsHash,\n availableBTCSats: balanceResult.availableBalance,\n availableUTXOs: balanceResult.availableUTXOs,\n\n // Price data\n btcPriceUsd,\n\n // Calculated metrics\n collateralValueUsd: collateralMetrics.collateralValueUsd,\n collateralRatioBps: collateralMetrics.collateralRatioBps,\n\n // Term status\n termDurationDays: termStatus.termDurationDays,\n termLengthDays: termStatus.termLengthDays,\n isExpired: termStatus.isExpired,\n daysUntilExpiry: termStatus.daysUntilExpiry,\n daysIntoGracePeriod: termStatus.daysIntoGracePeriod,\n\n // Liquidation risk\n currentLiquidationThreshold,\n isLiquidatable,\n marginToLiquidationBps,\n\n // Protocol parameters (from smart contracts)\n liquidationThresholdBps,\n originationFeeBps: termFees.originationFeeBps,\n extensionFeeBps: termFees.extensionFeeBps,\n\n // Metadata\n timestamp: Date.now(),\n };\n }\n\n // NOTE (remediation P1/#5): `getVaultSnapshotFast` \u2014 a snapshot built on the\n // skip-UTXO-validation balance path \u2014 was deleted. It had zero callers, and\n // a snapshot whose balance skipped UTXO validation + consensus must never\n // exist within reach of a signing flow. Every snapshot now runs the full\n // validation path above.\n\n /**\n * Query position state from smart contract\n *\n * Gets the simple state that contract stores:\n * - positionId, pkpId, borrower, vaultAddress\n * - ucdDebt\n * - termStartTimestamp\n * - selectedTerm\n * - status\n */\n protected async queryPositionState(positionId: string): Promise<{\n positionId: string;\n pkpId: string;\n borrower: string;\n vaultAddress: string;\n ucdDebt: bigint;\n termStartTimestamp: number;\n selectedTerm: number;\n status: number;\n expiryAt: number;\n previousExpiryAt: number;\n totalTerm: number;\n lastRenewedAt: number;\n }> {\n // Convert positionId to bytes32\n const positionIdBytes32 = positionId.startsWith(\"0x\")\n ? positionId\n : `0x${positionId.padStart(64, \"0\")}`;\n\n // Get RPC URL\n let rpcUrl: string;\n if (this.config.rpcUrl) {\n rpcUrl = this.config.rpcUrl;\n } else {\n rpcUrl = await litNodeRpcUrl(this.config.chain, this.config.drpcKey);\n }\n\n // Query contract\n // @ts-ignore - ethers available in LIT runtime\n // StaticJsonRpcProvider with just chainId to avoid network validation errors\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.config.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n this.config.chainId\n );\n\n // CRITICAL: Must call PositionManagerCore facet directly to get full Position struct with vaultAddress\n // The Diamond proxy's getPositionDetails() returns simplified struct without vaultAddress\n\n // Step 1: Get core facet address from Diamond proxy\n // @ts-ignore - ethers available in LIT runtime\n const diamondContract = new ethers.Contract(\n this.config.contractAddress,\n [\n {\n inputs: [],\n name: \"core\",\n outputs: [{ internalType: \"address\", name: \"\", type: \"address\" }],\n stateMutability: \"view\",\n type: \"function\",\n },\n ],\n provider\n );\n\n const coreAddress = await diamondContract.core();\n\n // Step 2: Call getPositionDetails on core facet (returns full struct with vaultAddress)\n // ABI for PositionManagerCoreModule.getPositionDetails\n const coreGetPositionDetailsABI = [\n {\n inputs: [\n { internalType: \"bytes32\", name: \"positionId\", type: \"bytes32\" },\n ],\n name: \"getPositionDetails\",\n outputs: [\n {\n components: [\n { internalType: \"bytes32\", name: \"positionId\", type: \"bytes32\" },\n { internalType: \"bytes32\", name: \"pkpId\", type: \"bytes32\" },\n { internalType: \"uint256\", name: \"ucdDebt\", type: \"uint256\" },\n { internalType: \"string\", name: \"vaultAddress\", type: \"string\" },\n { internalType: \"address\", name: \"borrower\", type: \"address\" },\n { internalType: \"uint40\", name: \"createdAt\", type: \"uint40\" },\n { internalType: \"uint40\", name: \"lastUpdated\", type: \"uint40\" },\n { internalType: \"uint16\", name: \"selectedTerm\", type: \"uint16\" },\n { internalType: \"uint40\", name: \"expiryAt\", type: \"uint40\" },\n {\n internalType: \"enum LoanStatusLib.LoanStatus\",\n name: \"status\",\n type: \"uint8\",\n },\n { internalType: \"uint40\", name: \"previousExpiryAt\", type: \"uint40\" },\n { internalType: \"uint16\", name: \"totalTerm\", type: \"uint16\" },\n { internalType: \"uint40\", name: \"lastRenewedAt\", type: \"uint40\" },\n ],\n internalType: \"struct IPositionManagerCore.Position\",\n name: \"\",\n type: \"tuple\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n ];\n\n // @ts-ignore - ethers available in LIT runtime\n const coreContract = new ethers.Contract(\n coreAddress,\n coreGetPositionDetailsABI,\n provider\n );\n\n const position = await coreContract.getPositionDetails(positionIdBytes32);\n\n // Validate status is in valid range (0-7)\n const statusNum = Number(position.status);\n if (statusNum < 0 || statusNum > 7) {\n // Log detailed diagnostic info for debugging\n console.error(\n \"[VaultSnapshot] INVALID STATUS - ABI decoding error detected\"\n );\n console.error(\" Position ID:\", positionIdBytes32);\n console.error(\" Contract:\", this.config.contractAddress);\n console.error(\" Status decoded:\", statusNum, \"(expected 0-7)\");\n console.error(\" Full position:\", JSON.stringify(position, null, 2));\n\n throw new Error(\n `Invalid position status decoded from contract: ${statusNum} (expected 0-7). ` +\n `This indicates an ABI decoding issue. Position: ${positionIdBytes32}`\n );\n }\n\n // Calculate term start timestamp from expiry using pure function\n // Always use selectedTerm (current period length) for term start calculation.\n // expiryAt = start of current period + selectedTerm months, so termStart = expiryAt - selectedTerm months.\n // totalTerm is the accumulated total months and is NOT relevant for when the current period started.\n const expiryAt = Number(position.expiryAt);\n const selectedTermMonths = Number(position.selectedTerm);\n const totalTermMonths = Number(position.totalTerm);\n const previousExpiryAt = Number(position.previousExpiryAt);\n const lastRenewedAt = Number(position.lastRenewedAt);\n const termStartTimestamp = calculateTermStartFromExpiry(\n expiryAt,\n selectedTermMonths\n );\n\n // A JSON vault record without the address for this chain's Bitcoin\n // network is a data error \u2014 fail loud here rather than let an undefined\n // address flow into balance reads / signed snapshots.\n const parsedVaultAddress = parseVaultAddress(\n position.vaultAddress,\n validateChain(this.config.chain)\n );\n if (typeof parsedVaultAddress !== \"string\" || parsedVaultAddress.length === 0) {\n throw new Error(\n `Position ${positionIdBytes32} vaultAddress has no entry for chain \"${this.config.chain}\"`\n );\n }\n\n return {\n positionId: position.positionId,\n pkpId: position.pkpId,\n borrower: position.borrower,\n vaultAddress: parsedVaultAddress,\n ucdDebt: BigInt(position.ucdDebt.toString()),\n termStartTimestamp,\n selectedTerm: selectedTermMonths,\n status: statusNum,\n expiryAt,\n previousExpiryAt,\n totalTerm: totalTermMonths,\n lastRenewedAt,\n };\n }\n\n // parseVaultAddress moved to `modules/vault-address.ts` (shared with the\n // phase-2 signer for the P6/#7b vault-identity binding).\n\n /**\n * Quick check if position is liquidatable\n *\n * Convenience method when you only need to know if position can be liquidated.\n *\n * @param positionId - Position to check\n * @returns True if position is liquidatable\n */\n async isLiquidatable(positionId: string): Promise<boolean> {\n const snapshot = await this.getVaultSnapshot(positionId);\n return snapshot.isLiquidatable;\n }\n\n /**\n * Get collateral ratio for position\n *\n * Convenience method when you only need the collateral ratio.\n *\n * @param positionId - Position to check\n * @returns Collateral ratio in basis points\n */\n async getCollateralRatio(positionId: string): Promise<number> {\n const snapshot = await this.getVaultSnapshot(positionId);\n return snapshot.collateralRatioBps;\n }\n\n /**\n * Get available BTC balance\n *\n * Convenience method when you only need available balance.\n *\n * @param positionId - Position to check\n * @returns Available BTC in satoshis\n */\n async getAvailableBalance(positionId: string): Promise<bigint> {\n const snapshot = await this.getVaultSnapshot(positionId);\n return snapshot.availableBTCSats;\n }\n\n /**\n * Check if position has sufficient collateral for new debt\n *\n * Used by minting authorization to validate new mints.\n *\n * @param positionId - Position to check\n * @param additionalDebt - Additional UCD debt to add\n * @param requiredRatioBps - Required collateral ratio (e.g., 11000 for 110%)\n * @returns True if sufficient collateral exists\n */\n async hasSufficientCollateral(\n positionId: string,\n additionalDebt: bigint,\n requiredRatioBps: number\n ): Promise<boolean> {\n const snapshot = await this.getVaultSnapshot(positionId);\n\n // Delegate to pure math function\n return hasSufficientCollateralForDebt(\n snapshot.collateralValueUsd,\n snapshot.ucdDebt,\n additionalDebt,\n requiredRatioBps\n );\n }\n}\n\n/**\n * Factory function to create VaultSnapshotModule\n *\n * @param config - Configuration\n * @returns VaultSnapshotModule instance\n */\nexport function createVaultSnapshotModule(\n config: VaultSnapshotConfig\n): VaultSnapshotModule {\n return new VaultSnapshotModule(config);\n}\n\n/**\n * USAGE EXAMPLE:\n *\n * ```typescript\n * import { createVaultSnapshotModule } from './modules/vault-snapshot';\n * import { BitcoinDataProvider } from './modules/bitcoin-data-provider.module';\n * import { PriceOracleModule } from './modules/price-oracle.module';\n *\n * // Initialize dependencies\n * const bitcoinProvider = new BitcoinDataProvider({\n * providerUrl: 'https://blockstream.info/testnet/api'\n * });\n *\n * const priceOracle = new PriceOracleModule('mainnet');\n *\n * // Create vault balance module\n * const vaultBalance = createVaultBalanceModule({\n * contractAddress: '0x...',\n * chain: 'sepolia',\n * bitcoinProvider,\n * minConfirmations: 6\n * });\n *\n * // Create vault snapshot module\n * const vaultSnapshot = createVaultSnapshotModule({\n * contractAddress: '0x...',\n * chain: 'sepolia',\n * vaultBalance,\n * priceOracle,\n * });\n *\n * // Get complete snapshot\n * const snapshot = await vaultSnapshot.getVaultSnapshot('position123');\n *\n * console.log('Position:', snapshot.positionId);\n * console.log('Collateral Ratio:', snapshot.collateralRatioBps / 100, '%');\n * console.log('Liquidatable:', snapshot.isLiquidatable);\n * console.log('Days Until Expiry:', snapshot.daysUntilExpiry);\n * console.log('Available BTC:', snapshot.availableBTCSats, 'sats');\n *\n * // Or use convenience methods\n * const isLiquidatable = await vaultSnapshot.isLiquidatable('position123');\n * const collateralRatio = await vaultSnapshot.getCollateralRatio('position123');\n * const availableBalance = await vaultSnapshot.getAvailableBalance('position123');\n *\n * // Check if can mint more UCD\n * const canMint = await vaultSnapshot.hasSufficientCollateral(\n * 'position123',\n * BigInt(5000), // Want to mint 5000 more UCD\n * 11000 // Required 110% ratio\n * );\n * ```\n */\n", "/**\n * Opt-in verbose logging for Lit Actions.\n *\n * Production / IPFS builds should stay quiet: no message hashes, PKP material,\n * encoded blobs, or user signatures in logs unless explicitly enabled.\n *\n * Enable via (after jsParams merge onto globalThis):\n * - globalThis.debugAction === true (existing)\n * - globalThis.LIT_ACTION_DEBUG === true or \"true\"\n * - process.env.LIT_ACTION_DEBUG or process.env.DEBUG === \"1\" | \"true\" (Node/tests only)\n */\n\n/**\n * Strip credentials and common API-key query params from URLs before logging.\n * (RPC providers often put secrets in the query string, e.g. dkey=.)\n * Uses string replacement so values stay human-readable (no URL-encoding of [REDACTED]).\n */\nexport function sanitizeUrlForLogs(url: string): string {\n if (url == null || typeof url !== \"string\") return \"[missing]\";\n let out = url.replace(\n /([?&])(dkey|apikey|api_key|key|token|secret|password|auth|authorization)=[^&]*/gi,\n \"$1$2=[REDACTED]\",\n );\n try {\n const u = new URL(out);\n if (u.username || u.password) {\n u.username = \"\";\n u.password = \"\";\n out = u.toString();\n }\n } catch {\n /* invalid URL after redaction \u2014 return regex-sanitized string */\n }\n return out;\n}\n\nfunction envDebugEnabled(): boolean {\n try {\n if (typeof process === \"undefined\" || !process.env) return false;\n const a = process.env.LIT_ACTION_DEBUG;\n const b = process.env.DEBUG;\n return (\n a === \"1\" ||\n a === \"true\" ||\n b === \"1\" ||\n b === \"true\"\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Whether verbose debug logging is enabled for this execution.\n * @param override - When set (e.g. from explicit jsParams), takes precedence.\n */\nexport function isLitActionDebugEnabled(override?: boolean): boolean {\n if (override === true) return true;\n if (override === false) return false;\n\n const g = globalThis as Record<string, unknown>;\n\n if (g.debugAction === true) return true;\n if (g.LIT_ACTION_DEBUG === true) return true;\n if (g.LIT_ACTION_DEBUG === \"true\") return true;\n\n return envDebugEnabled();\n}\n\n/** Logs only when {@link isLitActionDebugEnabled} is true. */\nexport function litDebugLog(...args: unknown[]): void {\n if (!isLitActionDebugEnabled()) return;\n console.log(...args);\n}\n\n/** console.warn only when debug enabled (rare; prefer litDebugLog). */\nexport function litDebugWarn(...args: unknown[]): void {\n if (!isLitActionDebugEnabled()) return;\n console.warn(...args);\n}\n", "import { isLitActionDebugEnabled } from \"./lit-action-debug\";\n\n/**\n * LIT Action Logger Module\n *\n * Centralized logging and timing infrastructure for LIT Actions.\n *\n * Features:\n * - Opt-in debugging via globalThis.debugAction or LIT_ACTION_DEBUG (see lit-action-debug.ts)\n * - Execution ID for multi-node correlation\n * - Step timing with automatic elapsed/remaining calculation\n * - Timeout warnings (30s LIT Protocol limit)\n * - Node context detection\n * - Final execution summary\n *\n * Usage:\n * ```typescript\n * const logger = LitActionLogger.create();\n * logger.stepStart('1', 'Fetching vault snapshot');\n * // ... do work ...\n * logger.stepEnd('1');\n * logger.summary();\n * ```\n *\n * Debug mode when isLitActionDebugEnabled() is true (debugAction, LIT_ACTION_DEBUG, etc.)\n *\n * Performance: When disabled (99% of cases), returns a no-op stub that does nothing.\n */\n\n/**\n * No-op logger stub for when debugging is disabled\n * Zero overhead - all methods are empty\n */\nclass NoOpLogger implements ILitActionLogger {\n stepStart(_stepId: string, _description: string): void {}\n stepEnd(_stepId: string, _warnThresholdMs?: number): void {}\n log(_stepId: string, _message: string, ..._rest: unknown[]): void {}\n warn(_stepId: string, _message: string): void {}\n error(_stepId: string, _message: string): void {}\n getElapsed(): number {\n return 0;\n }\n getRemaining(): number {\n return 30000;\n }\n summary(): void {}\n getExecutionId(): string {\n return \"\";\n }\n isDebugEnabled(): boolean {\n return false;\n }\n}\n\n/**\n * Interface for LIT Action Logger\n */\ninterface ILitActionLogger {\n stepStart(stepId: string, description: string): void;\n stepEnd(stepId: string, warnThresholdMs?: number): void;\n log(stepId: string, message: string, ...rest: unknown[]): void;\n warn(stepId: string, message: string): void;\n error(stepId: string, message: string): void;\n getElapsed(): number;\n getRemaining(): number;\n summary(): void;\n getExecutionId(): string;\n isDebugEnabled(): boolean;\n}\n\n/**\n * Full logger implementation for when debugging is enabled\n */\nclass DebugLogger implements ILitActionLogger {\n private executionId: string;\n private executionStartTime: number;\n private stepStartTimes: Map<string, number> = new Map();\n private stepDurations: Map<string, number> = new Map();\n private readonly TIMEOUT_MS = 30000; // 30 seconds LIT Action timeout\n private actionName: string;\n\n constructor(actionName: string) {\n this.actionName = actionName;\n this.executionStartTime = Date.now();\n\n // Generate unique execution ID for multi-node correlation\n const timestamp = Date.now();\n const random = Math.random().toString(36).substring(2, 9);\n this.executionId = `exec_${timestamp}_${random}`;\n\n this.logHeader();\n }\n\n /**\n * Log action header with execution context\n */\n private logHeader(): void {\n console.log(\n `[${this.actionName}] ========================================`\n );\n console.log(`[${this.actionName}] Execution started`);\n console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);\n\n // Detect if running in LIT node context vs browser\n const isLitNode = typeof (globalThis as any).litNodeContext !== \"undefined\";\n if (isLitNode) {\n console.log(`[${this.actionName}] Context: LIT Node`);\n console.log(\n `[${this.actionName}] Node: ${\n (globalThis as any).litNodeContext?.nodeAddress || \"unknown\"\n }`\n );\n } else {\n console.log(`[${this.actionName}] Context: Browser/Test`);\n }\n\n console.log(\n `[${this.actionName}] ========================================`\n );\n }\n\n stepStart(stepId: string, description: string): void {\n this.stepStartTimes.set(stepId, Date.now());\n const elapsed = Date.now() - this.executionStartTime;\n const remaining = this.TIMEOUT_MS - elapsed;\n console.log(`[Step ${stepId}] ${description}...`);\n console.log(\n `[Step ${stepId}] Elapsed: ${elapsed}ms | Remaining: ${remaining}ms`\n );\n }\n\n stepEnd(stepId: string, warnThresholdMs: number = 5000): void {\n const startTime = this.stepStartTimes.get(stepId);\n if (!startTime) {\n console.warn(\n `[Step ${stepId}] \u26A0\uFE0F stepEnd called without matching stepStart`\n );\n return;\n }\n\n const duration = Date.now() - startTime;\n this.stepDurations.set(stepId, duration);\n console.log(`[Step ${stepId}] Duration: ${duration}ms`);\n\n // Warn if step took longer than threshold\n if (duration > warnThresholdMs) {\n console.warn(\n `\u26A0\uFE0F [Step ${stepId}] Took ${duration}ms (> ${warnThresholdMs}ms threshold)`\n );\n }\n\n // Warn if approaching timeout\n const elapsed = Date.now() - this.executionStartTime;\n const remaining = this.TIMEOUT_MS - elapsed;\n if (remaining < 5000) {\n console.warn(\n `\u26A0\uFE0F [Step ${stepId}] Time remaining: ${remaining}ms (approaching timeout)`\n );\n }\n }\n\n log(stepId: string, message: string, ...rest: unknown[]): void {\n if (rest.length > 0) {\n console.log(`[Step ${stepId}] ${message}`, ...rest);\n } else {\n console.log(`[Step ${stepId}] ${message}`);\n }\n }\n\n warn(stepId: string, message: string): void {\n console.warn(`\u26A0\uFE0F [Step ${stepId}] ${message}`);\n }\n\n error(stepId: string, message: string): void {\n console.error(`\u274C [Step ${stepId}] ${message}`);\n }\n\n getElapsed(): number {\n return Date.now() - this.executionStartTime;\n }\n\n getRemaining(): number {\n return this.TIMEOUT_MS - this.getElapsed();\n }\n\n summary(): void {\n const totalDuration = Date.now() - this.executionStartTime;\n const remaining = this.TIMEOUT_MS - totalDuration;\n\n console.log(\n `[${this.actionName}] ========================================`\n );\n console.log(`[${this.actionName}] Execution Summary`);\n console.log(`[${this.actionName}] Execution ID: ${this.executionId}`);\n console.log(\n `[${this.actionName}] Total time: ${(totalDuration / 1000).toFixed(2)}s`\n );\n console.log(`[${this.actionName}] Time remaining: ${remaining}ms`);\n\n // Log step timing breakdown\n if (this.stepDurations.size > 0) {\n console.log(`[${this.actionName}] Step breakdown:`);\n for (const [stepId, duration] of this.stepDurations.entries()) {\n const percent = ((duration / totalDuration) * 100).toFixed(1);\n console.log(\n `[${this.actionName}] Step ${stepId}: ${duration}ms (${percent}%)`\n );\n }\n }\n\n // Warnings for slow execution\n if (totalDuration > 20000) {\n console.warn(\n `\u26A0\uFE0F [${this.actionName}] Slow execution: ${(\n totalDuration / 1000\n ).toFixed(2)}s (${remaining}ms remaining)`\n );\n }\n if (remaining < 5000) {\n console.warn(\n `\u26A0\uFE0F [${this.actionName}] CRITICAL: Only ${remaining}ms remaining before timeout!`\n );\n }\n\n console.log(\n `[${this.actionName}] ========================================`\n );\n }\n\n getExecutionId(): string {\n return this.executionId;\n }\n\n isDebugEnabled(): boolean {\n return true;\n }\n}\n\n/**\n * LIT Action Logger factory\n */\nexport class LitActionLogger {\n /**\n * Create logger instance\n * Returns NoOpLogger when disabled (99% case), DebugLogger when enabled\n * @param actionName - Name of the LIT Action (for logging context)\n * @param debugAction - Optional override for globalThis.debugAction\n */\n static create(\n actionName: string = \"LIT Action\",\n debugAction?: boolean\n ): ILitActionLogger {\n const debugEnabled = isLitActionDebugEnabled(debugAction);\n\n if (debugEnabled) {\n return new DebugLogger(actionName);\n } else {\n // Return lightweight no-op stub - zero overhead for 99% of executions\n return new NoOpLogger();\n }\n }\n}\n", "/**\n * Lit SDK global parameter handling (chipotle / V8 style).\n *\n * `jsParams` is nested under `globalThis.jsParams`. Call\n * {@link mergeJsParamsOntoGlobalThis} once at the start of an action so code\n * that reads `globalThis.chain` (etc.) works with flat access. Use\n * {@link getLitActionParams} when you need a single object reference.\n */\n\n/** Minimal shape for the V8 nested bag (values are merged onto globalThis). */\nexport type LitJsParams = Record<string, unknown>;\n\ntype GlobalWithJsParams = typeof globalThis & { jsParams?: LitJsParams };\n\nfunction asGlobalWithJsParams(): GlobalWithJsParams {\n return globalThis as GlobalWithJsParams;\n}\n\n/**\n * Copy `globalThis.jsParams` onto `globalThis` so flat reads work (V8 compat).\n * No-op when `jsParams` is missing or not a plain object.\n */\nexport function mergeJsParamsOntoGlobalThis(): void {\n const g = asGlobalWithJsParams();\n const jp = g.jsParams;\n if (jp != null && typeof jp === \"object\" && !Array.isArray(jp)) {\n Object.assign(g, jp);\n }\n}\n\n/**\n * Parameter object for the current execution: nested `jsParams` (V8) or the global\n * object itself (V7). Prefer calling after {@link mergeJsParamsOntoGlobalThis} when\n * other code expects flat `globalThis` fields.\n */\nexport function getLitActionParams<\n T extends object = Record<string, unknown>,\n>(): T {\n const g = asGlobalWithJsParams();\n const jp = g.jsParams;\n if (jp != null && typeof jp === \"object\" && !Array.isArray(jp)) {\n return jp as T;\n }\n return g as unknown as T;\n}\n\n/**\n * Safe message extraction for `catch (error: unknown)` paths.\n */\nexport function getUnknownErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n if (typeof error === \"string\") {\n return error;\n }\n try {\n return JSON.stringify(error);\n } catch {\n return String(error);\n }\n}\n\n/**\n * Whether an unknown error is an AbortError (fetch timeout / abort).\n */\nexport function isAbortError(error: unknown): boolean {\n return error instanceof Error && error.name === \"AbortError\";\n}\n", "/**\n * Bitcoin provider auth (LIT Action side).\n *\n * The BitcoinProviderRegistry stores one encrypted blob per\n * `(chainId, providerId)`. Historically that blob was a bare Esplora base URL.\n * To support commercial providers that require credentials, the blob may now be\n * a JSON object:\n *\n * { \"provider\": \"esplora\", \"url\": \"https://blockstream.info/api\" }\n * { \"provider\": \"maestro\", \"url\": \".../v0/esplora\", \"apiKey\": \"...\" }\n * { \"provider\": \"blockstream-enterprise\", \"url\": \".../api\",\n * \"clientId\": \"...\", \"clientSecret\": \"...\", \"tokenUrl\"?: \"...\" }\n *\n * Secrets only ever materialize HERE, inside the running LIT Action (the blob is\n * decrypted in-TEE). They are never in jsParams, on-chain plaintext, or the\n * bundle.\n *\n * Backward compatibility: a legacy plaintext that is a bare URL (does not parse\n * as a JSON object with a string `url`) is treated as\n * `{ provider: \"esplora\", url }` \u2014 existing registry entries keep working\n * without re-encryption.\n */\n\n// `fetch` is provided by the LIT runtime (used throughout the bitcoin modules).\ndeclare const fetch: any;\n\nexport type ProviderAuth =\n | { provider: \"esplora\" }\n | { provider: \"maestro\"; apiKey: string }\n | {\n provider: \"blockstream-enterprise\";\n clientId: string;\n clientSecret: string;\n tokenUrl?: string;\n };\n\nexport interface ParsedProvider {\n /** Esplora base URL (no trailing slash; paths are concatenated onto it). */\n url: string;\n /** Auth descriptor used to build request headers. */\n auth: ProviderAuth;\n}\n\n/** Default Blockstream Enterprise OAuth2 token endpoint (client-credentials). */\nconst BLOCKSTREAM_TOKEN_URL =\n \"https://login.blockstream.com/realms/blockstream-public/protocol/openid-connect/token\";\n\n/**\n * Reject non-`https://` URLs for any provider that sends credentials over the\n * wire (api-key header / OAuth secret \u2192 Bearer). Plain `http://` would leak the\n * secret in transit.\n */\nfunction requireHttps(u: string, label: string): void {\n if (!/^https:\\/\\//i.test(u.trim())) {\n throw new Error(\n `parseProviderPlaintext: ${label} must use https:// (credentials must not be sent over http)`,\n );\n }\n}\n\n/** Options for {@link parseProviderPlaintext}. */\nexport interface ParseProviderOptions {\n /**\n * Require `https://` for EVERY provider type, including credential-less\n * esplora and legacy bare URLs. Registry call sites set this whenever\n * `!policy.allowArbitraryBitcoinProvider` (sepolia/mainnet) \u2014 a plain-http\n * provider there hands an on-path attacker the balance feed the PKP signs\n * over (finding #3). Hardhat/regtest bypasses the registry entirely, so the\n * local `http://` daemon keeps working.\n */\n requireHttps?: boolean;\n}\n\n/**\n * Parse a decrypted provider plaintext into `{ url, auth }`.\n *\n * Accepts either a JSON object (when the trimmed plaintext starts with `{` and\n * has a non-empty string `url`) or a legacy bare URL string. Throws on a JSON\n * object that is missing `url` or required credentials for its provider type.\n * Credentialed provider types (maestro / blockstream-enterprise) ALWAYS\n * require https; `opts.requireHttps` extends that to esplora/bare URLs.\n */\nexport function parseProviderPlaintext(\n plaintext: string,\n opts?: ParseProviderOptions,\n): ParsedProvider {\n if (typeof plaintext !== \"string\" || plaintext.trim().length === 0) {\n throw new Error(\"parseProviderPlaintext: empty plaintext\");\n }\n const trimmed = plaintext.trim();\n\n // Legacy: bare URL string, no auth.\n if (!trimmed.startsWith(\"{\")) {\n if (opts?.requireHttps) requireHttps(trimmed, \"provider url\");\n return { url: trimmed, auth: { provider: \"esplora\" } };\n }\n\n let obj: any;\n try {\n obj = JSON.parse(trimmed);\n } catch (e: any) {\n throw new Error(\n `parseProviderPlaintext: plaintext looked like JSON but failed to parse: ${\n e?.message ?? String(e)\n }`,\n );\n }\n if (typeof obj.url !== \"string\" || obj.url.trim().length === 0) {\n throw new Error(\n \"parseProviderPlaintext: JSON provider config missing non-empty string `url`\",\n );\n }\n const url = obj.url.trim();\n\n switch (obj.provider) {\n case undefined:\n case \"esplora\":\n if (opts?.requireHttps) requireHttps(url, \"esplora provider url\");\n return { url, auth: { provider: \"esplora\" } };\n\n case \"maestro\": {\n if (typeof obj.apiKey !== \"string\" || obj.apiKey.length === 0) {\n throw new Error(\n \"parseProviderPlaintext: maestro provider requires a non-empty `apiKey`\",\n );\n }\n // Credentials travel in request headers \u2014 refuse to send them over http.\n requireHttps(url, \"maestro provider url\");\n return { url, auth: { provider: \"maestro\", apiKey: obj.apiKey } };\n }\n\n case \"blockstream-enterprise\": {\n if (\n typeof obj.clientId !== \"string\" ||\n obj.clientId.length === 0 ||\n typeof obj.clientSecret !== \"string\" ||\n obj.clientSecret.length === 0\n ) {\n throw new Error(\n \"parseProviderPlaintext: blockstream-enterprise provider requires non-empty `clientId` and `clientSecret`\",\n );\n }\n // Credentials (client secret \u2192 token \u2192 Bearer) travel over the wire.\n requireHttps(url, \"blockstream-enterprise provider url\");\n const hasTokenUrl =\n typeof obj.tokenUrl === \"string\" && obj.tokenUrl.length > 0;\n if (hasTokenUrl) requireHttps(obj.tokenUrl, \"blockstream-enterprise tokenUrl\");\n return {\n url,\n auth: {\n provider: \"blockstream-enterprise\",\n clientId: obj.clientId,\n clientSecret: obj.clientSecret,\n ...(hasTokenUrl ? { tokenUrl: obj.tokenUrl } : {}),\n },\n };\n }\n\n default:\n throw new Error(\n `parseProviderPlaintext: unknown provider type \"${String(obj.provider)}\"`,\n );\n }\n}\n\n/**\n * Per-run OAuth token cache. LIT Action module state is fresh per execution, so\n * this Map lives only for the current run. Keyed by `${tokenUrl}\\n${clientId}`\n * so concurrent fetches (e.g. the parallel utxo+tip `Promise.all`) share ONE\n * token exchange. Rejected entries are evicted so a retry can re-attempt.\n */\nconst oauthTokenCache = new Map<string, Promise<string>>();\n\n/** Default timeout (ms) for the OAuth token exchange \u2014 bounds the extra round-trip. */\nconst OAUTH_TOKEN_TIMEOUT_MS = 10_000;\n\nasync function getBlockstreamBearerToken(\n auth: {\n clientId: string;\n clientSecret: string;\n tokenUrl?: string;\n },\n timeoutMs?: number,\n): Promise<string> {\n const tokenUrl = auth.tokenUrl || BLOCKSTREAM_TOKEN_URL;\n const key = `${tokenUrl}\\n${auth.clientId}`;\n const cached = oauthTokenCache.get(key);\n if (cached) return cached;\n\n const promise = (async () => {\n const body =\n `grant_type=client_credentials` +\n `&client_id=${encodeURIComponent(auth.clientId)}` +\n `&client_secret=${encodeURIComponent(auth.clientSecret)}` +\n `&scope=openid`;\n // The token endpoint is NOT covered by any caller's request AbortController,\n // so bound it explicitly \u2014 otherwise a slow/hung token server stalls the Lit\n // Action up to the global ~30s kill.\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n timeoutMs && timeoutMs > 0 ? timeoutMs : OAUTH_TOKEN_TIMEOUT_MS,\n );\n let resp: any;\n try {\n resp = await fetch(tokenUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/x-www-form-urlencoded\" },\n body,\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timeoutId);\n }\n if (!resp.ok) {\n throw new Error(\n `Blockstream OAuth token exchange failed: ${resp.status} ${resp.statusText}`,\n );\n }\n const json: any = await resp.json();\n const token = json?.access_token;\n if (typeof token !== \"string\" || token.length === 0) {\n throw new Error(\n \"Blockstream OAuth token exchange returned no access_token\",\n );\n }\n return token;\n })();\n\n // Evict on rejection so a transient failure isn't sticky for the rest of the run.\n promise.catch(() => oauthTokenCache.delete(key));\n oauthTokenCache.set(key, promise);\n return promise;\n}\n\n/**\n * Resolve the HTTP headers to attach to an Esplora request for the given auth.\n *\n * - `esplora` (or undefined) \u2192 no auth headers\n * - `maestro` \u2192 `{ \"api-key\": <key> }`\n * - `blockstream-enterprise` \u2192 OAuth client-credentials exchange \u2192 `Authorization: Bearer <token>`\n */\nexport async function authHeaders(\n auth: ProviderAuth | undefined,\n timeoutMs?: number,\n): Promise<Record<string, string>> {\n if (!auth) return {};\n switch (auth.provider) {\n case \"esplora\":\n return {};\n case \"maestro\":\n return { \"api-key\": auth.apiKey };\n case \"blockstream-enterprise\": {\n const token = await getBlockstreamBearerToken(auth, timeoutMs);\n return { Authorization: `Bearer ${token}` };\n }\n default:\n return {};\n }\n}\n\n/**\n * Auth-aware GET with an END-TO-END timeout budget.\n *\n * A request to an authenticated provider has two sequential network legs \u2014 the\n * OAuth token exchange (Blockstream Enterprise) and the data request itself.\n * Bounding each leg independently would let a single logical request run up to\n * `2 \u00D7 timeoutMs`, which can collide with Lit's ~30s execution limit. Instead we\n * pin one deadline at the start: the token exchange is bounded by `timeoutMs`,\n * and the data fetch only gets the REMAINING time. Total wall-time \u2264 `timeoutMs`.\n *\n * Maestro/esplora have no token leg, so the data fetch gets ~the full budget.\n * Returns the raw fetch Response; callers handle `.ok` / `.json()` as today.\n */\nexport async function authedFetch(\n url: string,\n auth: ProviderAuth | undefined,\n timeoutMs: number,\n): Promise<any> {\n const deadline = Date.now() + timeoutMs;\n const headers = await authHeaders(auth, timeoutMs);\n const remaining = Math.max(1, deadline - Date.now());\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), remaining);\n try {\n return await fetch(url, { headers, signal: controller.signal });\n } finally {\n clearTimeout(timeoutId);\n }\n}\n", "/**\n * Bitcoin Data Provider Module\n *\n * Provides Bitcoin network data with support for future consensus mechanisms.\n * Current implementation: Single provider with fallback support\n * Future implementation: 2-of-3 provider consensus\n *\n * This module centralizes all Bitcoin data queries to maintain a consistent\n * interface that won't break when upgrading to multi-provider consensus.\n */\n\nimport {\n BitcoinDataProviderConfig,\n UTXO,\n UTXOSet,\n} from \"../interfaces/chunks/vault-balance.i\";\nimport { IBitcoinDataProvider } from \"../interfaces/chunks/bitcoin-data-provider.i\";\nimport { LitActionLogger } from \"./lit-action-logger.module\";\nimport {\n MAX_BTC_AMOUNT,\n UTXO_QUERY_MAX_RETRIES,\n UTXO_QUERY_RETRY_DELAY_MS,\n} from \"../constants\";\n\n/**\n * Assert a provider-reported satoshi amount is a sane integer before it is\n * promoted to a `bigint` the protocol signs over (remediation P1/#13). A\n * non-integer, negative, or supply-exceeding value is provider corruption or\n * manipulation \u2014 `BigInt()` would either throw opaquely (fractions) or admit\n * the bogus magnitude (negatives / absurd values) into a signed balance.\n */\nfunction assertSaneSatoshis(value: number, context: string): void {\n if (!Number.isSafeInteger(value) || value < 0 || value > MAX_BTC_AMOUNT) {\n throw new Error(\n `${context}: satoshi value ${value} is not a sane amount ` +\n `(must be an integer in [0, ${MAX_BTC_AMOUNT}])`,\n );\n }\n}\nimport {\n getUnknownErrorMessage,\n isAbortError,\n} from \"./lit-global-bootstrap\";\nimport { litDebugLog } from \"./lit-action-debug\";\nimport { authHeaders } from \"./bitcoin-provider-auth\";\n\n/** Opening words of every tip-read failure message (kept stable for operators). */\nconst TIP_READ_FAILURE_PREFIX = \"Bitcoin tip-height read failed\";\n\n/**\n * One provider could not state the chain tip, so no confirmation depth exists\n * to report. Distinct from every other provider error on purpose:\n *\n * - `getTransaction`'s own boundary translates a message containing \"404\" into\n * `null` (\"transaction not found\"). The tip endpoint is a DIFFERENT resource\n * on the same provider, so a 404 there must not be read as a missing\n * transaction \u2014 that `null` is the fabricated-depth bug in another costume.\n * - The consensus layer treats THIS class, and only this class, as provider\n * ABSENCE (quorum reduced, floor still enforced). Every other failure \u2014\n * notably a provider that answers \"I have never seen that transaction\" \u2014\n * stays fatal, because it is a claim about the chain, not an outage, and it\n * is the signature of a fabricated UTXO (review 2026-07-15 P1).\n *\n * Identified by a structural marker rather than `instanceof`: the bundler and\n * downlevel transpilation can break the prototype chain across the action\n * bundle, and a mis-identified error here fails in the dangerous direction.\n */\nexport class BitcoinTipUnreadableError extends Error {\n readonly isBitcoinTipUnreadable = true as const;\n constructor(message: string) {\n super(message);\n this.name = \"BitcoinTipUnreadableError\";\n }\n}\n\n/** True when `error` is a {@link BitcoinTipUnreadableError} (bundle-safe check). */\nexport function isBitcoinTipUnreadableError(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n (error as { isBitcoinTipUnreadable?: unknown }).isBitcoinTipUnreadable ===\n true\n );\n}\n\n/** Bitcoin Core `listunspent` row (subset used here) */\ninterface RpcUnspentOutput {\n txid: string;\n vout: number;\n amount: number;\n confirmations: number;\n}\n\n/** Esplora / Blockstream UTXO JSON row before normalization */\ninterface EsploraUtxoRow {\n txid?: string;\n vout?: number;\n n?: number;\n value?: number;\n satoshis?: number;\n confirmations?: number;\n status?: {\n confirmed?: boolean;\n block_height?: number;\n };\n}\n\n/** `/address/:addr` chain_stats response (Esplora) */\ninterface EsploraAddressChainStats {\n chain_stats?: {\n funded_txo_sum?: number;\n spent_txo_sum?: number;\n };\n}\n\n/**\n * Bitcoin Data Provider\n *\n * Fetches UTXO data from Bitcoin network.\n * Interface designed to remain stable when adding multi-provider consensus.\n */\nexport class BitcoinDataProvider implements IBitcoinDataProvider {\n private config: BitcoinDataProviderConfig;\n private timeout: number;\n private logger: ReturnType<typeof LitActionLogger.create>;\n\n constructor(config: BitcoinDataProviderConfig) {\n // Fail closed (2026-10-27 ruling): a provider with no URL must not exist.\n // Before this guard, `getTransactionOutputs` answered `null` for a blank\n // URL \u2014 \"transaction not found\" \u2014 which the self-change consensus reader\n // counts as a \"not self-change\" vote, a silent fallback contrary to \u00A71.\n if (\n typeof config.providerUrl !== \"string\" ||\n config.providerUrl.trim().length === 0\n ) {\n throw new Error(\n \"BitcoinDataProvider: providerUrl must be a non-empty string; refusing to construct a provider that cannot be queried\",\n );\n }\n this.config = config;\n // 15 seconds to leave time for other operations in LIT action (30s total limit)\n this.timeout = config.timeout || 15000;\n this.logger = LitActionLogger.create(\"BitcoinDataProvider\");\n }\n\n /**\n * Merge per-provider auth headers into a base header set. No-op for public\n * Esplora / regtest faucet (no `auth`); attaches the `api-key` header for\n * Maestro and performs a (memoized) OAuth exchange \u2192 `Bearer` for Blockstream\n * Enterprise. Awaited at every fetch site so a single run shares one token.\n */\n private async withAuth(\n base: Record<string, string> = {},\n ): Promise<Record<string, string>> {\n // Pass this.timeout so the OAuth token exchange (Blockstream Enterprise) is\n // bounded by the same budget as the data request it precedes.\n return { ...base, ...(await authHeaders(this.config.auth, this.timeout)) };\n }\n\n /**\n * Get current Bitcoin block height from provider\n */\n private async getCurrentBlockHeight(): Promise<number> {\n this.logger.stepStart(\"0\", \"getCurrentBlockHeight\");\n // If RPC helper is provided, use it\n if (this.config.rpcHelper) {\n const blockCount = await this.config.rpcHelper.getBlockCount();\n this.logger.stepEnd(\"0\");\n return blockCount;\n }\n\n // Fetch from Esplora API\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const t0 = Date.now();\n const response = await fetch(\n `${this.config.providerUrl}/blocks/tip/height`,\n {\n signal: controller.signal,\n headers: await this.withAuth({\n Accept: \"text/plain\",\n \"User-Agent\": \"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)\",\n \"ngrok-skip-browser-warning\": \"true\",\n }),\n }\n );\n\n clearTimeout(timeoutId);\n litDebugLog(\n `[BitcoinDataProvider] blocks/tip/height ${Date.now() - t0}ms (timeout budget ${this.timeout}ms)`,\n );\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch block height: ${response.status} ${response.statusText}`\n );\n }\n\n const heightText = await response.text();\n \n // FAIL FAST: Detect HTML response (wrong URL pointing to web interface)\n if (heightText.trim().startsWith('<!DOCTYPE') || heightText.trim().startsWith('<html')) {\n throw new Error(\n `Bitcoin RPC endpoint returned HTML instead of block height. ` +\n `URL may be pointing to web interface instead of API endpoint. ` +\n `Expected: plain text number, Got: HTML document. ` +\n `Check that URL ends with /api/esplora (not root /)`\n );\n }\n \n const height = parseInt(heightText.trim(), 10);\n\n if (isNaN(height)) {\n // Truncate response to prevent HTML dump catastrophe\n const truncated = heightText.length > 200 \n ? heightText.substring(0, 200) + '... (truncated)'\n : heightText;\n throw new Error(`Invalid block height response: ${truncated}`);\n }\n\n this.logger.stepEnd(\"0\");\n return height;\n } catch (error: unknown) {\n clearTimeout(timeoutId);\n this.logger.stepEnd(\"0\");\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n\n /**\n * Fetch all UTXOs for a Bitcoin address\n *\n * @param address - Bitcoin address (legacy, segwit, or taproot)\n * @returns Array of UTXOs\n */\n async getUTXOs(address: string): Promise<UTXO[]> {\n this.logger.log(\"0\", `Original address: \"${address}\"`);\n\n // Strip network prefix if present (e.g., \"REGTEST_address\" -> \"address\")\n const cleanAddress = this.stripNetworkPrefix(address);\n\n this.logger.log(\"0\", `Cleaned address: \"${cleanAddress}\"`);\n\n // If RPC helper is provided (for regtest/testing), use it directly\n if (this.config.rpcHelper) {\n return await this.fetchUTXOsFromRPC(cleanAddress);\n }\n\n // Try primary provider first\n try {\n return await this.fetchUTXOsFromProvider(\n this.config.providerUrl,\n cleanAddress\n );\n } catch (error: unknown) {\n this.logger.warn(\n \"0\",\n `Primary provider failed: ${getUnknownErrorMessage(error)}`,\n );\n\n // Try fallback providers if available\n if (\n this.config.fallbackProviders &&\n this.config.fallbackProviders.length > 0\n ) {\n const sortedFallbacks = [...this.config.fallbackProviders].sort(\n (a, b) => a.priority - b.priority\n );\n\n for (const fallback of sortedFallbacks) {\n try {\n this.logger.log(\n \"0\",\n `Trying fallback: ${fallback.name} (${fallback.url})`\n );\n return await this.fetchUTXOsFromProvider(\n fallback.url,\n cleanAddress\n );\n } catch (fallbackError: unknown) {\n this.logger.warn(\n \"0\",\n `Fallback ${fallback.name} failed: ${getUnknownErrorMessage(fallbackError)}`,\n );\n continue;\n }\n }\n }\n\n throw new Error(`Failed to fetch UTXOs: ${getUnknownErrorMessage(error)}`);\n }\n }\n\n /**\n * Strip network prefix from Bitcoin address\n *\n * Addresses may be stored with network prefix (e.g., \"REGTEST_address\")\n * but APIs expect clean addresses without prefix.\n *\n * @param address - Address with optional prefix\n * @returns Clean address without prefix\n */\n private stripNetworkPrefix(address: string): string {\n const prefixPattern = /^(REGTEST_|TESTNET_|MAINNET_)/;\n return address.replace(prefixPattern, \"\");\n }\n\n /**\n * Fetch UTXOs using Bitcoin RPC (for regtest/testing)\n */\n private async fetchUTXOsFromRPC(address: string): Promise<UTXO[]> {\n if (!this.config.rpcHelper) {\n throw new Error(\"RPC helper not configured\");\n }\n\n const wallet = this.config.rpcWallet || \"\";\n const unspentOutputs = await this.config.rpcHelper.listUnspent(\n wallet,\n address\n );\n\n const utxos: UTXO[] = (unspentOutputs as RpcUnspentOutput[]).map(\n (utxo) => {\n const satNumber = Math.round(utxo.amount * 100000000); // BTC to satoshis\n assertSaneSatoshis(satNumber, `fetchUTXOsFromRPC ${utxo.txid}:${utxo.vout}`);\n return {\n txid: utxo.txid,\n vout: utxo.vout,\n satoshis: BigInt(satNumber),\n confirmations: utxo.confirmations,\n };\n },\n );\n\n return utxos;\n }\n\n /**\n * Parse Esplora/Blockstream/Mempool.space UTXO response\n *\n * Supports multiple formats:\n * - Esplora format: {txid, vout, value, status: {confirmed, block_height}}\n * - Blockstream format: {txid, vout, value, confirmations}\n *\n * @param data Raw response from provider API\n * @param currentBlockHeight Current block height (for calculating confirmations from block_height)\n * @returns Array of normalized UTXOs\n */\n private parseBlockstreamUTXOs(\n data: unknown,\n currentBlockHeight: number,\n ): UTXO[] {\n if (!Array.isArray(data)) {\n throw new Error(\"Invalid Blockstream response format: expected an array\");\n }\n\n const rows = data as EsploraUtxoRow[];\n\n // Normalize UTXO format (different providers may have different field names)\n const utxos: UTXO[] = [];\n for (const utxo of rows) {\n // Calculate confirmations based on format\n let confirmations = 0;\n\n // Check for Esplora format (status.confirmed and status.block_height)\n if (utxo.status && typeof utxo.status === \"object\") {\n if (utxo.status.confirmed) {\n // For Esplora format: calculate confirmations from block heights\n // confirmations = current_height - tx_block_height + 1\n if (\n utxo.status.block_height !== undefined &&\n utxo.status.block_height > 0\n ) {\n confirmations = currentBlockHeight - utxo.status.block_height + 1;\n } else {\n // Confirmed but no block_height (or block_height is 0)\n // This handles regtest where blocks are mined instantly\n confirmations = 1;\n }\n }\n // If not confirmed, confirmations remains 0\n } else if (utxo.confirmations !== undefined) {\n // Blockstream format: direct confirmations field\n confirmations = utxo.confirmations;\n }\n\n const txid = utxo.txid;\n const vout =\n utxo.vout !== undefined ? utxo.vout : utxo.n;\n const satRaw =\n utxo.value !== undefined ? utxo.value : utxo.satoshis;\n if (txid === undefined || vout === undefined || satRaw === undefined) {\n throw new Error(\n \"Invalid UTXO row: missing txid, vout/n, or value/satoshis\",\n );\n }\n assertSaneSatoshis(satRaw, `parseBlockstreamUTXOs ${txid}:${vout}`);\n\n utxos.push({\n txid,\n vout,\n satoshis: BigInt(satRaw),\n confirmations,\n });\n }\n\n return utxos;\n }\n\n /**\n * Internal method to fetch UTXOs from a specific provider\n *\n * Supports standard Esplora API format:\n * - Standard format: {providerUrl}/address/{address}/utxo\n * - providerUrl must include full base path (e.g., \"http://localhost:3002/api/esplora\")\n */\n private async fetchUTXOsFromProvider(\n providerUrl: string,\n address: string\n ): Promise<UTXO[]> {\n this.logger.stepStart(\"1\", \"fetchUTXOsFromProvider\");\n // Standard Esplora API format only\n // providerUrl must include full base path (e.g., \"http://localhost:3002/api/esplora\")\n // Canonical Esplora endpoint is SINGULAR `/utxo` (Blockstream + Maestro). Our regtest\n // faucet also serves `/utxo` (and keeps a `/utxos` alias for older deployed bundles).\n const endpoint = `${providerUrl}/address/${address}/utxo`;\n this.logger.log(\"1\", `Fetching UTXOs from ${endpoint}`);\n\n // Run block-height fetch and UTXO fetch in parallel \u2014 saves ~8s vs sequential\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const tParallel = Date.now();\n const [currentBlockHeight, response] = await Promise.all([\n this.getCurrentBlockHeight(),\n fetch(endpoint, {\n signal: controller.signal,\n headers: await this.withAuth({\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)\",\n \"ngrok-skip-browser-warning\": \"true\", // Skip ngrok browser warning page\n }),\n }),\n ]);\n\n clearTimeout(timeoutId);\n litDebugLog(\n `[BitcoinDataProvider] parallel(tipHeight + GET utxo) wall ${Date.now() - tParallel}ms endpoint tail .../${address.slice(0, 12)}.../utxo (timeout budget ${this.timeout}ms)`,\n );\n this.logger.log(\"1\", `Current block height: ${currentBlockHeight}`);\n\n if (!response.ok) {\n throw new Error(\n `Bitcoin provider error: ${response.status} ${response.statusText}`\n );\n }\n\n // Get response text first to detect HTML before JSON parsing\n const responseText = await response.text();\n \n // FAIL FAST: Detect HTML response (wrong URL pointing to web interface)\n if (responseText.trim().startsWith('<!DOCTYPE') || responseText.trim().startsWith('<html')) {\n throw new Error(\n `Bitcoin RPC endpoint returned HTML instead of JSON. ` +\n `URL may be pointing to web interface instead of API endpoint. ` +\n `Expected: JSON array of UTXOs, Got: HTML document. ` +\n `Check that URL ends with /api/esplora (not root /)`\n );\n }\n \n let data;\n try {\n data = JSON.parse(responseText) as unknown;\n } catch (parseError: unknown) {\n // Truncate response to prevent catastrophic logs\n const truncated = responseText.length > 200\n ? responseText.substring(0, 200) + '... (truncated)'\n : responseText;\n throw new Error(\n `Failed to parse JSON response: ${getUnknownErrorMessage(parseError)}. Response: ${truncated}`,\n );\n }\n\n // Log the parsed data\n this.logger.log(\n \"1\",\n `Raw API Response: ${JSON.stringify(data, null, 2)}`\n );\n\n // Parse standard Esplora/Blockstream format with current block height\n const utxos = this.parseBlockstreamUTXOs(data, currentBlockHeight);\n this.logger.stepEnd(\"1\");\n return utxos;\n } catch (error: unknown) {\n clearTimeout(timeoutId);\n this.logger.stepEnd(\"1\");\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n\n /**\n * Get complete UTXO set with balance summary\n *\n * This is the SINGLE method that vault-balance module should call.\n * Returns everything needed to know about Bitcoin network state for an address.\n *\n * @param address - Bitcoin address\n * @param minConfirmations - Minimum confirmations for \"confirmed\" status (REQUIRED - caller must specify)\n * @returns Complete UTXO set with balance breakdown\n */\n async getUTXOSet(\n address: string,\n minConfirmations: number\n ): Promise<UTXOSet> {\n // Retry logic to handle transient failures from Bitcoin provider\n let utxos: UTXO[] = [];\n let lastError: Error | null = null;\n const maxRetries = UTXO_QUERY_MAX_RETRIES;\n const retryDelay = UTXO_QUERY_RETRY_DELAY_MS;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n this.logger.log(\"2\", `UTXO query attempt ${attempt}/${maxRetries}...`);\n utxos = await this.getUTXOs(address);\n this.logger.log(\"2\", `UTXO query succeeded on attempt ${attempt}`);\n lastError = null;\n break; // Success - exit retry loop\n } catch (error: unknown) {\n lastError =\n error instanceof Error ? error : new Error(getUnknownErrorMessage(error));\n this.logger.error(\n \"2\",\n `UTXO query failed on attempt ${attempt}: ${getUnknownErrorMessage(error)}`,\n );\n\n if (attempt < maxRetries) {\n this.logger.log(\"2\", `Waiting ${retryDelay}ms before retry...`);\n await new Promise((resolve) => setTimeout(resolve, retryDelay));\n }\n }\n }\n\n // If all retries failed, throw the last error\n if (lastError) {\n throw new Error(\n `Failed to query UTXOs after ${maxRetries} attempts: ${lastError.message}`,\n );\n }\n\n const totalBalance = utxos.reduce((sum, utxo) => sum + utxo.satoshis, 0n);\n const confirmedBalance = utxos\n .filter((utxo) => utxo.confirmations >= minConfirmations)\n .reduce((sum, utxo) => sum + utxo.satoshis, 0n);\n const unconfirmedBalance = totalBalance - confirmedBalance;\n\n return {\n utxos,\n totalBalance,\n totalUTXOs: utxos.length,\n confirmedBalance,\n unconfirmedBalance,\n };\n }\n\n /**\n * Get balance for a Bitcoin address (fast, no UTXO details)\n *\n * WARNING: This method does NOT validate individual UTXOs.\n * Use ONLY for non-critical balance display, never for authorization validation.\n * For authorization/security: ALWAYS use getUTXOSet() with full UTXO validation.\n *\n * Uses Esplora /address/:address endpoint to get confirmed balance from chain_stats.\n *\n * @param address - Bitcoin address\n * @returns Balance in satoshis (confirmed balance only)\n * @throws Error if the request fails or response is invalid\n */\n async getBalance(address: string): Promise<bigint> {\n const cleanAddress = this.stripNetworkPrefix(address);\n const endpoint = `${this.config.providerUrl}/address/${cleanAddress}`;\n this.logger.log(\"3\", `Fetching balance from ${endpoint}`);\n\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const t0 = Date.now();\n const response = await fetch(endpoint, {\n signal: controller.signal,\n headers: await this.withAuth({\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": \"Mozilla/5.0 (compatible; DiamondHandsValidator/1.0)\",\n \"ngrok-skip-browser-warning\": \"true\",\n }),\n });\n\n clearTimeout(timeoutId);\n litDebugLog(\n `[BitcoinDataProvider] GET address chain_stats ${Date.now() - t0}ms (timeout budget ${this.timeout}ms)`,\n );\n\n if (!response.ok) {\n throw new Error(\n `Bitcoin provider error: ${response.status} ${response.statusText}`\n );\n }\n\n const data = (await response.json()) as EsploraAddressChainStats;\n\n // Validate response structure\n if (!data.chain_stats) {\n throw new Error(\"Invalid response: missing chain_stats\");\n }\n\n const fundedTxoSum = data.chain_stats.funded_txo_sum;\n const spentTxoSum = data.chain_stats.spent_txo_sum;\n\n if (fundedTxoSum === undefined || spentTxoSum === undefined) {\n throw new Error(\n `Invalid response: missing required fields. funded_txo_sum: ${fundedTxoSum}, spent_txo_sum: ${spentTxoSum}`\n );\n }\n\n // Calculate confirmed balance: funded - spent. Guard both operands and\n // the result before the bigint promotion \u2014 a negative difference means\n // the provider served corrupt chain_stats (spent > funded is impossible\n // on an honest view).\n assertSaneSatoshis(fundedTxoSum, `getBalance ${cleanAddress} funded_txo_sum`);\n assertSaneSatoshis(spentTxoSum, `getBalance ${cleanAddress} spent_txo_sum`);\n const confirmedBalance = fundedTxoSum - spentTxoSum;\n assertSaneSatoshis(confirmedBalance, `getBalance ${cleanAddress} confirmed balance`);\n const balance = BigInt(confirmedBalance);\n\n this.logger.log(\"3\", `Balance: ${balance.toString()} sats`);\n this.logger.log(\n \"3\",\n ` - Funded: ${fundedTxoSum} sats, Spent: ${spentTxoSum} sats`\n );\n\n return balance;\n } catch (error: unknown) {\n clearTimeout(timeoutId);\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${this.timeout}ms`);\n }\n const errorMessage = getUnknownErrorMessage(error);\n this.logger.log(\"3\", `Balance fetch failed: ${errorMessage}`);\n throw new Error(\n `Failed to fetch Bitcoin balance for address ${cleanAddress}: ${errorMessage}`,\n );\n }\n }\n\n /**\n * Get transaction with confirmation count\n *\n * Checks if transaction exists on Bitcoin network and returns confirmation count.\n * Used to validate authorized spends have been broadcasted.\n *\n * @param txid - Transaction ID to check\n * @returns Transaction with confirmation count, or null if not found\n */\n async getTransaction(\n txid: string\n ): Promise<{ txid: string; confirmations: number } | null> {\n // If RPC helper is provided (for regtest/testing), use it directly\n if (this.config.rpcHelper) {\n try {\n const wallet = this.config.rpcWallet || \"\";\n const tx = await this.config.rpcHelper.getTransaction(wallet, txid);\n return {\n txid: tx.txid,\n confirmations: tx.confirmations || 0,\n };\n } catch (error: unknown) {\n // Transaction not found\n const msg = getUnknownErrorMessage(error);\n const code =\n error !== null &&\n typeof error === \"object\" &&\n \"code\" in error &&\n typeof (error as { code: unknown }).code === \"number\"\n ? (error as { code: number }).code\n : undefined;\n if (msg.includes(\"Invalid or non-wallet transaction\") || code === -5) {\n return null;\n }\n throw error;\n }\n }\n\n // Try provider API\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const t0 = Date.now();\n const response = await fetch(`${this.config.providerUrl}/tx/${txid}`, {\n signal: controller.signal,\n headers: await this.withAuth(),\n });\n\n clearTimeout(timeoutId);\n litDebugLog(\n `[BitcoinDataProvider] GET tx/${txid.slice(0, 10)}\u2026 ${Date.now() - t0}ms (timeout budget ${this.timeout}ms)`,\n );\n\n if (!response.ok) {\n if (response.status === 404) {\n return null; // Transaction not found\n }\n throw new Error(\n `Bitcoin provider error: ${response.status} ${response.statusText}`\n );\n }\n\n const data = (await response.json()) as {\n txid?: string;\n status?: { confirmed?: boolean; block_height?: number };\n };\n\n // Blockstream / Esplora API format. Compute actual confirmation depth\n // by subtracting the tx's block_height from the current tip height:\n // confirmations = current_height - block_height + 1\n // Previously this hard-coded `1` whenever the tx was confirmed, making\n // any caller that gates on a confirmation threshold (e.g. the\n // stale-spend recovery validator's `MIN_CONFIRMATIONS_DEFAULT = 6`)\n // structurally unable to pass. Mirrors the depth math already used by\n // `getUtxos` lower in this module.\n if (data.status) {\n if (!data.status.confirmed || !data.status.block_height) {\n return { txid: data.txid ?? txid, confirmations: 0 };\n }\n // Depth is derived from the chain tip, and there is no honest way to\n // guess it. Until 2026-09-23 all three tip-read failure modes\n // (endpoint not ok / unparseable body / fetch threw) answered\n // `confirmations: 1`. On a BTC-custody protocol that is the most\n // dangerous value this module can invent: confirmation depth is\n // exactly what the spend and balance gates consult, and `1` already\n // clears every one-confirmation gate (regtest/sepolia thresholds, and\n // each provider's depth vote on the stale-spend recovery path).\n // \"Could not read the tip\" must never become \"it has a confirmation\",\n // so the read throws, named \u2014 see `fetchTipHeight`. The self-change\n // consensus layer above treats a provider that cannot state the tip as\n // ABSENT from the quorum, never as agreeing, and fails loudly once the\n // survivors fall below `policy.minConsensusProviders`; the stale-spend\n // recovery path keeps its stricter rule and refuses outright.\n const tipHeight = await this.fetchTipHeight(controller.signal);\n const depth = tipHeight - data.status.block_height + 1;\n return {\n txid: data.txid ?? txid,\n confirmations: depth > 0 ? depth : 0,\n };\n }\n\n return null;\n } catch (error: unknown) {\n clearTimeout(timeoutId);\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${this.timeout}ms`);\n }\n // A tip-height failure is NOT \"transaction not found\" \u2014 it is a refusal\n // to state a depth. It must escape intact, BEFORE the 404 heuristic\n // below, which would otherwise turn a 404 from `/blocks/tip/height`\n // into `null` and let callers silently drop a transaction that exists.\n if (isBitcoinTipUnreadableError(error)) {\n throw error;\n }\n // 404 means transaction not found\n if (getUnknownErrorMessage(error).includes(\"404\")) {\n return null;\n }\n throw error;\n }\n }\n\n /**\n * Current chain tip height from THIS provider \u2014 or throw.\n *\n * Every exit is a throw naming the provider and the precise failure, because\n * the only alternative is inventing a confirmation depth (see the call site).\n * The single `try` exists solely to attach that name to a transport-level\n * rejection (DNS, TLS, connection reset, abort); it re-throws the cause\n * verbatim inside the message and never substitutes a value \u2014 authorized for\n * this case by the Batch 2 plan, \u00A7C2.\n *\n * @param signal - The caller's AbortSignal, so this read shares the same\n * timeout budget as the transaction fetch it serves.\n */\n private async fetchTipHeight(signal: AbortSignal): Promise<number> {\n const endpoint = `${this.config.providerUrl}/blocks/tip/height`;\n // `Awaited<ReturnType<typeof fetch>>`, not `Response`: inside a Lit Action\n // the ambient `fetch` resolves to the runtime's narrower `LitFetchResponse`.\n let tipResp: Awaited<ReturnType<typeof fetch>>;\n try {\n tipResp = await fetch(endpoint, {\n signal,\n headers: await this.withAuth(),\n });\n } catch (error: unknown) {\n throw new BitcoinTipUnreadableError(\n `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} threw \u2014 ${getUnknownErrorMessage(error)}`,\n );\n }\n if (!tipResp.ok) {\n throw new BitcoinTipUnreadableError(\n `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} \u2192 ${tipResp.status} ${tipResp.statusText}`,\n );\n }\n const tipBody = (await tipResp.text()).trim();\n const tipHeight = Number.parseInt(tipBody, 10);\n if (!Number.isFinite(tipHeight) || tipHeight <= 0) {\n throw new BitcoinTipUnreadableError(\n `${TIP_READ_FAILURE_PREFIX}: GET ${endpoint} returned an unusable tip height ` +\n `\"${tipBody.slice(0, 64)}\"`,\n );\n }\n return tipHeight;\n }\n\n /**\n * Get outputs (vouts) of a Bitcoin transaction\n *\n * Fetches the full transaction from the Esplora API and returns all outputs\n * with their index, scriptPubKey, address, and value.\n *\n * Used to canonicalize UTXO vout index when the Esplora UTXO endpoint\n * returns a wrong vout (a known faucet API bug in regtest environments).\n *\n * @param txid - Transaction ID\n * @returns Array of transaction outputs with index, or null if not found\n */\n async getTransactionOutputs(\n txid: string\n ): Promise<Array<{ index: number; scriptpubkey?: string; scriptpubkey_address?: string; value: number }> | null> {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), this.timeout);\n\n try {\n const response = await fetch(`${this.config.providerUrl}/tx/${txid}`, {\n signal: controller.signal,\n headers: await this.withAuth(),\n });\n\n clearTimeout(timeoutId);\n\n if (!response.ok) {\n if (response.status === 404) {\n return null;\n }\n throw new Error(\n `Bitcoin provider error: ${response.status} ${response.statusText}`\n );\n }\n\n const data = await response.json() as {\n vout?: Array<{\n scriptpubkey?: string;\n scriptpubkey_address?: string;\n value?: number;\n }>;\n };\n\n if (!data.vout || !Array.isArray(data.vout)) {\n return null;\n }\n\n return data.vout.map((output, index) => {\n // The withdrawal canonicalization matches on VALUE \u2014 a missing value\n // silently defaulted to 0 would fail every match and surface as a\n // misleading \"no vault output matches\" abort. A response without a\n // per-output value is malformed: fail loud here instead.\n if (output.value === undefined) {\n throw new Error(\n `getTransactionOutputs(${txid}): output ${index} is missing its ` +\n `value \u2014 malformed provider response, refusing to return ` +\n `outputs that cannot be value-verified`,\n );\n }\n assertSaneSatoshis(\n output.value,\n `getTransactionOutputs(${txid}) output ${index}`,\n );\n return {\n index,\n scriptpubkey: output.scriptpubkey,\n scriptpubkey_address: output.scriptpubkey_address,\n value: output.value,\n };\n });\n } catch (error: unknown) {\n clearTimeout(timeoutId);\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${this.timeout}ms`);\n }\n throw error;\n }\n }\n\n // FUTURE: Multi-provider consensus methods will be added here\n // async getUTXOsWithConsensus(address: string): Promise<UTXO[]> {\n // // Fetch from all providers\n // // Return UTXOs that appear in 2+ sources\n // // Use median value if amounts differ\n // }\n}\n\n/**\n * Factory function for creating Bitcoin Data Provider\n * Useful for dependency injection and testing\n */\nexport function createBitcoinDataProvider(\n config: BitcoinDataProviderConfig\n): BitcoinDataProvider {\n return new BitcoinDataProvider(config);\n}\n", "// LIT Actions environment provides native fetch API - no imports needed\nimport {\n IPriceOracle,\n PriceSourceConfig,\n} from \"../interfaces/chunks/price-oracle.i\";\n\nconst PRICE_ORACLE_TOLERANCE = 0.01; // 1% max spread: (hi - lo) / lo\n\nexport class PriceOracleModule implements IPriceOracle {\n private sources: PriceSourceConfig[];\n\n /**\n * The locked production set. Every signed-price flow uses exactly these three\n * providers. The set was narrowed from five to three (dropping Binance and\n * Coinbase) after Binance returned HTTP 451 from the Lit TEE egress IP \u2014 the\n * two exchange APIs geofence/restrict in ways the global-egress data APIs do\n * not. Each provider here MUST be invoked with an API key (per-key rate\n * limiting + revokability + tenant attribution).\n *\n * Adding to this list re-opens the 2-of-3-consensus manipulation path flagged\n * in audit H-2 \u2014 do not extend without an explicit design review.\n */\n private static readonly ACTIVE_PROVIDER_NAMES = [\n \"cryptocompare\",\n \"coinmarketcap\",\n \"coingecko\",\n ] as const;\n\n /**\n * Number of DISTINCT providers required for a price signature. Strict 3-of-3\n * \u2014 not \"at least 3\"; not \"3 of N.\" Callers MUST pass exactly three entries\n * from {@link PriceOracleModule.ACTIVE_PROVIDER_NAMES}. Names are deduplicated\n * before the count is checked, so three CoinGecko entries still count as one.\n */\n private static readonly REQUIRED_PROVIDER_COUNT = 3;\n\n /**\n * Hardhat-only single-provider mode. When true the oracle requires exactly ONE\n * plaintext provider instead of the locked 3-of-3 encrypted set. Set ONLY by a\n * validator that has already verified `chain-policy.allowDevSinglePriceProvider`\n * (true only for hardhat). It NEVER relaxes consensus on sepolia/mainnet, and a\n * price signed under it is bound to the hardhat chainId domain (unusable elsewhere).\n */\n private readonly devSingleProvider: boolean;\n\n /** Distinct providers required for the active mode: 1 in hardhat dev, else 3. */\n private requiredCount(): number {\n return this.devSingleProvider ? 1 : PriceOracleModule.REQUIRED_PROVIDER_COUNT;\n }\n\n /**\n * @param priceProvidersOrConfig - REQUIRED in production flows. An array of\n * exactly 3 `{name, apiKey}` entries, one per locked provider. Every entry\n * needs an apiKey. Names are deduplicated so three entries with\n * `name: \"coingecko\"` collapse to a single provider \u2014 which then fails the\n * strict count check.\n * @param legacySources - Test-only back door. When supplied, the constructor\n * trusts the caller-supplied array verbatim and skips credential checks.\n * The strict count is still enforced (exactly 3).\n * @param _mode - Ignored. Retained for backward-compatible call sites.\n */\n constructor(\n priceProvidersOrConfig?:\n | Array<{ name: string; apiKey?: string; apiSecret?: string }>\n | any,\n legacySources?: PriceSourceConfig[],\n _mode?: \"dev\" | \"prod\",\n opts?: { devSingleProvider?: boolean },\n ) {\n this.devSingleProvider = opts?.devSingleProvider === true;\n if (legacySources && Array.isArray(legacySources)) {\n this.sources = legacySources;\n } else {\n if (!Array.isArray(priceProvidersOrConfig)) {\n throw new Error(\n \"Price oracle requires a priceProviders array \u2014 defaults and fallbacks have been removed. \" +\n `Pass exactly ${PriceOracleModule.REQUIRED_PROVIDER_COUNT} distinct {name, apiKey} entries from the locked set: ` +\n PriceOracleModule.ACTIVE_PROVIDER_NAMES.join(\", \"),\n );\n }\n this.sources = this.buildSources(priceProvidersOrConfig);\n }\n\n this.sources.sort((a, b) => a.priority - b.priority);\n this.validateProviderCount();\n }\n\n /**\n * Enforces strict 3-of-3. Any deviation re-opens the consensus-manipulation\n * path flagged as H-2 in the audit. There is no \"\u22653\" or \"3 of N\" mode.\n */\n private validateProviderCount(): void {\n if (this.sources.length !== this.requiredCount()) {\n throw new Error(\n `Price oracle requires exactly ${this.requiredCount()} provider(s). ` +\n `Currently configured: ${this.sources.length} provider(s). ` +\n (this.devSingleProvider\n ? \"(hardhat dev single-provider mode)\"\n : `Locked production set: ${PriceOracleModule.ACTIVE_PROVIDER_NAMES.join(\", \")}`),\n );\n }\n }\n\n /**\n * Build price sources from the caller-supplied config.\n *\n * Rules (all unconditional):\n * - Exactly 3 entries \u2014 reject fewer and reject more.\n * - Every entry must be a supported provider name from the locked set.\n * - Every entry must carry an `apiKey`.\n * - Duplicates by `name` are rejected outright.\n *\n * Throws as soon as any rule is violated.\n */\n private buildSources(\n priceProviders: Array<{\n name: string;\n apiKey?: string;\n apiSecret?: string;\n }>,\n ): PriceSourceConfig[] {\n if (priceProviders.length !== this.requiredCount()) {\n throw new Error(\n `priceProviders must contain exactly ${this.requiredCount()} entr${this.requiredCount() === 1 ? \"y\" : \"ies\"}. ` +\n `Received: ${priceProviders.length}. ` +\n (this.devSingleProvider\n ? \"(hardhat dev single-provider mode)\"\n : `Locked production set: ${PriceOracleModule.ACTIVE_PROVIDER_NAMES.join(\", \")}`),\n );\n }\n\n const sources: PriceSourceConfig[] = [];\n const seen = new Set<string>();\n let priority = 1;\n\n for (const provider of priceProviders) {\n if (!provider || typeof provider.name !== \"string\") {\n throw new Error(\"priceProviders entries must be {name, apiKey, apiSecret?} objects\");\n }\n const name = provider.name.toLowerCase();\n\n if (!PriceOracleModule.ACTIVE_PROVIDER_NAMES.includes(name as any)) {\n throw new Error(\n `Unsupported price provider \"${provider.name}\". ` +\n `Locked production set: ${PriceOracleModule.ACTIVE_PROVIDER_NAMES.join(\", \")}`,\n );\n }\n\n if (seen.has(name)) {\n throw new Error(\n `Duplicate price provider \"${name}\" \u2014 the oracle requires ${PriceOracleModule.REQUIRED_PROVIDER_COUNT} DISTINCT ` +\n `providers so a single upstream failure or manipulation cannot ` +\n `compromise consensus. Use ${PriceOracleModule.REQUIRED_PROVIDER_COUNT} different provider names from: ` +\n `${PriceOracleModule.ACTIVE_PROVIDER_NAMES.join(\", \")}`,\n );\n }\n seen.add(name);\n\n switch (name) {\n case \"cryptocompare\":\n if (!provider.apiKey) {\n throw new Error(\"CryptoCompare provider requires an apiKey\");\n }\n sources.push(\n this.createCryptoCompareSource(provider.apiKey, priority++),\n );\n break;\n case \"coinmarketcap\":\n if (!provider.apiKey) {\n throw new Error(\"CoinMarketCap provider requires an apiKey\");\n }\n sources.push(\n this.createCoinMarketCapSource(provider.apiKey, priority++),\n );\n break;\n case \"coingecko\":\n if (!provider.apiKey) {\n throw new Error(\n \"CoinGecko provider requires an apiKey (Demo or Pro). \" +\n \"Unauthenticated CoinGecko access is not accepted \u2014 the \" +\n \"free tier is rate-limited and edge-cached, which breaks \" +\n \"median consensus under load.\",\n );\n }\n sources.push(\n this.createCoinGeckoSource(provider.apiKey, priority++),\n );\n break;\n default:\n // Unreachable: validated against ACTIVE_PROVIDER_NAMES above.\n throw new Error(`Unhandled provider: ${name}`);\n }\n }\n\n return sources;\n }\n\n /**\n * Create CryptoCompare price source\n * Requires API key for access\n */\n private createCryptoCompareSource(\n apiKey: string,\n priority: number\n ): PriceSourceConfig {\n const fetchJson = async (url: string) => {\n const controller = new AbortController();\n const timeoutMs = 5000;\n const timeoutId = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(url, {\n signal: controller.signal,\n headers: {\n // LIT runtime rejects custom User-Agent headers (gRPC invalid_argument)\n Accept: \"application/json\",\n },\n });\n clearTimeout(timeoutId);\n if (!res.ok) {\n throw new Error(\n `CryptoCompare HTTP ${res.status} ${res.statusText}`,\n );\n }\n return await res.json();\n } catch (error: any) {\n clearTimeout(timeoutId);\n if (error.name === \"AbortError\") {\n throw new Error(`Request timeout after ${timeoutMs}ms`);\n }\n throw error;\n }\n };\n\n return {\n name: \"CryptoCompare\",\n fetchPrice: async () => {\n // Each node fetches the price\n const url = new URL(\"https://min-api.cryptocompare.com/data/price\");\n url.searchParams.set(\"fsym\", \"BTC\");\n url.searchParams.set(\"tsyms\", \"USDT\");\n url.searchParams.set(\"api_key\", apiKey);\n\n const data: any = await fetchJson(url.toString());\n // Response format: {\"USDT\":86800.42}\n // Treat USDT as USD (1:1 for price oracle purposes)\n const price = Number((data as any)?.USDT);\n if (!Number.isFinite(price) || price <= 0) {\n throw new Error(\"Invalid CryptoCompare price payload\");\n }\n\n // Chipotle: no broadcastAndCollect \u2014 each node uses its local fetch (deterministic if APIs agree).\n return price;\n },\n priority,\n };\n }\n\n /**\n * Create shared fetch helper with timeout\n * LIT runtime rejects custom User-Agent headers\n */\n private createFetchJson(providerName: string) {\n return async (url: string, headers?: Record<string, string>) => {\n const controller = new AbortController();\n const timeoutMs = 5000;\n const id = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const res = await fetch(url, {\n headers: { Accept: \"application/json\", ...(headers || {}) },\n signal: controller.signal,\n });\n if (!res.ok) {\n throw new Error(\n `${providerName} HTTP ${res.status} ${res.statusText}`,\n );\n }\n return await res.json();\n } finally {\n clearTimeout(id);\n }\n };\n }\n\n /**\n * Create CoinGecko price source.\n *\n * CoinGecko's public endpoint has no authentication, but we intentionally\n * require the caller to supply either a Demo (`x-cg-demo-api-key`) or Pro\n * (`x-cg-pro-api-key`) key.\n */\n private createCoinGeckoSource(\n apiKey: string,\n priority: number,\n ): PriceSourceConfig {\n if (!apiKey) {\n throw new Error(\"createCoinGeckoSource requires an apiKey\");\n }\n const fetchJson = this.createFetchJson(\"CoinGecko\");\n\n return {\n name: \"CoinGecko\",\n fetchPrice: async () => {\n // Pro API keys use `x-cg-pro-api-key`; Demo keys use `x-cg-demo-api-key`.\n // Diamond Hands deployments issue Demo keys; if a Pro key is supplied\n // the caller should prefix it with \"pro:\" so we route it correctly.\n const isPro = apiKey.startsWith(\"pro:\");\n const key = isPro ? apiKey.slice(4) : apiKey;\n const headers: Record<string, string> = isPro\n ? { \"x-cg-pro-api-key\": key }\n : { \"x-cg-demo-api-key\": key };\n\n const url = new URL(\"https://api.coingecko.com/api/v3/simple/price\");\n url.searchParams.set(\"ids\", \"bitcoin\");\n url.searchParams.set(\"vs_currencies\", \"usd\");\n\n const data: any = await fetchJson(url.toString(), headers);\n const price = Number((data as any)?.bitcoin?.usd);\n if (!Number.isFinite(price) || price <= 0) {\n throw new Error(\"Invalid CoinGecko price payload\");\n }\n\n return price;\n },\n priority,\n };\n }\n\n private createCoinMarketCapSource(\n apiKey: string,\n priority: number\n ): PriceSourceConfig {\n const fetchJson = this.createFetchJson(\"CoinMarketCap\");\n\n return {\n name: \"CoinMarketCap\",\n fetchPrice: async () => {\n const url = new URL(\n \"https://pro-api.coinmarketcap.com/v2/cryptocurrency/quotes/latest\"\n );\n url.searchParams.set(\"symbol\", \"BTC\");\n url.searchParams.set(\"convert\", \"USDT\");\n\n const data: any = await fetchJson(url.toString(), {\n \"X-CMC_PRO_API_KEY\": apiKey,\n });\n const quote =\n data?.data?.BTC?.[0]?.quote?.USDT?.price ??\n data?.data?.BTC?.quote?.USDT?.price;\n const price = Number(quote);\n if (!Number.isFinite(price) || price <= 0) {\n throw new Error(\"Invalid CoinMarketCap price payload\");\n }\n\n return price;\n },\n priority,\n };\n }\n\n /**\n * Get BTC price in USD with 8 decimals.\n *\n * Strict 3-of-3: queries all sources in parallel; if any one fails, the whole\n * call fails (no fallback). All three prices must lie within 1% of each other\n * (`(hi - lo) / lo <= 0.01`). Returns the median of the three.\n *\n * This is the only signed-price path in the codebase. The previously-exposed\n * `getBTCPriceConsensus()` (with outlier filtering + lenient survivor median)\n * was removed in the H-2 fix.\n */\n async getBTCPrice(): Promise<bigint> {\n const startTime = Date.now();\n\n if (this.sources.length !== this.requiredCount()) {\n throw new Error(\n `Price oracle requires exactly ${this.requiredCount()} provider(s). Currently configured: ${this.sources.length}`\n );\n }\n\n const GLOBAL_TIMEOUT_MS = 8000;\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(() => {\n reject(\n new Error(`Price oracle global timeout after ${GLOBAL_TIMEOUT_MS}ms`)\n );\n }, GLOBAL_TIMEOUT_MS);\n });\n\n const fetchAll = Promise.all(\n this.sources.map(async (source) => {\n const t = Date.now();\n try {\n const priceUSD = await source.fetchPrice();\n console.log(\n `[Price Oracle] \u2705 [+${Date.now() - t}ms] ${source.name}: $${priceUSD.toLocaleString()}`,\n );\n return priceUSD;\n } catch (error) {\n const cause = error instanceof Error ? error.message : String(error);\n console.log(`[Price Oracle] \u274C ${source.name}: ${cause}`);\n throw new Error(`${source.name} price fetch failed: ${cause}`);\n }\n }),\n );\n\n const prices: number[] = await Promise.race([fetchAll, timeoutPromise]);\n\n // Sort ascending; median is middle value\n const sorted = [...prices].sort((a, b) => a - b);\n\n let median: number;\n if (this.devSingleProvider) {\n // Hardhat dev mode: exactly one provider, so there is no cross-provider\n // spread to check \u2014 use the single fetched price directly.\n median = sorted[0];\n } else {\n median = sorted[1];\n // Tolerance check: (hi - lo) / lo must be within 1%\n const spread = (sorted[2] - sorted[0]) / sorted[0];\n if (spread > PRICE_ORACLE_TOLERANCE) {\n const names = this.sources.map((s) => s.name).join(\", \");\n const formatted = sorted.map((p) => `$${p.toLocaleString()}`).join(\", \");\n throw new Error(\n `Price consensus failed: prices not within ${PRICE_ORACLE_TOLERANCE * 100}% tolerance. ` +\n `Providers: [${names}]. Prices: [${formatted}]`\n );\n }\n }\n\n // Convert median to 8-decimal bigint (deterministic: cents \u2192 BigInt)\n const priceCents = Math.round(median * 100);\n const priceWith8Decimals = BigInt(priceCents) * 1_000_000n;\n\n const totalElapsed = Date.now() - startTime;\n console.log(`[Price Oracle] Median price: $${median.toLocaleString()} \u2014 total time: ${totalElapsed}ms`);\n console.log(`[Price Oracle] Price with 8 decimals: ${priceWith8Decimals}`);\n\n return priceWith8Decimals;\n }\n}\n", "/**\n * Vault Balance Consensus \u2014 multi-provider cross-checks for the trusted balance\n *\n * Extracted from `vault-balance.module.ts` (review 2026-07-15) so the balance\n * module owns only the contract-state / authorized-spend / filter orchestration\n * while this class owns everything provider-facing:\n * - provider expansion (one data reader per registered provider),\n * - confirmed-UTXO-set consensus (each confirmed UTXO must match, by value,\n * on every provider; tip skew demotes, forgery / depth-lie throws),\n * - self-change proofing (unconfirmed change admitted only when every\n * provider agrees the parent tx spends confirmed vault-owned outputs and\n * corroborates the claimed output),\n * - the fan-out / concurrency / timeout policy those checks depend on.\n *\n * Bundling note: this file is imported ONLY by `vault-balance.module.ts` (hence\n * only by the six vault-balance consumer actions). It deliberately does NOT\n * touch `bitcoin-data-provider.module.ts`, whose other importers \u2014 including\n * `btc-transaction-signer`, pinned by an in-flight deploy ceremony \u2014 must not\n * rebundle. See docs/vault-balance-confirmed-gate-plan-2026-07-14.md \u00A73.1/\u00A73.2.\n */\n\nimport {\n SelfChangeProviderConfig,\n TransactionInput,\n UTXO,\n UTXOSet,\n} from \"../interfaces/chunks/vault-balance.i\";\nimport { IBitcoinDataProvider } from \"../interfaces/chunks/bitcoin-data-provider.i\";\nimport {\n BitcoinDataProvider,\n isBitcoinTipUnreadableError,\n} from \"./bitcoin-data-provider.module\";\nimport { authHeaders } from \"./bitcoin-provider-auth\";\nimport { isAbortError } from \"./lit-global-bootstrap\";\nimport { litDebugLog } from \"./lit-action-debug\";\n\n/**\n * Self-change classification budget: at most this many distinct unconfirmed\n * parent transactions are classified per balance calculation, largest claimed\n * value first (deterministic). Anyone can dust a vault address with 0-conf\n * deposits, so an unbounded fan-out would let mempool spam amplify into\n * provider rate-limit failures and \u2014 since consensus is fail-closed \u2014 an\n * action-wide outage. Protocol self-spends are rare and high-value, so they\n * always win the ordering; overflow parents are excluded (the safe direction\n * for third-party dust).\n */\nconst MAX_CLASSIFIED_PARENTS = 5;\n\n/** Parent transactions evaluated concurrently (each fans out to all providers). */\nconst CLASSIFICATION_CONCURRENCY = 2;\n\n/**\n * Max acceptable spread (in blocks) between the highest and lowest confirmation\n * count any registered provider reports for the SAME confirmed UTXO. Honest\n * providers track the chain tip within a block or two, so a spread inside this\n * tolerance is treated as benign tip skew (the UTXO is gated on the minimum\n * count \u2014 it simply waits a block if that dips below threshold). A spread\n * beyond it means providers materially disagree on the UTXO's depth \u2014 a\n * compromised provider trying to inflate a shallow UTXO past the gate, or to\n * deflate a deep one to force a wrongful liquidation \u2014 and is refused\n * (fail-closed) rather than silently demoted.\n */\nconst CONFIRMATION_SKEW_TOLERANCE = 3;\n\n/** Parsed output of a parent transaction (Esplora `/tx/:txid` vout row). */\ninterface ParentTxOutput {\n index: number;\n scriptpubkey_address?: string;\n value?: bigint;\n}\n\n/** Parent transaction data needed for the self-change proof. */\ninterface ParentTransactionData {\n inputs: TransactionInput[];\n outputs: ParentTxOutput[];\n}\n\n/**\n * Run `fn` over `items` with at most `limit` in flight, preserving order.\n * First rejection propagates (fail-closed) once in-flight work settles.\n */\nasync function mapWithConcurrency<T, R>(\n items: T[],\n limit: number,\n fn: (item: T) => Promise<R>\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n const workers = Array.from(\n { length: Math.min(limit, items.length) },\n async () => {\n while (true) {\n const i = next++;\n if (i >= items.length) {\n return;\n }\n results[i] = await fn(items[i]!);\n }\n }\n );\n await Promise.all(workers);\n return results;\n}\n\n/**\n * Verify the primary provider's claimed UTXOs against a provider's view of\n * the parent transaction's outputs. Returns a mismatch description, or null\n * when every claim matches (exists at the claimed index, pays the vault,\n * exact claimed value).\n */\nfunction findOutputClaimMismatch(\n claimedUtxos: UTXO[],\n outputs: ParentTxOutput[],\n cleanVaultAddress: string\n): string | null {\n for (const claim of claimedUtxos) {\n const output = outputs.find((o) => o.index === claim.vout);\n if (!output) {\n return `claimed output ${claim.txid}:${claim.vout} not present in parent tx`;\n }\n if (output.scriptpubkey_address !== cleanVaultAddress) {\n return `claimed output ${claim.txid}:${claim.vout} pays ${output.scriptpubkey_address ?? \"<no address>\"}, not the vault`;\n }\n if (output.value === undefined || output.value !== claim.satoshis) {\n return `claimed output ${claim.txid}:${claim.vout} value ${output.value?.toString() ?? \"<missing>\"} != reported ${claim.satoshis.toString()}`;\n }\n }\n return null;\n}\n\n/**\n * Strip network prefix from a Bitcoin address.\n *\n * Parity with BitcoinDataProvider's private `stripNetworkPrefix` \u2014 duplicated\n * (2 lines) rather than exported from the provider module, so this change does\n * not rebundle the provider's other importers.\n */\nfunction stripNetworkPrefix(address: string): string {\n const prefixPattern = /^(REGTEST_|TESTNET_|MAINNET_)/;\n return address.replace(prefixPattern, \"\");\n}\n\n/**\n * Multi-provider consensus over a vault's UTXO set.\n *\n * Constructed per balance calculation from the primary data provider (the one\n * the primary UTXO set came from \u2014 index 0, reused verbatim to preserve test\n * doubles) plus the full registered provider list. All secondary readers are\n * built once, up front, and shared by both consensus passes.\n */\nexport class VaultBalanceConsensus {\n private readonly readers: IBitcoinDataProvider[] | null;\n\n /**\n * @param minConsensusProviders Policy floor (`policy.minConsensusProviders`,\n * remediation P1/#1). Both consensus passes THROW when fewer providers are\n * configured than the floor demands \u2014 below it the cross-checks cannot run\n * and neither trusting the primary (inflation) nor excluding UTXOs\n * (deflation \u2192 wrongful liquidation) is a safe direction. A floor of 1\n * (hardhat / single-provider sepolia) preserves the trust-primary /\n * exclude-unconfirmed baseline unchanged.\n */\n constructor(\n private readonly primaryProvider: IBitcoinDataProvider,\n private readonly providerConfigs: SelfChangeProviderConfig[] | undefined,\n private readonly minConsensusProviders: number\n ) {\n // A provider with no endpoint cannot vote. Counting it as \"not self-change\"\n // would exclude real collateral (deflation \u2192 wrongful liquidation), so a\n // config without a URL is refused up front rather than at read time.\n (providerConfigs ?? []).forEach((cfg, i) => {\n if (!cfg.providerUrl) {\n throw new Error(\n `VaultBalanceConsensus: provider config ${i} (\"${cfg.name}\") has no providerUrl; refusing to count it as a vote`\n );\n }\n });\n this.readers = this.buildReaders();\n }\n\n /**\n * Fail-closed floor check shared by both consensus passes. Only floors above\n * 1 can bite: a floor of 1 with zero configs means \"no esplora access\n * configured\" (dev/test), where the documented pre-gate behaviour \u2014\n * trust-primary confirmed set, exclude unconfirmed \u2014 remains correct.\n */\n private assertProviderFloor(pass: string): void {\n const configured = this.providerConfigs?.length ?? 0;\n if (this.minConsensusProviders > 1 && configured < this.minConsensusProviders) {\n throw new Error(\n `${pass}: this chain requires at least ${this.minConsensusProviders} Bitcoin providers ` +\n `for consensus; ${configured} configured. Refusing to proceed without cross-check.`\n );\n }\n }\n\n /**\n * Build one data reader per configured provider (primary first). Index 0\n * reuses the injected primary instance; the rest are constructed from their\n * configs so cross-check reads hit the right endpoint. Null when no providers\n * are configured \u2014 both passes then fall back to primary-only behaviour.\n */\n private buildReaders(): IBitcoinDataProvider[] | null {\n const configs = this.providerConfigs;\n if (!configs || configs.length === 0) {\n return null;\n }\n return configs.map((cfg, i) =>\n i === 0\n ? this.primaryProvider\n : new BitcoinDataProvider({\n providerUrl: cfg.providerUrl,\n auth: cfg.auth,\n ...(cfg.timeout ? { timeout: cfg.timeout } : {}),\n })\n );\n }\n\n /**\n * Confirmed-UTXO-set consensus across every registered provider (strict).\n *\n * The signed balance is dominated by the primary's confirmed UTXOs, but the\n * UTXO set \u2014 txid, vout, and value \u2014 is read only from the primary; the\n * `assertBitcoinBalanceConsensus` check the validators run compares\n * `chain_stats` totals, not individual outpoints. So a compromised primary\n * can add a fabricated confirmed UTXO, or inflate a real one's value, and the\n * balance consensus still passes (it serves honest `chain_stats`). This\n * closes that: each UTXO the primary reports at or above `minConfirmations`\n * must be present with the EXACT same value on every registered provider.\n *\n * Semantics:\n * - Absent on any provider, or value mismatch \u2192 THROW (fail-closed). Confirmed\n * transactions are fully propagated, so absence is unambiguous forgery, not\n * a race.\n * - Present + value-matched everywhere: the UTXO counts as confirmed only if\n * it meets `minConfirmations` on ALL providers (gated on the minimum\n * reported depth). A UTXO just past the boundary on the primary but a block\n * behind on a lagging provider is DEMOTED \u2014 excluded until it matures \u2014\n * rather than signed over. A depth spread beyond CONFIRMATION_SKEW_TOLERANCE\n * is not benign skew but a provider lying about depth (to inflate a shallow\n * UTXO past the gate, or deflate a deep one into a wrongful liquidation) \u2192\n * THROW.\n * - SYMMETRIC (finding #6): a confirmed outpoint any secondary reports that\n * the primary omits entirely, reports with a different value, or reports\n * at a depth more than the skew tolerance BELOW the secondary's \u2192 THROW.\n * Without this, a compromised primary deflates the balance by omission and\n * forces a wrongful liquidation.\n *\n * Below `minConsensusProviders` this THROWS (P1/#1). With a floor of 1 and\n * 0/1 providers configured, no cross-check is possible and the primary's\n * confirmed UTXOs are returned unchanged (behaviour identical to before\n * this gate).\n *\n * Cross-checking `chain_stats` totals against the confirmed-UTXO sum was\n * considered and rejected: `getBalance` reads mempool-blind `chain_stats`\n * while `getUTXOSet` removes mempool-spent outputs, so the two legitimately\n * diverge during any pending spend \u2014 precisely the self-change window \u2014 and\n * that comparison would false-fail there. Outpoint-set consensus asserts\n * agreement only on confirmed outpoints, which the mempool does not touch.\n *\n * @returns Set of \"txid:vout\" keys admitted as confirmed-with-consensus.\n */\n async confirmedUtxoConsensus(\n primaryUtxos: UTXO[],\n vaultAddress: string,\n minConfirmations: number\n ): Promise<Set<string>> {\n const providerConfigs = this.providerConfigs;\n const readers = this.readers;\n\n // P1/#1: below the policy floor, refusing to sign is the only safe move \u2014\n // trusting the primary's confirmed set unverified is the exact single-\n // provider inflation vector this pass exists to close.\n this.assertProviderFloor(\"confirmedUtxoConsensus\");\n\n const confirmedKeys = new Set<string>();\n const primaryConfirmed = primaryUtxos.filter(\n (utxo) => utxo.confirmations >= minConfirmations\n );\n for (const utxo of primaryConfirmed) {\n confirmedKeys.add(`${utxo.txid}:${utxo.vout}`);\n }\n\n // 0 or 1 provider (only reachable with a floor of 1 \u2014 hardhat / single-\n // provider sepolia): no cross-check possible; trust the primary (unchanged).\n // NOTE: an empty primaryConfirmed set does NOT short-circuit the multi-\n // provider path \u2014 a primary omitting EVERY confirmed UTXO is the most\n // extreme deflation (finding #6), and only the symmetric pass below can\n // catch it.\n if (!providerConfigs || providerConfigs.length <= 1 || !readers) {\n return confirmedKeys;\n }\n\n const providerName = (i: number) =>\n providerConfigs[i]!.name || providerConfigs[i]!.providerUrl;\n\n // Fetch every SECONDARY provider's UTXO set concurrently (the primary's is\n // already in hand). Fail-closed: any request failure throws and names it.\n //\n // NOTE: getUTXOSet's second argument does NOT filter the returned `utxos`\n // array \u2014 it only shapes the summary balance fields. Each secondary's map\n // below therefore contains the provider's FULL UTXO set (0-conf included),\n // so a boundary UTXO on a provider one block behind the primary is still\n // PRESENT here with its lower count and takes the demote path \u2014 absence\n // from the map means the provider doesn't know the outpoint at all, even\n // in its mempool, which for a \u2265minConfirmations claim is forgery or a\n // materially desynced provider, not tip skew.\n const settled = await Promise.allSettled(\n readers\n .slice(1)\n .map((reader) => reader.getUTXOSet(vaultAddress, minConfirmations))\n );\n const failures = settled\n .map((r, i) => ({ r, name: providerName(i + 1) }))\n .filter(\n (x): x is { r: PromiseRejectedResult; name: string } =>\n x.r.status === \"rejected\"\n )\n .map(\n ({ r, name }) => `${name} \u2192 ${r.reason?.message ?? String(r.reason)}`\n );\n if (failures.length > 0) {\n throw new Error(\n `Confirmed UTXO set read failed for ${vaultAddress} on ${failures.length}/${providerConfigs.length - 1} secondary provider(s): ${failures.join(\"; \")}`\n );\n }\n\n // Index secondary sets by outpoint for O(1) lookup.\n const secondaryMaps = settled.map((r) => {\n const map = new Map<string, { value: bigint; confirmations: number }>();\n for (const utxo of (r as PromiseFulfilledResult<UTXOSet>).value.utxos) {\n map.set(`${utxo.txid}:${utxo.vout}`, {\n value: utxo.satoshis,\n confirmations: utxo.confirmations,\n });\n }\n return map;\n });\n\n const demoted: string[] = [];\n for (const utxo of primaryConfirmed) {\n const key = `${utxo.txid}:${utxo.vout}`;\n let minConfs = utxo.confirmations;\n let maxConfs = utxo.confirmations;\n for (let s = 0; s < secondaryMaps.length; s++) {\n const entry = secondaryMaps[s]!.get(key);\n const name = providerName(s + 1);\n if (!entry) {\n throw new Error(\n `Confirmed UTXO ${key} present on ${providerName(0)} but absent on ${name}; refusing to sign (possible fabricated UTXO).`\n );\n }\n if (entry.value !== utxo.satoshis) {\n throw new Error(\n `Confirmed UTXO ${key} value mismatch: ${providerName(0)}=${utxo.satoshis.toString()} vs ${name}=${entry.value.toString()}; refusing to sign.`\n );\n }\n if (entry.confirmations < minConfs) minConfs = entry.confirmations;\n if (entry.confirmations > maxConfs) maxConfs = entry.confirmations;\n }\n\n if (maxConfs - minConfs > CONFIRMATION_SKEW_TOLERANCE) {\n throw new Error(\n `Confirmed UTXO ${key} confirmation spread ${maxConfs - minConfs} exceeds tolerance ${CONFIRMATION_SKEW_TOLERANCE} (min ${minConfs}, max ${maxConfs}); providers disagree on depth, refusing to sign.`\n );\n }\n if (minConfs < minConfirmations) {\n // Benign tip skew at the boundary: present + value-matched everywhere\n // but a provider is a block behind. Demote (exclude) until it matures.\n confirmedKeys.delete(key);\n demoted.push(key);\n }\n }\n if (demoted.length > 0) {\n litDebugLog(\n `[VaultBalance] confirmed-consensus: ${demoted.length} UTXO(s) demoted pending provider tip skew (excluded until matured): ${demoted.join(\", \")}`\n );\n }\n\n // Symmetric direction (finding #6): a confirmed outpoint a SECONDARY\n // reports that the primary omits \u2014 or reports at a wildly lower depth /\n // different value \u2014 is a deflation attempt (suppress collateral \u2192 wrongful\n // liquidation) or a materially desynced provider. The primary-direction\n // loop above cannot see it because it iterates only the primary's set.\n // Compared against the primary's FULL UTXO set (mempool included), so a\n // boundary UTXO the primary merely has at a lower depth takes the skew /\n // demote semantics, not this absence throw. NOTE: this can throw\n // transiently when the primary has already seen a just-broadcast vault\n // spend in its mempool (outpoint removed) and a secondary has not \u2014 that\n // is fail-closed in the safe direction and resolves on retry.\n const primaryByKey = new Map(\n primaryUtxos.map((utxo) => [`${utxo.txid}:${utxo.vout}`, utxo])\n );\n for (let s = 0; s < secondaryMaps.length; s++) {\n const name = providerName(s + 1);\n for (const [key, entry] of secondaryMaps[s]!) {\n if (entry.confirmations < minConfirmations) continue;\n const primaryUtxo = primaryByKey.get(key);\n if (!primaryUtxo) {\n throw new Error(\n `Confirmed UTXO ${key} present on ${name} (${entry.confirmations} confs) but absent on ` +\n `${providerName(0)}; refusing to sign (possible omitted UTXO / balance deflation \u2014 ` +\n `may be transient during an in-flight vault spend).`\n );\n }\n if (primaryUtxo.satoshis !== entry.value) {\n throw new Error(\n `Confirmed UTXO ${key} value mismatch: ${providerName(0)}=${primaryUtxo.satoshis.toString()} ` +\n `vs ${name}=${entry.value.toString()}; refusing to sign.`\n );\n }\n if (entry.confirmations - primaryUtxo.confirmations > CONFIRMATION_SKEW_TOLERANCE) {\n throw new Error(\n `Confirmed UTXO ${key} depth disagreement: ${providerName(0)}=${primaryUtxo.confirmations} ` +\n `vs ${name}=${entry.confirmations} exceeds tolerance ${CONFIRMATION_SKEW_TOLERANCE}; ` +\n `the primary may be under-reporting depth to suppress collateral, refusing to sign.`\n );\n }\n }\n }\n return confirmedKeys;\n }\n\n /**\n * Classify unconfirmed UTXOs as protocol self-change.\n *\n * A UTXO below minConfirmations counts as confirmed-equivalent ONLY when the\n * transaction that created it spends exclusively vault-owned, confirmed\n * outputs. Such a transaction can only have been signed by the vault's PKP,\n * so no third party can RBF-replace or double-spend it \u2014 the reversal risk\n * the confirmation gate exists to close does not apply. Any non-vault input,\n * unconfirmed funding tx, or coinbase input disqualifies the UTXO\n * (fail-safe: exclusion, never inclusion).\n *\n * Multi-provider consensus (audit C-1/C-2 parity): the parent-tx proof is\n * verified independently against EVERY configured provider and admitted\n * only on unanimity. The confirmed-balance consensus the validators run\n * covers `chain_stats` only, so without this the primary provider alone\n * could fabricate an unconfirmed UTXO plus a self-consistent parent proof\n * and inflate the signed balance. Any verdict disagreement THROWS\n * (fail-closed) \u2014 exclusion on a suppressed proof would deflate the balance\n * and open a wrongful-liquidation window, so neither direction may proceed\n * without agreement. A provider that cannot state the chain tip \u2014 and only\n * that failure \u2014 is dropped from the quorum rather than aborting the read (it\n * never counts as agreeing), and falling below `minConsensusProviders`\n * survivors throws \u2014 see `verifyParentIsSelfSpendConsensus`.\n *\n * The same per-provider `/tx` fetch also returns the parent's outputs, and\n * every provider must corroborate each claimed UTXO (index, vault address,\n * exact value) before admission \u2014 the UTXO list itself comes only from the\n * primary, so an unchecked claim would let it attach a fabricated or\n * inflated output to a genuine self-spend.\n *\n * Fetch cost: zero when every UTXO is confirmed (the common case); otherwise\n * per provider: one tx lookup per classified parent (vins + vouts in one\n * response), plus per distinct funding tx a confirmation check and \u2014 only\n * when the provider omits vin prevout data \u2014 an output lookup. Classified\n * parents are capped at MAX_CLASSIFIED_PARENTS (largest claimed value\n * first, deterministic) and evaluated CLASSIFICATION_CONCURRENCY at a time,\n * so third-party dust spam cannot amplify into provider rate-limiting and\n * an action-wide outage.\n *\n * See docs/vault-balance-confirmed-gate-plan-2026-07-14.md \u00A73.1.\n *\n * @param utxos - Full UTXO set for the vault address\n * @param vaultAddress - Bitcoin address of the vault (may carry network prefix)\n * @param minConfirmations - Confirmation threshold for the chain\n * @returns Set of \"txid:vout\" keys for UTXOs verified as self-change\n */\n async classifySelfChange(\n utxos: UTXO[],\n vaultAddress: string,\n minConfirmations: number\n ): Promise<Set<string>> {\n const providerConfigs = this.providerConfigs;\n const readers = this.readers;\n\n const selfChange = new Set<string>();\n const unconfirmed = utxos.filter(\n (utxo) => utxo.confirmations < minConfirmations\n );\n if (unconfirmed.length === 0) {\n return selfChange;\n }\n\n // P1/#1: below the policy floor a self-change proof cannot be unanimously\n // verified, and silently excluding (deflating) opens the wrongful-\n // liquidation window this module's own docs warn about. Fail closed.\n this.assertProviderFloor(\"classifySelfChange\");\n\n if (!providerConfigs || providerConfigs.length === 0 || !readers) {\n // No Esplora access configured \u2014 unconfirmed UTXOs cannot be verified\n // as self-change and stay excluded (fail-safe).\n litDebugLog(\n `[VaultBalance] ${unconfirmed.length} unconfirmed UTXO(s) excluded: no bitcoinProviderConfigs for self-change classification`\n );\n return selfChange;\n }\n\n const cleanVaultAddress = stripNetworkPrefix(vaultAddress);\n\n // Group claims per parent tx, then rank parents by total claimed value\n // (desc, txid asc tiebreak). The ordering is a pure function of the UTXO\n // set, so every LIT node classifies the same parents and consensus\n // reconciliation is unaffected.\n const claimsByParent = new Map<string, UTXO[]>();\n for (const utxo of unconfirmed) {\n const claims = claimsByParent.get(utxo.txid) ?? [];\n claims.push(utxo);\n claimsByParent.set(utxo.txid, claims);\n }\n const claimedSum = (txid: string) =>\n claimsByParent\n .get(txid)!\n .reduce((sum, utxo) => sum + utxo.satoshis, 0n);\n const rankedParents = [...claimsByParent.keys()].sort((a, b) => {\n const diff = claimedSum(b) - claimedSum(a);\n if (diff !== 0n) {\n return diff > 0n ? 1 : -1;\n }\n return a < b ? -1 : a > b ? 1 : 0;\n });\n const parentTxids = rankedParents.slice(0, MAX_CLASSIFIED_PARENTS);\n const skippedParents = rankedParents.length - parentTxids.length;\n if (skippedParents > 0) {\n litDebugLog(\n `[VaultBalance] self-change: ${skippedParents} parent tx(s) beyond the ${MAX_CLASSIFIED_PARENTS}-parent classification budget excluded (mempool-spam bound; largest claimed value classified first)`\n );\n }\n\n const verdicts = await mapWithConcurrency(\n parentTxids,\n CLASSIFICATION_CONCURRENCY,\n async (parentTxid) => ({\n parentTxid,\n verified: await this.verifyParentIsSelfSpendConsensus(\n parentTxid,\n claimsByParent.get(parentTxid)!,\n cleanVaultAddress,\n minConfirmations,\n providerConfigs,\n readers\n ),\n })\n );\n\n const verifiedParents = new Set(\n verdicts.filter((v) => v.verified).map((v) => v.parentTxid)\n );\n for (const utxo of unconfirmed) {\n if (verifiedParents.has(utxo.txid)) {\n selfChange.add(`${utxo.txid}:${utxo.vout}`);\n }\n }\n if (verifiedParents.size > 0) {\n litDebugLog(\n `[VaultBalance] self-change: ${selfChange.size}/${unconfirmed.length} unconfirmed UTXO(s) verified as protocol change by ${providerConfigs.length} provider(s)`\n );\n }\n return selfChange;\n }\n\n /**\n * Run the self-spend proof against every configured provider and require\n * unanimity AMONG THE PROVIDERS THAT ANSWERED. Fail-closed on disagreement:\n * a verdict mismatch throws and aborts the balance calculation \u2014 see\n * classifySelfChange for why exclusion is not a safe fallback here.\n *\n * Quorum semantics (2026-09-23, plan C2). ONE failure class is tolerated: a\n * provider that could not state the chain tip (`BitcoinTipUnreadableError`).\n * It is ABSENT from the quorum \u2014 never counted as agreeing, never allowed to\n * decide the verdict \u2014 and the policy floor, not \"at least one\", decides when\n * that absence is fatal: below `minConsensusProviders` surviving readings\n * there is no cross-check left to trust, and the read fails loudly naming\n * every provider that dropped out.\n *\n * Why only that class. `getTransaction` now throws on an unreadable tip\n * instead of fabricating `confirmations: 1`; without this carve-out one flaky\n * `/blocks/tip/height` endpoint would take every balance and spend path down\n * with it. Every OTHER failure remains fatal, as before: a provider that\n * answers \"I have never seen that transaction\" is making a claim about the\n * chain rather than suffering an outage, and that shape is precisely the\n * fabricated-UTXO signature the fail-closed rule exists to catch.\n *\n * When the parent IS a unanimous self-spend, every provider's view of the\n * parent's OUTPUTS must additionally corroborate the primary's claimed\n * UTXOs (index exists, pays the vault, exact value). Without this, a\n * compromised primary could attach a fabricated or value-inflated output\n * to a genuine self-spend the honest providers happily verify.\n *\n * @returns True when every provider verified the parent and corroborated\n * the claimed outputs, false when every provider rejected the\n * parent (genuine third-party deposit)\n */\n private async verifyParentIsSelfSpendConsensus(\n parentTxid: string,\n claimedUtxos: UTXO[],\n cleanVaultAddress: string,\n minConfirmations: number,\n providerConfigs: SelfChangeProviderConfig[],\n readers: IBitcoinDataProvider[]\n ): Promise<boolean> {\n const providerName = (i: number) =>\n providerConfigs[i]!.name || providerConfigs[i]!.providerUrl;\n\n const settled = await Promise.allSettled(\n providerConfigs.map((cfg, i) =>\n this.evaluateParentForProvider(\n parentTxid,\n claimedUtxos,\n cleanVaultAddress,\n minConfirmations,\n readers[i]!,\n cfg\n )\n )\n );\n\n // Partition into the quorum (providers that answered), the providers that\n // could not state the chain tip (ABSENT), and everything else (fatal). The\n // provider INDEX travels with each entry so every message below still names\n // the real provider once the list is no longer dense.\n const answered: Array<{\n index: number;\n evaluation: { selfSpend: boolean; outputMismatch: string | null };\n }> = [];\n const absences: string[] = [];\n const failures: string[] = [];\n settled.forEach((result, i) => {\n if (result.status === \"fulfilled\") {\n answered.push({ index: i, evaluation: result.value });\n return;\n }\n const described = `${providerName(i)} \u2192 ${result.reason?.message ?? String(result.reason)}`;\n if (isBitcoinTipUnreadableError(result.reason)) {\n absences.push(described);\n return;\n }\n failures.push(described);\n });\n\n // Anything OTHER than an unreadable tip stays fatal, exactly as before.\n // A provider that answers \"I have never seen that transaction\" is making a\n // claim about the chain, not suffering an outage, and that shape IS the\n // fabricated-UTXO signature (review 2026-07-15 P1): dropping it from the\n // quorum would let a compromised primary invent an unconfirmed UTXO and\n // have the honest provider's 404 quietly ignored.\n if (failures.length > 0) {\n throw new Error(\n `Self-change classification failed for tx ${parentTxid} on ${failures.length}/${providerConfigs.length} provider(s): ${failures.join(\"; \")}`\n );\n }\n\n // The floor is the policy's (1 on hardhat/sepolia, 2 on ethereum), never\n // below 1 \u2014 a verdict resting on zero readings would be no verdict at all.\n const floor = Math.max(1, this.minConsensusProviders);\n if (answered.length < floor) {\n throw new Error(\n `Self-change classification for tx ${parentTxid}: only ${answered.length}/${providerConfigs.length} ` +\n `provider(s) could state a confirmation depth, below this chain's floor of ${floor}. ` +\n `Unreadable tips: ${absences.join(\"; \")}`\n );\n }\n if (absences.length > 0) {\n // Loud in the action log, not silent: the read proceeded on a REDUCED\n // quorum, which an operator must be able to see after the fact.\n litDebugLog(\n `[VaultBalance] self-change: tx ${parentTxid} classified on a reduced quorum \u2014 ` +\n `${answered.length}/${providerConfigs.length} provider(s) answered (floor ${floor}); ` +\n `dropped for an unreadable chain tip: ${absences.join(\"; \")}`\n );\n }\n\n const first = answered[0]!;\n const disagreements = answered\n .slice(1)\n .filter((a) => a.evaluation.selfSpend !== first.evaluation.selfSpend)\n .map(\n (a) =>\n `${providerName(first.index)}=${first.evaluation.selfSpend} vs ` +\n `${providerName(a.index)}=${a.evaluation.selfSpend}`\n );\n if (disagreements.length > 0) {\n throw new Error(\n `Self-change consensus mismatch for tx ${parentTxid}: ${disagreements.join(\"; \")}. ` +\n `A provider may be compromised or out of sync; refusing to sign.`\n );\n }\n\n if (!first.evaluation.selfSpend) {\n return false;\n }\n\n const outputMismatches = answered\n .map((a) =>\n a.evaluation.outputMismatch\n ? `${providerName(a.index)} \u2192 ${a.evaluation.outputMismatch}`\n : null\n )\n .filter((m): m is string => m !== null);\n if (outputMismatches.length > 0) {\n throw new Error(\n `Self-change output claim mismatch for tx ${parentTxid}: ${outputMismatches.join(\"; \")}. ` +\n `The reported UTXO set contradicts the parent transaction; refusing to sign.`\n );\n }\n\n return true;\n }\n\n /**\n * Single provider's evaluation of a parent tx: the self-spend proof plus \u2014\n * when the proof holds \u2014 corroboration of the claimed outputs against this\n * provider's view of the parent's vout set. The output check is skipped for\n * non-self-spend parents (their UTXOs are excluded regardless, and a\n * third-party deposit's values are not ours to police).\n */\n private async evaluateParentForProvider(\n parentTxid: string,\n claimedUtxos: UTXO[],\n cleanVaultAddress: string,\n minConfirmations: number,\n reader: IBitcoinDataProvider,\n providerConfig: SelfChangeProviderConfig\n ): Promise<{ selfSpend: boolean; outputMismatch: string | null }> {\n const parentTx = await this.fetchParentTransaction(\n parentTxid,\n providerConfig\n );\n // null == provably coinbase-funded (legitimate \"not self-change\" vote).\n // Provider inability throws inside fetchParentTransaction and surfaces as\n // a named provider failure in the consensus caller (fail-closed).\n if (!parentTx || parentTx.inputs.length === 0) {\n return { selfSpend: false, outputMismatch: null };\n }\n const selfSpend = await this.verifyInputsAreSelfSpend(\n parentTx.inputs,\n cleanVaultAddress,\n minConfirmations,\n reader\n );\n const outputMismatch = selfSpend\n ? findOutputClaimMismatch(claimedUtxos, parentTx.outputs, cleanVaultAddress)\n : null;\n return { selfSpend, outputMismatch };\n }\n\n /**\n * Verify that a transaction's inputs spend exclusively vault-owned,\n * confirmed outputs, using a single provider's view of the chain.\n *\n * @param inputs - Parsed inputs of the parent transaction\n * @param cleanVaultAddress - Vault address with network prefix stripped\n * @param minConfirmations - Required depth for every funding transaction\n * @param reader - Data provider for funding-tx lookups (same provider the inputs came from)\n * @returns True only when every input is a confirmed, vault-owned outpoint\n */\n private async verifyInputsAreSelfSpend(\n inputs: TransactionInput[],\n cleanVaultAddress: string,\n minConfirmations: number,\n reader: IBitcoinDataProvider\n ): Promise<boolean> {\n // Every input must spend an output owned by the vault address. Use the\n // provider's vin prevout when present; otherwise resolve ownership from\n // the funding transaction's outputs (regtest faucet omits prevout).\n const fundingTxids = [...new Set(inputs.map((input) => input.txid))];\n const outputsByFundingTx = new Map<\n string,\n Awaited<ReturnType<IBitcoinDataProvider[\"getTransactionOutputs\"]>>\n >();\n const needsOutputLookup = fundingTxids.filter((fundingTxid) =>\n inputs.some(\n (input) =>\n input.txid === fundingTxid && input.prevoutAddress === undefined\n )\n );\n await Promise.all(\n needsOutputLookup.map(async (fundingTxid) => {\n outputsByFundingTx.set(\n fundingTxid,\n await reader.getTransactionOutputs(fundingTxid)\n );\n })\n );\n\n for (const input of inputs) {\n let ownerAddress: string | undefined = input.prevoutAddress;\n if (ownerAddress === undefined) {\n const outputs = outputsByFundingTx.get(input.txid);\n ownerAddress = outputs?.find(\n (output) => output.index === input.vout\n )?.scriptpubkey_address;\n }\n if (ownerAddress !== cleanVaultAddress) {\n return false;\n }\n }\n\n // Defense in depth: every funding transaction must itself be confirmed to\n // the chain threshold. Protocol coin selection only spends confirmed\n // UTXOs, so this always holds for protocol-created transactions; it\n // protects against a legacy/buggy action version having signed a\n // chained-unconfirmed spend. No recursion \u2014 an unconfirmed ancestor\n // disqualifies.\n const fundingStatuses = await Promise.all(\n fundingTxids.map((fundingTxid) => reader.getTransaction(fundingTxid))\n );\n for (const status of fundingStatuses) {\n if (!status || status.confirmations < minConfirmations) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Fetch a parent transaction's inputs (vins) and outputs (vouts) via Esplora.\n *\n * A module-private fetch (not a `BitcoinDataProvider` method) so editing this\n * consensus logic does not rebundle the shared provider module's other\n * importers \u2014 see this file's header for the ripple-set constraint.\n *\n * @param txid - Transaction ID\n * @param providerConfig - Esplora endpoint to query (one of the configured\n * consensus providers)\n * @returns Parsed inputs + outputs, or null ONLY when the tx is provably not\n * a self-spend candidate (coinbase-funded). Provider inability \u2014\n * 404, malformed vin rows, missing vin array \u2014 THROWS (review\n * 2026-07-15 P1): the parent of a UTXO the primary lists must\n * exist, so \"can't fetch it\" is a provider failure, and treating it\n * as a false self-change vote would silently deflate collateral\n * (wrongful-liquidation direction) if every provider failed the\n * same way.\n */\n private async fetchParentTransaction(\n txid: string,\n providerConfig: SelfChangeProviderConfig\n ): Promise<ParentTransactionData | null> {\n // Every providerUrl is non-empty (checked in the constructor).\n // Same latency budget as BitcoinDataProvider (15s of the 30s action limit)\n const timeout = providerConfig.timeout || 15000;\n\n const controller = new AbortController();\n // The timer stays armed through body parsing \u2014 a stalled response body\n // must count against the same budget as the headers, otherwise a\n // misbehaving provider can hang classification past the configured\n // timeout. Cleared in `finally`.\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n try {\n const response = await fetch(`${providerConfig.providerUrl}/tx/${txid}`, {\n signal: controller.signal,\n headers: await authHeaders(providerConfig.auth, timeout),\n });\n\n if (!response.ok) {\n if (response.status === 404) {\n // The parent of a UTXO the primary lists must exist somewhere \u2014 a\n // 404 means THIS provider cannot serve the proof. Fail closed\n // rather than vote \"not self-change\" (review 2026-07-15 P1).\n throw new Error(\n `parent tx ${txid} not found on this provider \u2014 cannot verify the self-change proof`\n );\n }\n throw new Error(\n `Bitcoin provider error: ${response.status} ${response.statusText}`\n );\n }\n\n const data = (await response.json()) as {\n vin?: Array<{\n txid?: string;\n vout?: number;\n is_coinbase?: boolean;\n prevout?: {\n scriptpubkey_address?: string;\n };\n }>;\n vout?: Array<{\n scriptpubkey_address?: string;\n value?: number;\n }>;\n };\n\n if (!data.vin || !Array.isArray(data.vin) || data.vin.length === 0) {\n // Every real Bitcoin transaction has at least one input \u2014 a missing\n // vin array is a malformed provider response, not a tx property.\n throw new Error(\n `provider returned tx ${txid} without a vin array \u2014 malformed response`\n );\n }\n\n const inputs: TransactionInput[] = [];\n for (const vin of data.vin) {\n if (vin.is_coinbase) {\n // Coinbase-funded: provably NOT a vault self-spend \u2014 a legitimate\n // \"false\" vote, not a provider failure.\n return null;\n }\n if (vin.txid === undefined || vin.vout === undefined) {\n // A non-coinbase input without an outpoint is provider data\n // corruption; fail closed (review 2026-07-15 P1).\n throw new Error(\n `provider returned tx ${txid} with a malformed vin row (missing txid/vout)`\n );\n }\n inputs.push({\n txid: vin.txid,\n vout: vin.vout,\n prevoutAddress: vin.prevout?.scriptpubkey_address,\n });\n }\n\n // Esplora vout rows are positional; a row that omits value/address\n // simply fails the output-claim check for any UTXO that references it.\n const outputs: ParentTxOutput[] = Array.isArray(data.vout)\n ? data.vout.map((vout, index) => ({\n index,\n scriptpubkey_address: vout?.scriptpubkey_address,\n value:\n typeof vout?.value === \"number\" ? BigInt(vout.value) : undefined,\n }))\n : [];\n\n return { inputs, outputs };\n } catch (error: unknown) {\n if (isAbortError(error)) {\n throw new Error(`Request timeout after ${timeout}ms`);\n }\n throw error;\n } finally {\n clearTimeout(timeoutId);\n }\n }\n}\n", "/**\n * Vault Balance Module - Super Module for Trusted Balance Calculation\n *\n * Combines Bitcoin network data with smart contract state to calculate\n * the \"trusted balance\" - the amount available for new authorizations.\n *\n * Formula: Available Balance = Total UTXOs - Authorized Spends\n *\n * This is the primary source of truth for determining if a new spending\n * authorization can be created for a given position.\n */\n\nimport {\n AuthorizedSpend,\n UTXO,\n UTXOSet,\n VaultBalanceConfig,\n VaultBalanceResult,\n} from \"../interfaces/chunks/vault-balance.i\";\n\nimport { IVaultBalance } from \"../interfaces/chunks/vault-balance-module.i\";\nimport { IBitcoinDataProvider } from \"../interfaces/chunks/bitcoin-data-provider.i\";\nimport { LIT_ACTION_ETH_RPC_TIMEOUT_MS } from \"../constants\";\nimport { evmRpcConnection, litNodeRpcUrl } from \"./evm-rpc\";\nimport { VaultBalanceConsensus } from \"./vault-balance-consensus.module\";\n\n/**\n * Vault Balance Module\n *\n * This module is the \"super module\" that combines:\n * 1. Bitcoin network data (UTXOs from bitcoin-data-provider)\n * 2. Smart contract state (authorized spends from contract)\n *\n * To produce: Trusted Balance = Total - Authorized\n *\n * DESIGN NOTES:\n *\n * 1. Change Output Handling:\n * When a UTXO is spent, the change output will have a DIFFERENT txid.\n * This means we don't need special logic for change - it appears as a new UTXO.\n * The old UTXO (original deposit) will be gone from Bitcoin queries.\n *\n * 2. Authorization is Commitment:\n * Any UTXO in the AuthorizedSpend array is considered committed/consumed.\n * Once authorized, it's the user's responsibility to sign and broadcast.\n * If they don't, that's their problem - not the ecosystem's concern.\n *\n * 3. Security Model - Dual Source of Truth:\n * - Bitcoin Network: What UTXOs actually exist\n * - Smart Contract: What UTXOs are authorized to be spent\n * - Available Balance = Total UTXOs - Authorized UTXOs\n *\n * This prevents double-spending by ensuring the same UTXO cannot be\n * authorized twice. The contract's isAuthorizedSpend mapping enforces this.\n *\n * 4. Race Condition Protection:\n * The FAFO (First Actor Fails Others) model protects against concurrent\n * authorization attempts via state hash commitment in quantum time windows.\n * This module provides the trusted balance INPUT to that authorization process.\n *\n * 5. UTXO Matching:\n * We match authorized spends to UTXOs by (txid, vout) pair.\n * A UTXO is available if it exists in Bitcoin but NOT in authorized spends.\n *\n * 6. Edge Cases:\n * - UTXO authorized but not yet spent: Appears in Bitcoin, appears in contract\n * - UTXO spent: Doesn't appear in Bitcoin, may still appear in contract\n * - New deposit: Appears in Bitcoin, doesn't appear in contract\n *\n * 7. Confirmed-Only Gate (+ self-change carve-out):\n * A UTXO contributes to availableBalance only once it reaches\n * minConfirmations \u2014 a 0-conf third-party deposit is RBF-replaceable /\n * double-spendable and must never back a signed collateral figure.\n * EXCEPTION: unconfirmed \"self-change\" (change returned to the vault by a\n * transaction whose every input spends a confirmed, vault-owned output)\n * counts as confirmed-equivalent. Only the vault's PKP can sign such a\n * transaction, so no third party can replace it; excluding it would zero a\n * position's visible collateral for ~minConfirmations blocks after every\n * partial withdrawal and make healthy positions transiently liquidatable.\n * The self-change proof (parent tx inputs, prevout ownership, funding-tx\n * depth) is verified independently against EVERY registered provider and\n * requires unanimity; any disagreement or provider failure aborts the\n * calculation (fail-closed) so a single compromised provider can neither\n * inflate the balance (fabricated change) nor deflate it (suppressed\n * change enabling wrongful liquidation).\n * See docs/vault-balance-confirmed-gate-plan-2026-07-14.md \u00A73.1.\n */\nexport class VaultBalanceModule implements IVaultBalance {\n private config: VaultBalanceConfig;\n private bitcoinProvider: IBitcoinDataProvider;\n\n constructor(config: VaultBalanceConfig) {\n if (\n !Number.isInteger(config.minConfirmations) ||\n config.minConfirmations < 1\n ) {\n throw new Error(\n `VaultBalanceModule: minConfirmations must be a positive integer ` +\n `(got ${config.minConfirmations}). Pass the policy-derived ` +\n `balance-confirmation threshold \u2014 there is no default.`,\n );\n }\n this.config = config;\n this.bitcoinProvider = config.bitcoinProvider;\n }\n\n /**\n * Calculate balance (arithmetic only - no UTXO validation)\n *\n * Balance-only calculation: Total Balance - Authorized Balance = Available.\n *\n * \u26A0\uFE0F SECURITY (remediation P1/#5): this result skips UTXO validation, the\n * confirmed-consensus gate, and self-change proofing. It must NEVER feed a\n * signed BalanceConfirmation or any authorization decision. No production\n * action calls it (the `skipUTXOValidation` fast path that used to route\n * here was deleted); it exists for read-only diagnostics and tests. Adding\n * a production caller requires Master sign-off.\n *\n * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @returns Complete breakdown of vault balance (with empty UTXO arrays)\n */\n async calculateBalance(\n positionId: string,\n vaultAddress: string\n ): Promise<VaultBalanceResult> {\n // 1. Get balance from Bitcoin network (fast, no UTXO details)\n const totalBalance = await this.bitcoinProvider.getBalance(vaultAddress);\n\n // 2. Get authorized spends from smart contract\n const authorizedSpends: AuthorizedSpend[] =\n await this.getAuthorizedSpendsFromContract(positionId);\n\n // 3. Calculate authorized balance (sum of all authorized spends)\n const authorizedBalance = authorizedSpends.reduce(\n (sum, spend) => sum + spend.satoshis,\n 0n\n );\n\n // 4. Calculate available balance = Total - Authorized\n const availableBalance =\n totalBalance > authorizedBalance ? totalBalance - authorizedBalance : 0n;\n\n // 5. Compute authorized spends hash (race prevention)\n // Hash each spend's full details, then hash the array\n // @ts-ignore - ethers available in LIT runtime\n const authorizedSpendsHash = this.computeAuthorizedSpendsHash(\n positionId,\n authorizedSpends\n );\n\n return {\n // Total from Bitcoin\n totalUTXOs: [], // Empty for fast path\n totalBalance,\n\n // Authorized from Contract\n authorizedUTXOs: authorizedSpends,\n authorizedBalance,\n authorizedSpendsHash,\n\n // Available = Total - Authorized (THIS IS THE TRUSTED BALANCE)\n availableUTXOs: [], // Empty for fast path\n availableBalance,\n\n // Metadata\n vaultAddress,\n positionId,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Calculate trusted balance for a position (full validation)\n *\n * This is the main entry point for determining available balance with full validation.\n *\n * CRITICAL: Validates that all authorized spends have been properly broadcasted\n * to Bitcoin network with sufficient confirmations. Throws errors if:\n * 1. Authorized transaction not found on network (not broadcasted)\n * 2. Authorized transaction has insufficient confirmations (network updating)\n *\n * NOTE: the `skipUTXOValidation` fast path was removed (remediation P1/#5).\n * Every trusted-balance read runs full UTXO validation + consensus; a\n * balance that skipped validation must never feed a signed\n * BalanceConfirmation.\n *\n * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @returns Complete breakdown of vault balance\n * @throws Error if authorized spends are in invalid state\n */\n async calculateTrustedBalance(\n positionId: string,\n vaultAddress: string\n ): Promise<VaultBalanceResult> {\n const minConfirmations = this.config.minConfirmations;\n\n // 1. Get all UTXOs from Bitcoin network\n const utxoSet: UTXOSet = await this.bitcoinProvider.getUTXOSet(\n vaultAddress,\n minConfirmations\n );\n\n // 2. Get authorized spends from smart contract\n const authorizedSpends: AuthorizedSpend[] =\n await this.getAuthorizedSpendsFromContract(positionId);\n\n // 3. Authorized spends are COMMITMENTS, not exceptions (design note 2\n // above: \"Once authorized, it's the user's responsibility to sign and\n // broadcast. If they don't, that's their problem\").\n //\n // An authorized outpoint can be in one of two states, and BOTH are\n // handled by exclusion at step 6 rather than by an error here:\n // - already spent \u2192 it is absent from the UTXO set, so it cannot be\n // counted anyway;\n // - authorized but not yet broadcast \u2192 still present in the UTXO set,\n // and `isUTXOAuthorized` removes it from `availableUTXOs`, so the\n // signed collateral figure never includes sats the borrower already\n // holds a signature to move.\n //\n // This loop used to THROW on the second case (\"Authorized UTXO ... not\n // yet spent\"). That turned a borrower-controlled state into a denial of\n // service on the WHOLE module: `calculateTrustedBalance` is the only\n // balance path, and liquidation-validator \u2192 vault-snapshot goes through\n // it, so a borrower could call withdrawBTC while healthy, never\n // broadcast phase 2, and block EVERY liquidation attestation on their\n // position indefinitely (clearing an unspent reservation needs their own\n // signed envelope or the 24h admin timelock) while the position sank\n // into bad debt. Excluding is also the strictly conservative direction:\n // it can only LOWER `availableBalance`, never overstate collateral \u2014 and\n // `availableBalance` is the only figure any caller signs over\n // (vault-snapshot maps it to `availableBTCSats`; `totalBalance` is\n // informational).\n\n // 4. Calculate authorized balance (sum of all authorized spends)\n const authorizedBalance = authorizedSpends.reduce(\n (sum, spend) => sum + spend.satoshis,\n 0n\n );\n\n // Multi-provider consensus over the primary UTXO set. The consensus object\n // owns provider expansion, fan-out, output-claim parsing, confirmation-depth\n // policy, and self-change proofing (built once; both passes share readers).\n const consensus = new VaultBalanceConsensus(\n this.bitcoinProvider,\n this.config.bitcoinProviderConfigs,\n // Absent \u21D2 1: dev/test constructions without a policy keep the\n // single-provider baseline; validators pass policy.minConsensusProviders.\n this.config.minConsensusProviders ?? 1\n );\n\n // 5a. Confirmed-UTXO-set consensus: the primary's confirmed UTXOs are the\n // bulk of the signed balance, yet the UTXO set (txid/vout/value) comes only\n // from the primary \u2014 the balance consensus checks `chain_stats` totals, not\n // individual outpoints. Each primary-confirmed UTXO is cross-checked against\n // EVERY registered provider (strict: present + exact value on all). A\n // fabricated or value-inflated confirmed UTXO throws; benign tip skew at\n // the confirmation boundary demotes the UTXO (it waits a block) rather than\n // signing over a disputed figure.\n const confirmedConsensusKeys = await consensus.confirmedUtxoConsensus(\n utxoSet.utxos,\n vaultAddress,\n minConfirmations\n );\n\n // 5b. Classify unconfirmed UTXOs: only protocol self-change may bypass the\n // confirmation gate (no network calls when everything is confirmed)\n const selfChangeKeys = await consensus.classifySelfChange(\n utxoSet.utxos,\n vaultAddress,\n minConfirmations\n );\n\n // 6. Filter to available UTXOs. A UTXO is available only when it is\n // (a) confirmed with multi-provider consensus OR verified protocol\n // self-change, AND\n // (b) not committed to an authorized spend.\n // (b) is judged against the FULL UTXO set (confirmed + mempool) on purpose:\n // an authorized outpoint whose spending transaction is sitting in the\n // mempool must STAY excluded \u2014 it must not re-enter the collateral figure\n // merely because it is no longer confirmed.\n const availableUTXOs = utxoSet.utxos.filter(\n (utxo) =>\n (confirmedConsensusKeys.has(`${utxo.txid}:${utxo.vout}`) ||\n selfChangeKeys.has(`${utxo.txid}:${utxo.vout}`)) &&\n !this.isUTXOAuthorized(utxo, authorizedSpends)\n );\n\n // 7. Calculate available balance\n const availableBalance = availableUTXOs.reduce(\n (sum, utxo) => sum + utxo.satoshis,\n 0n\n );\n\n // 8. Compute authorized spends hash (race prevention)\n // Hash each spend's full details, then hash the array\n // @ts-ignore - ethers available in LIT runtime\n const authorizedSpendsHash = this.computeAuthorizedSpendsHash(\n positionId,\n authorizedSpends\n );\n\n return {\n // Total from Bitcoin\n totalUTXOs: utxoSet.utxos,\n totalBalance: utxoSet.totalBalance,\n\n // Authorized from Contract\n authorizedUTXOs: authorizedSpends,\n authorizedBalance,\n authorizedSpendsHash,\n\n // Available = Total - Authorized (THIS IS THE TRUSTED BALANCE)\n availableUTXOs,\n availableBalance,\n\n // Metadata\n vaultAddress,\n positionId,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Get just the trusted balance amount\n *\n * Convenience method when you only need the number.\n *\n * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @returns Available balance in satoshis\n */\n async getTrustedBalance(\n positionId: string,\n vaultAddress: string\n ): Promise<bigint> {\n const result = await this.calculateTrustedBalance(positionId, vaultAddress);\n return result.availableBalance;\n }\n\n /**\n * Get available UTXOs that can be used for new authorizations\n *\n * This is useful when you need to select specific UTXOs for authorization.\n *\n * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @returns Array of available UTXOs\n */\n async getAvailableUTXOs(\n positionId: string,\n vaultAddress: string\n ): Promise<UTXO[]> {\n const result = await this.calculateTrustedBalance(positionId, vaultAddress);\n return result.availableUTXOs;\n }\n\n /**\n * Check if a specific UTXO is available for authorization\n *\n * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @param txid - Transaction ID of the UTXO\n * @param vout - Output index of the UTXO\n * @returns True if UTXO is available, false otherwise\n */\n async isUTXOAvailable(\n positionId: string,\n vaultAddress: string,\n txid: string,\n vout: number\n ): Promise<boolean> {\n const availableUTXOs = await this.getAvailableUTXOs(\n positionId,\n vaultAddress\n );\n return availableUTXOs.some(\n (utxo) => utxo.txid === txid && utxo.vout === vout\n );\n }\n\n /**\n * Check if a UTXO is authorized (appears in authorized spends)\n *\n * @param utxo - The UTXO to check\n * @param authorizedSpends - List of authorized spends from contract\n * @returns True if UTXO is authorized, false otherwise\n */\n private isUTXOAuthorized(\n utxo: UTXO,\n authorizedSpends: AuthorizedSpend[]\n ): boolean {\n return authorizedSpends.some(\n (spend) => spend.txid === utxo.txid && spend.vout === utxo.vout\n );\n }\n\n /**\n * Query smart contract for authorized spends\n *\n * Calls the contract's getAuthorizedSpends(positionId) view function\n * to retrieve all authorized Bitcoin spends for this position.\n *\n * Contract struct AuthorizedSpend:\n * - txid: string\n * - vout: uint32\n * - satoshis: uint256\n * - authorizedAt: uint256 (timestamp)\n *\n * @param positionId - The position ID to query\n * @returns Array of authorized spends for this position\n */\n protected async getAuthorizedSpendsFromContract(\n positionId: string\n ): Promise<AuthorizedSpend[]> {\n // For LIT Actions, Lit.Actions.call provides RPC access\n // This uses the ethers.js-like interface available in LIT runtime\n\n // Convert positionId to bytes32 if it's a hex string\n const positionIdBytes32 = positionId.startsWith(\"0x\")\n ? positionId\n : `0x${positionId.padStart(64, \"0\")}`;\n\n // ABI fragment for getAuthorizedSpends function\n const getAuthorizedSpendsABI = [\n {\n inputs: [\n { internalType: \"bytes32\", name: \"positionId\", type: \"bytes32\" },\n ],\n name: \"getAuthorizedSpends\",\n outputs: [\n {\n components: [\n { internalType: \"string\", name: \"txid\", type: \"string\" },\n { internalType: \"uint32\", name: \"vout\", type: \"uint32\" },\n { internalType: \"uint256\", name: \"satoshis\", type: \"uint256\" },\n {\n internalType: \"string\",\n name: \"targetAddress\",\n type: \"string\",\n },\n {\n internalType: \"uint256\",\n name: \"targetAmount\",\n type: \"uint256\",\n },\n // changeAddress removed - contract derives from position.vaultAddress\n {\n internalType: \"uint256\",\n name: \"authorizedAt\",\n type: \"uint256\",\n },\n ],\n internalType: \"struct LoanOperationsManager.AuthorizedSpend[]\",\n name: \"\",\n type: \"tuple[]\",\n },\n ],\n stateMutability: \"view\",\n type: \"function\",\n },\n ];\n\n // Get RPC URL - either from config (for local testing) or from Lit runtime\n let rpcUrl: string;\n\n if (this.config.rpcUrl) {\n // Local testing: use provided RPC URL\n rpcUrl = this.config.rpcUrl;\n } else {\n // Production: get RPC from Lit runtime\n rpcUrl = await litNodeRpcUrl(this.config.chain, this.config.drpcKey);\n }\n\n // Use ethers.js to query the contract directly\n // @ts-ignore - ethers is available in LIT runtime\n // StaticJsonRpcProvider with just chainId (no network name) to avoid validation errors\n // This works for all chains including custom RPCs (ngrok, localhost, hardhat)\n // @ts-ignore - ethers is available in LIT runtime\n const provider = new ethers.providers.StaticJsonRpcProvider(\n evmRpcConnection(rpcUrl, this.config.drpcKey, LIT_ACTION_ETH_RPC_TIMEOUT_MS),\n this.config.chainId\n );\n\n // @ts-ignore - ethers is available in LIT runtime\n const contract = new ethers.Contract(\n this.config.contractAddress,\n getAuthorizedSpendsABI,\n provider\n );\n\n const result = await contract.getAuthorizedSpends(positionIdBytes32);\n\n // Transform contract response to our interface\n return result.map((spend: any) => ({\n txid: spend.txid,\n vout: Number(spend.vout),\n satoshis: BigInt(spend.satoshis.toString()),\n positionId: positionId,\n targetAddress: spend.targetAddress,\n targetAmount: BigInt(spend.targetAmount.toString()),\n // changeAddress removed - contract doesn't return this field\n timestamp: Number(spend.authorizedAt),\n }));\n }\n\n /**\n * Compute authorized spends hash matching contract implementation\n *\n * CRITICAL: Must match LoanOperationsManager.getAuthorizedSpendsHash()\n *\n * Algorithm:\n * 1. For each AuthorizedSpend, hash all 6 fields:\n * - keccak256(txid string)\n * - vout (uint32)\n * - satoshis (uint256)\n * - keccak256(targetAddress string)\n * - targetAmount (uint256)\n * - authorizedAt (uint256 timestamp)\n * 2. Hash the array: keccak256(abi.encode(positionId, array of hashed spends))\n *\n * @param positionId - Position identifier\n * @param authorizedSpends - Array of authorized spends\n * @returns bytes32 hash matching contract\n */\n private computeAuthorizedSpendsHash(\n positionId: string,\n authorizedSpends: AuthorizedSpend[]\n ): string {\n const positionIdBytes32 = positionId.startsWith(\"0x\")\n ? positionId\n : `0x${positionId.padStart(64, \"0\")}`;\n\n // Empty authorized spends case\n if (authorizedSpends.length === 0) {\n // @ts-ignore - ethers available in LIT runtime\n return ethers.utils.keccak256(\n // @ts-ignore - ethers available in LIT runtime\n ethers.utils.defaultAbiCoder.encode(\n [\"bytes32\", \"bytes32[]\"],\n [positionIdBytes32, []]\n )\n );\n }\n\n // Hash each authorized spend with all 6 fields\n const hashedSpends = authorizedSpends.map((spend) => {\n // @ts-ignore - ethers available in LIT runtime\n const txidHash = ethers.utils.keccak256(\n // @ts-ignore - ethers available in LIT runtime\n ethers.utils.toUtf8Bytes(spend.txid)\n );\n // @ts-ignore - ethers available in LIT runtime\n const targetHash = ethers.utils.keccak256(\n // @ts-ignore - ethers available in LIT runtime\n ethers.utils.toUtf8Bytes(spend.targetAddress)\n );\n\n // Hash all 6 fields: txidHash, vout, satoshis, targetHash, targetAmount, authorizedAt\n // @ts-ignore - ethers available in LIT runtime\n return ethers.utils.keccak256(\n // @ts-ignore - ethers available in LIT runtime\n ethers.utils.defaultAbiCoder.encode(\n [\"bytes32\", \"uint32\", \"uint256\", \"bytes32\", \"uint256\", \"uint256\"],\n [\n txidHash,\n spend.vout,\n spend.satoshis.toString(),\n targetHash,\n spend.targetAmount.toString(),\n spend.timestamp, // authorizedAt\n ]\n )\n );\n });\n\n // Hash positionId with array of hashed spends\n // @ts-ignore - ethers available in LIT runtime\n return ethers.utils.keccak256(\n // @ts-ignore - ethers available in LIT runtime\n ethers.utils.defaultAbiCoder.encode(\n [\"bytes32\", \"bytes32[]\"],\n [positionIdBytes32, hashedSpends]\n )\n );\n }\n}\n\n/**\n * Factory function to create VaultBalanceModule instance\n *\n * @param config - Configuration for the module\n * @returns VaultBalanceModule instance\n */\nexport function createVaultBalanceModule(\n config: VaultBalanceConfig\n): VaultBalanceModule {\n return new VaultBalanceModule(config);\n}\n\n/**\n * USAGE EXAMPLE:\n *\n * ```typescript\n * import { createVaultBalanceModule } from './vault-balance.module';\n * import { BitcoinDataProvider } from './bitcoin-data-provider.module';\n *\n * const bitcoinProvider = new BitcoinDataProvider({\n * providerUrl: 'https://blockstream.info/testnet/api'\n * });\n *\n * const vaultBalance = createVaultBalanceModule({\n * contractAddress: '0x...',\n * chain: 'sepolia',\n * bitcoinProvider,\n * minConfirmations: 6\n * });\n *\n * // Get complete balance breakdown\n * const result = await vaultBalance.calculateTrustedBalance(\n * 'position123',\n * 'tb1q...'\n * );\n *\n * console.log('Total Balance:', result.totalBalance, 'sats');\n * console.log('Authorized Balance:', result.authorizedBalance, 'sats');\n * console.log('Available Balance:', result.availableBalance, 'sats');\n *\n * // Or just get the available amount\n * const available = await vaultBalance.getTrustedBalance('position123', 'tb1q...');\n * console.log('Can authorize:', available, 'sats');\n * ```\n */\n", "/**\n * Chain-derived security policy for LIT Actions.\n *\n * Replaces the previous attacker-supplied `auth.mode === \"prod\" | \"dev\"`\n * toggle (see audit finding C-1). Policy is derived from the `chain` string\n * the caller passes, after running it through `validateChain` \u2014 anything\n * outside the known chain set is rejected up front.\n *\n * Because every signed EIP-712 payload produced downstream binds the\n * chainId via OZ EIP712Upgradeable (block.chainid at verify time), an\n * attacker who lies about `chain` to soften the policy can only obtain a\n * signature valid under the chain they claimed \u2014 which is useless against\n * any other chain's contracts. Chain binding is therefore sufficient to\n * make per-chain policy an authoritative switch.\n */\n\nimport {\n APPROVED_EVM_RPC_DOMAINS,\n BitcoinNetwork,\n CHAIN_TO_BITCOIN_NETWORK,\n CHAIN_TO_CHAIN_ID,\n EVMChain,\n validateChain,\n} from \"../constants\";\n\nexport interface ChainPolicy {\n chain: EVMChain;\n chainId: number;\n bitcoinNetwork: BitcoinNetwork;\n /**\n * When true, the caller-supplied Bitcoin provider URL is accepted without\n * looking it up in any allowlist / registry. Only hardhat (regtest) sets\n * this \u2014 the local Bitcoin daemon URL is never fixed.\n */\n allowArbitraryBitcoinProvider: boolean;\n /**\n * When true, the caller-supplied EVM RPC URL is accepted without\n * matching APPROVED_EVM_RPC_DOMAINS. Only hardhat sets this \u2014 we\n * want to allow `http://localhost:8545` during local tests.\n */\n allowArbitraryEvmRpc: boolean;\n /**\n * When true, the security-critical contract addresses are taken from the\n * generated pinned map (constants/chunks/deployment-addresses.ts) and any\n * caller-supplied values are IGNORED \u2014 a contradicting supplied value is\n * rejected loudly (F1 remediation). sepolia + ethereum set this; hardhat\n * does not, because local deployments are freshly generated per run and\n * carry no real funds, so the caller-supplied addresses are used as before.\n *\n * This is the ONLY switch that decides \"real chain\" for address pinning, and\n * \u2014 like allowArbitraryEvmRpc \u2014 it is bound to the signed `chain` string, not\n * to any mutable server env. A caller who lies about `chain` to soften the\n * policy only obtains a signature valid on the claimed chain, useless\n * elsewhere (EIP-712 binds block.chainid at verify time).\n */\n pinContractAddresses: boolean;\n /**\n * When true, a validator may run the price oracle in single-provider plaintext\n * mode (one un-encrypted key) instead of the locked 3-of-3 encrypted set. Only\n * hardhat sets this \u2014 it lets the local mega test run with the one key we hold.\n * sepolia/mainnet keep it false, so a requested dev price flag is REJECTED there;\n * and because a price is signed against this chain's EIP-712 domain, a hardhat-\n * signed single-provider price is unusable on any other chain anyway.\n */\n allowDevSinglePriceProvider: boolean;\n /**\n * Confirmations a UTXO needs before it counts toward \"confirmed vault\n * balance\" (regtest/testnet=1, mainnet=6). This is the single definition of\n * confirmed balance used by EVERY balance-reading flow \u2014 deposit\n * confirmation, mint, address-balance, and the extend/liquidation/payment\n * collateral checks \u2014 so all validators agree on what a vault holds.\n * NEVER use this to gate UTXO spends; that is `minBitcoinSpendConfirmations`.\n */\n minBitcoinBalanceConfirmations: number;\n /**\n * Confirmations a UTXO needs before the protocol may SPEND it\n * (regtest/testnet=1, mainnet=6). Reorg protection on outgoing transactions\n * \u2014 used by the btc-withdrawal spend gate and as the stale-spend recovery\n * floor. Must never be looser than the balance threshold.\n */\n minBitcoinSpendConfirmations: number;\n /**\n * Minimum number of registered Bitcoin providers required before any\n * balance-consensus read may proceed (fail-closed below the floor \u2014 see\n * tasks/security/btc-lit-actions-remediation-plan-2026-07-15.md P1/#1).\n * hardhat: 1 (single local daemon is the legitimate dev baseline).\n * sepolia: 1 (single faucet provider by design \u2014 the consensus floor is a\n * mainnet guarantee; multi-provider paths are covered by unit tests).\n * ethereum: 2 (registry holds Validation Cloud + Blockstream Enterprise\n * after the 2026-09 Maestro retirement; raise to 3 once a third independent\n * operator is registered).\n */\n minConsensusProviders: number;\n}\n\nconst POLICY_BY_CHAIN: Record<EVMChain, ChainPolicy> = {\n [EVMChain.HARDHAT]: {\n chain: EVMChain.HARDHAT,\n chainId: CHAIN_TO_CHAIN_ID[EVMChain.HARDHAT],\n bitcoinNetwork: CHAIN_TO_BITCOIN_NETWORK[EVMChain.HARDHAT],\n allowArbitraryBitcoinProvider: true,\n allowArbitraryEvmRpc: true,\n pinContractAddresses: false,\n allowDevSinglePriceProvider: true,\n minBitcoinBalanceConfirmations: 1,\n minBitcoinSpendConfirmations: 1,\n minConsensusProviders: 1,\n },\n [EVMChain.SEPOLIA]: {\n chain: EVMChain.SEPOLIA,\n chainId: CHAIN_TO_CHAIN_ID[EVMChain.SEPOLIA],\n bitcoinNetwork: CHAIN_TO_BITCOIN_NETWORK[EVMChain.SEPOLIA],\n allowArbitraryBitcoinProvider: false,\n allowArbitraryEvmRpc: false,\n pinContractAddresses: true,\n allowDevSinglePriceProvider: false,\n minBitcoinBalanceConfirmations: 1,\n minBitcoinSpendConfirmations: 1,\n // 2 since 2026-09-23. It was 1 because Sepolia ran a single faucet provider\n // \"by design\", so the consensus floor was documented as a mainnet-only\n // guarantee. The registry now holds two, and leaving the floor at 1 meant\n // Sepolia could never exercise the multi-provider agreement the stale-spend\n // and balance paths rely on \u2014 the one environment where that logic is\n // supposed to be proved before mainnet.\n minConsensusProviders: 2,\n },\n [EVMChain.ETHEREUM]: {\n chain: EVMChain.ETHEREUM,\n chainId: CHAIN_TO_CHAIN_ID[EVMChain.ETHEREUM],\n bitcoinNetwork: CHAIN_TO_BITCOIN_NETWORK[EVMChain.ETHEREUM],\n allowArbitraryBitcoinProvider: false,\n allowArbitraryEvmRpc: false,\n pinContractAddresses: true,\n allowDevSinglePriceProvider: false,\n minBitcoinBalanceConfirmations: 6,\n minBitcoinSpendConfirmations: 6,\n minConsensusProviders: 2,\n },\n};\n\n/**\n * Resolve the security policy for a chain string. Throws on unknown chains.\n */\nexport function getChainPolicy(chain: string): ChainPolicy {\n const validated = validateChain(chain);\n const policy = POLICY_BY_CHAIN[validated];\n if (!policy) {\n // Unreachable: validateChain only ever returns a known EVMChain value.\n throw new Error(`No chain policy registered for \"${chain}\"`);\n }\n return policy;\n}\n\n/**\n * Validate an EVM RPC URL under the given policy.\n *\n * hardhat \u2192 no-op.\n * sepolia / ethereum \u2192 hostname must equal or end with an approved domain\n * from APPROVED_EVM_RPC_DOMAINS. The `endsWith(\".<domain>\")` rule already\n * covers subdomains like `sepolia.drpc.org` / `eth-mainnet.g.alchemy.com`\n * would match `drpc.org` / an `alchemy.com` entry without extra config.\n *\n * Throws on mismatch so the caller doesn't accidentally fall through to an\n * attacker-controlled RPC.\n */\nexport function validateEvmRpcForPolicy(\n policy: ChainPolicy,\n rpcUrl: string,\n): void {\n if (policy.allowArbitraryEvmRpc) {\n return;\n }\n if (!rpcUrl || typeof rpcUrl !== \"string\") {\n throw new Error(\"validateEvmRpcForPolicy: rpcUrl must be a non-empty string\");\n }\n let hostname: string;\n try {\n hostname = new URL(rpcUrl).hostname;\n } catch (e: any) {\n throw new Error(`Invalid rpcUrl: ${e?.message ?? String(e)}`);\n }\n const approved = APPROVED_EVM_RPC_DOMAINS.some(\n (domain) => hostname === domain || hostname.endsWith(`.${domain}`),\n );\n if (!approved) {\n throw new Error(\n `Custom RPC domain \"${hostname}\" is not in the approved list: ${APPROVED_EVM_RPC_DOMAINS.join(\", \")}`,\n );\n }\n}\n", "/**\n * Price Oracle Executor - NOLA (No LIT Action)\n *\n * Standalone executor that wraps PriceOracleModule for Node.js execution.\n * Reuses the same pattern as tests/helpers/setup-lit-env.ts.\n *\n * Purpose: FREE price queries without paying for LIT Action execution.\n * Use case: Display current BTC price, calculate mint previews, show collateral ratios.\n *\n * Architecture:\n * - Same price-oracle.module.ts code (zero changes)\n * - Inject Node.js fetch instead of Lit.Actions.*\n * - Returns identical price data with 8 decimals\n *\n * The previously-exposed `executePriceOracleConsensus` variant was removed in\n * the H-2 audit fix \u2014 the lenient consensus algorithm is gone, so there is now\n * only one strict path.\n */\n\nimport { PriceOracleModule } from \"../../../src/modules/price-oracle.module\";\nimport { PriceSourceConfig } from \"../../../src/interfaces/chunks/price-oracle.i\";\n\n/**\n * Parameters for price oracle execution\n */\nexport interface PriceOracleExecutorParams {\n priceProviders?: Array<{\n name: string;\n apiKey?: string;\n apiSecret?: string;\n }>;\n customSources?: PriceSourceConfig[];\n mode?: \"dev\" | \"prod\";\n}\n\n/**\n * Execute price oracle in Node.js (NOLA - No LIT Action).\n *\n * Strict 3-of-3: caller must supply exactly 3 distinct providers from the\n * locked set (cryptocompare, coinmarketcap, coingecko). Any single provider\n * failure aborts the call; the 3 prices must lie within 1% of each other.\n *\n * @param params - Optional configuration\n * @returns BTC price in USD with 8 decimals (bigint)\n */\nexport async function executePriceOracle(\n params?: PriceOracleExecutorParams\n): Promise<bigint> {\n // Setup Lit.Actions mock (same pattern as tests/helpers/setup-lit-env.ts)\n // Note: We don't cleanup to avoid race conditions with background promises\n (global as any).Lit = {\n Actions: {\n /**\n * Broadcast and collect (NOLA mode: single node, just return value)\n * In LIT Actions environment, this would collect values from all nodes.\n * In NOLA executor, we're running on a single trusted node, so return single value.\n */\n broadcastAndCollect: async ({\n name,\n value,\n }: {\n name: string;\n value: string;\n }): Promise<string[]> => {\n // NOLA: Single node execution, return array with single value\n return [value];\n },\n },\n };\n\n // Initialize price oracle with optional config\n const oracle = params?.customSources\n ? new PriceOracleModule({}, params.customSources, params?.mode)\n : new PriceOracleModule(params?.priceProviders, undefined, params?.mode);\n\n // Execute - returns identical price as LIT Action would\n return await oracle.getBTCPrice();\n}\n", "/**\n * NOLA Executors Catalog\n *\n * Standalone executors for running LIT Action modules in Node.js (NOLA - No LIT Action).\n * These executors wrap existing modules with Node.js providers for FREE data access.\n *\n * Use cases:\n * - Position listing (100 positions = FREE)\n * - Collateral ratio display (FREE)\n * - Mint preview/validation (FREE)\n * - Any data view that doesn't require PKP signature\n *\n * Architecture: Same code as LIT Actions, different execution context.\n */\n\n// Import executors\nimport { executeVaultSnapshot, VaultSnapshotExecutorParams } from './chunks/vault-snapshot-executor';\nimport { executePriceOracle, PriceOracleExecutorParams } from './chunks/price-oracle-executor';\n\n/**\n * NOLA Executors Catalog\n *\n * Registry of all available NOLA executors with metadata.\n */\nexport const NOLA_EXECUTORS = {\n /**\n * Vault Snapshot Executor\n *\n * Returns complete position health metrics:\n * - BTC balance (total, authorized, available)\n * - Collateral ratio and liquidation risk\n * - Term status (duration, expiry, grace period)\n * - Protocol parameters (fees, thresholds)\n *\n * Cost: FREE (no LIT Action execution)\n * Same data as LIT Action would return\n */\n vaultSnapshot: {\n name: 'vault-snapshot',\n description: 'Get complete position health metrics',\n executor: executeVaultSnapshot,\n version: '1.0.0',\n },\n\n /**\n * Price Oracle Executor\n *\n * Returns BTC price in USD (8 decimals) via strict 3-of-3 consensus:\n * - All 3 configured providers must respond\n * - Prices must agree within 1%\n * - Returns the median\n *\n * Cost: FREE (no LIT Action execution)\n * Use for: Price display, mint preview, collateral ratio calculation\n */\n priceOracle: {\n name: 'price-oracle',\n description: 'Get current BTC price (strict 3-of-3 consensus)',\n executor: executePriceOracle,\n version: '2.0.0',\n },\n} as const;\n\n// Re-export executors for direct import\nexport { executeVaultSnapshot } from './chunks/vault-snapshot-executor';\nexport { executePriceOracle } from './chunks/price-oracle-executor';\n\n// Re-export types\nexport type { VaultSnapshotExecutorParams } from './chunks/vault-snapshot-executor';\nexport type { PriceOracleExecutorParams } from './chunks/price-oracle-executor';\n", "/**\n * EIP-712 type definitions for the two **owner-signed BTC-custody** messages:\n * the withdrawal execute step and the stale-spend invalidate step\n * (`contracts/docs/EIP712_DOMAIN_SPEC.md` \u00A73.8; plan\n * `docs/vigil/plans/2026-10-16-A2-eip712-withdrawal-authorization-plan.md`).\n *\n * **Single source of truth** for the verifier side. The SDK carries a copy\n * (`sdk/src/utils/btc-spend-request-712.ts`) until it depends on a\n * `dh-lit-actions` that exports this module; the golden vectors in\n * `tests/vectors/btc-spend-request.v1.json` keep the two byte-identical.\n *\n * ## Why a separate module from `borrower-authorization-types.ts`\n *\n * Different domain: these bind to the **BTCSpendAuthorizer** proxy, the\n * contract that holds the spend record the signature consumes, not to the\n * LoanOperationsManager. It is also deliberately kept out of the\n * `constants/index.ts` barrel that every action imports, so only the two\n * actions that verify these messages change bytes when it changes.\n *\n * ## Naming\n *\n * Owner-signed types are `*Request`. \u00A73.4's `BtcSpendAuth` is the validator\n * PKP's attestation \u2014 a different signer over a different digest.\n */\n\nimport { getPinnedContractAddresses } from \"./chunks/deployment-addresses\";\nimport {\n PROTOCOL_EIP712_DOMAIN_NAME,\n PROTOCOL_EIP712_DOMAIN_VERSION,\n} from \"./message-hash-domains\";\n\n/** One EIP-712 struct member. Shape is compatible with both ethers v5 and v6. */\nexport interface BtcSpendRequestField {\n readonly name: string;\n readonly type: string;\n}\n\nexport const BTC_SPEND_REQUEST_PRIMARY_TYPES = {\n EXECUTE: \"ExecuteBtcWithdrawalRequest\",\n INVALIDATE: \"InvalidateStaleSpendRequest\",\n} as const;\n\nexport type BtcSpendRequestPrimaryType =\n (typeof BTC_SPEND_REQUEST_PRIMARY_TYPES)[keyof typeof BTC_SPEND_REQUEST_PRIMARY_TYPES];\n\n/**\n * Field lists per primary type. **Order is part of the digest** \u2014 appending,\n * reordering, or renaming a member changes every signature and invalidates\n * the ERC-7730 descriptor in the same step.\n *\n * Execute lists what the borrower judges first (destination, what arrives,\n * the fee, the total) ahead of protocol bookkeeping, so a device that\n * truncates still shows the decision-relevant fields.\n */\nexport const BTC_SPEND_REQUEST_FIELDS: Readonly<\n Record<BtcSpendRequestPrimaryType, readonly BtcSpendRequestField[]>\n> = {\n ExecuteBtcWithdrawalRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"withdrawalAddress\", type: \"string\" },\n { name: \"recipientAmount\", type: \"uint256\" },\n { name: \"networkFee\", type: \"uint256\" },\n { name: \"totalDeduction\", type: \"uint256\" },\n { name: \"spendTxid\", type: \"string\" },\n { name: \"spendVout\", type: \"uint32\" },\n { name: \"inputSetHash\", type: \"bytes32\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n InvalidateStaleSpendRequest: [\n { name: \"positionId\", type: \"bytes32\" },\n { name: \"spendTxid\", type: \"string\" },\n { name: \"spendVout\", type: \"uint32\" },\n { name: \"quantumTimestamp\", type: \"uint256\" },\n ],\n} as const;\n\n/**\n * Frozen `encodeType` strings. Duplicated from the field lists on purpose:\n * they are the exact `display.formats` keys of the ERC-7730 descriptor, and\n * the unit suite asserts an encoder derives these same strings from\n * `BTC_SPEND_REQUEST_FIELDS`.\n */\nexport const BTC_SPEND_REQUEST_ENCODE_TYPES: Readonly<\n Record<BtcSpendRequestPrimaryType, string>\n> = {\n ExecuteBtcWithdrawalRequest:\n \"ExecuteBtcWithdrawalRequest(bytes32 positionId,string withdrawalAddress,uint256 recipientAmount,uint256 networkFee,uint256 totalDeduction,string spendTxid,uint32 spendVout,bytes32 inputSetHash,uint256 quantumTimestamp)\",\n InvalidateStaleSpendRequest:\n \"InvalidateStaleSpendRequest(bytes32 positionId,string spendTxid,uint32 spendVout,uint256 quantumTimestamp)\",\n} as const;\n\n/** EIP-712 domain for BTC-custody owner authorizations. */\nexport interface BtcSpendRequestDomain {\n readonly name: string;\n readonly version: string;\n readonly chainId: number;\n readonly verifyingContract: string;\n}\n\n/**\n * The `types` argument for `TypedDataEncoder.hash(domain, types, message)`.\n * Returns ONLY the requested primary type, so a message shaped like the other\n * type cannot encode without complaint.\n *\n * @throws if `primaryType` is not one of the two.\n */\nexport function btcSpendRequestTypes(\n primaryType: BtcSpendRequestPrimaryType,\n): Record<string, BtcSpendRequestField[]> {\n const fields = BTC_SPEND_REQUEST_FIELDS[primaryType];\n if (!fields) {\n throw new Error(\n `Unknown BTC spend request primary type \"${primaryType}\"; ` +\n `expected one of ${Object.keys(BTC_SPEND_REQUEST_FIELDS).join(\", \")}`,\n );\n }\n return { [primaryType]: fields.map((field) => ({ ...field })) };\n}\n\n/**\n * Build the EIP-712 domain for a chain. `verifyingContract` is the pinned\n * BTCSpendAuthorizer proxy. Same rule as `buildBorrowerAuthorizationDomain`:\n * on a pinned chain an override is CHECKED, never honoured, and a\n * contradicting value throws; on an unpinned chain (hardhat) the override\n * supplies the domain and its absence throws.\n */\nexport function buildBtcSpendRequestDomain(\n chainId: number,\n verifyingContractOverride?: string,\n): BtcSpendRequestDomain {\n if (!Number.isInteger(chainId) || chainId <= 0) {\n throw new Error(\n `BTC spend request domain requires a positive integer chainId, got ${String(chainId)}`,\n );\n }\n\n const pinned = getPinnedContractAddresses(chainId);\n const pinnedAuthorizer = pinned?.BTCSpendAuthorizer;\n\n if (pinnedAuthorizer && verifyingContractOverride) {\n if (pinnedAuthorizer.toLowerCase() !== verifyingContractOverride.toLowerCase()) {\n throw new Error(\n `Refusing a caller-supplied verifyingContract that contradicts the pin for chainId ${chainId}: ` +\n `caller ${verifyingContractOverride}, pinned ${pinnedAuthorizer}`,\n );\n }\n }\n\n const verifyingContract = pinnedAuthorizer ?? verifyingContractOverride;\n if (!verifyingContract) {\n throw new Error(\n `No pinned BTCSpendAuthorizer for chainId ${chainId} and no verifyingContract supplied; ` +\n `refusing to build a BTC spend request domain without one`,\n );\n }\n\n return {\n name: PROTOCOL_EIP712_DOMAIN_NAME,\n version: PROTOCOL_EIP712_DOMAIN_VERSION,\n chainId,\n verifyingContract,\n };\n}\n\n/**\n * Canonical Bitcoin txid for a typed message: lowercase, no `0x`, exactly 64\n * hex characters. BTCSpendAuthorizer stores `txid` as an unvalidated string,\n * so anything else is refused here rather than encoded.\n *\n * @throws if the canonical form is not 64 hex characters.\n */\nexport function canonicalBtcTxid(txid: unknown): string {\n const canonical = String(txid).toLowerCase().replace(/^0x/, \"\");\n if (!/^[0-9a-f]{64}$/.test(canonical)) {\n throw new Error(\n `Invalid Bitcoin txid \"${String(txid)}\": expected 64 hex characters (optionally 0x-prefixed)`,\n );\n }\n return canonical;\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;;;;AAkCO,SAAS,sBAAsB,QAAoC;AACxE,gBAAc,EAAE,GAAG,aAAa,GAAG,OAAO;AAC5C;AAKA,SAAS,eAAuB;AAC9B,UAAO,oBAAI,KAAK,GAAE,YAAY;AAChC;AAKA,SAAS,cAAc,OAAe,WAAmB,SAAiB,UAAwB;AAChG,QAAM,YAAY,YAAY,mBAAmB,IAAI,aAAa,CAAC,OAAO;AAC1E,QAAM,cAAc,WAAW,IAAI,KAAK,UAAU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MAAM,0BAA0B,YAAY,GAAG;AAC9E,YAAM,IAAI;AAAA,QACR,qFAAqF,OAAO,YAChF,yBAAyB,YAAY,gBAAgB;AAAA,MACnE;AAAA,IACF;AAAA,EACF;AAEA,QAAM,oBAAoB,oBAAoB;AAC9C,MAAI,CAAC,mBAAmB;AACtB,UAAM,IAAI;AAAA,MACR,4CAA4C,OAAO;AAAA,IAErD;AAAA,EACF;AAEA,SAAO;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;AASO,SAAS,iBAAiB,MAAuB;AACtD,QAAM,YAAY,OAAO,IAAI,EAAE,YAAY,EAAE,QAAQ,OAAO,EAAE;AAC9D,MAAI,CAAC,iBAAiB,KAAK,SAAS,GAAG;AACrC,UAAM,IAAI;AAAA,MACR,yBAAyB,OAAO,IAAI,CAAC;AAAA,IACvC;AAAA,EACF;AACA,SAAO;AACT;",
6
6
  "names": ["LogLevel", "ALPHABET", "esm_default", "esm_default", "ErrorCategory", "RetryStrategy", "sessionSignatureCache", "EVMChain", "base"]
7
7
  }