@gvnrdao/dh-lit-actions 0.0.308 → 0.0.310

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 (54) 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/btc-address-balance.action.js +1 -1
  9. package/dist/btc-address-balance.hash +1 -1
  10. package/dist/btc-address-balance.meta.json +5 -5
  11. package/dist/btc-transaction-signer.action.js +1 -1
  12. package/dist/btc-transaction-signer.hash +1 -1
  13. package/dist/btc-transaction-signer.meta.json +5 -5
  14. package/dist/btc-utxo-invalidator.action.js +1 -1
  15. package/dist/btc-utxo-invalidator.hash +1 -1
  16. package/dist/btc-utxo-invalidator.meta.json +5 -5
  17. package/dist/btc-withdrawal.action.js +1 -1
  18. package/dist/btc-withdrawal.hash +1 -1
  19. package/dist/btc-withdrawal.meta.json +5 -5
  20. package/dist/encrypt-parameter.meta.json +1 -1
  21. package/dist/extend-position-validator.action.js +1 -1
  22. package/dist/extend-position-validator.hash +1 -1
  23. package/dist/extend-position-validator.meta.json +5 -5
  24. package/dist/liquidation-validator.action.js +1 -1
  25. package/dist/liquidation-validator.hash +1 -1
  26. package/dist/liquidation-validator.meta.json +5 -5
  27. package/dist/loan-vault-btc-balance.action.js +1 -1
  28. package/dist/loan-vault-btc-balance.hash +1 -1
  29. package/dist/loan-vault-btc-balance.meta.json +5 -5
  30. package/dist/pkp-validator.meta.json +1 -1
  31. package/dist/price-oracle.meta.json +1 -1
  32. package/dist/process-payment-validator.action.js +1 -1
  33. package/dist/process-payment-validator.hash +1 -1
  34. package/dist/process-payment-validator.meta.json +5 -5
  35. package/dist/stale-spend-recovery-validator.action.js +1 -1
  36. package/dist/stale-spend-recovery-validator.hash +1 -1
  37. package/dist/stale-spend-recovery-validator.meta.json +5 -5
  38. package/dist/ucd-mint-validator.action.js +1 -1
  39. package/dist/ucd-mint-validator.hash +1 -1
  40. package/dist/ucd-mint-validator.meta.json +5 -5
  41. package/package.json +1 -1
  42. package/pkg-dist/pkg-src/index.js +150 -77
  43. package/pkg-dist/pkg-src/index.js.map +4 -4
  44. package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts +7 -0
  45. package/pkg-dist/src/constants/chunks/bitcoin-network-config.d.ts.map +1 -1
  46. package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts +5 -0
  47. package/pkg-dist/src/interfaces/chunks/vault-balance.i.d.ts.map +1 -1
  48. package/pkg-dist/src/modules/bitcoin-balance-consensus.module.d.ts +23 -2
  49. package/pkg-dist/src/modules/bitcoin-balance-consensus.module.d.ts.map +1 -1
  50. package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts +8 -1
  51. package/pkg-dist/src/modules/bitcoin-data-provider.module.d.ts.map +1 -1
  52. package/pkg-dist/src/modules/bitcoin-provider-auth.d.ts +70 -0
  53. package/pkg-dist/src/modules/bitcoin-provider-auth.d.ts.map +1 -0
  54. package/pkg-dist/src/modules/bitcoin-provider-registry.d.ts.map +1 -1
@@ -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", "../../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/bitcoin-network-config.ts", "../../src/modules/business-rules-math.module.ts", "../../src/modules/protocol-parameters.module.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-data-provider.module.ts", "../../src/modules/price-oracle.module.ts", "../../src/modules/vault-balance.module.ts", "../../pkg-src/executors/chunks/price-oracle-executor.ts", "../../pkg-src/executors/index.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// 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: \"QmRAueBjNG78qA79x4NL4ogfNg7e6j6DiEGenEN4S3BSGg\",\n authorizedCidHex: cidToHex(\n \"QmRAueBjNG78qA79x4NL4ogfNg7e6j6DiEGenEN4S3BSGg\",\n ),\n name: \"Pkp Validator\",\n description: \"Production Pkp Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781116572961,\n size: 4110,\n hash: \"c3b121afcdc0d7d7ed7ca3be5b185fc502ffad99bf83cdf166769bbfa5194687\",\n validatorWalletAddress: \"0x9ee56687f7a984d5df7ab79330271a619ef56ddd\",\n pkp: {\n publicKey:\n \"0x04ec0e3acc40884e3f366ca469d08899eb640ad5259fa196b0238075086208a9f8732a3175704f35f0bcc28e07406cfb24c254efd1e7355640577330f0d2dd755f\",\n ethAddress: \"0x9eE56687F7a984D5DF7aB79330271a619ef56DdD\",\n },\n },\n btcTransactionSigner: {\n cid: \"QmTrtAnUFpAi6tpw74UPCiULqe9Z4SBE4b4neekY8evK5Y\",\n authorizedCidHex: cidToHex(\n \"QmTrtAnUFpAi6tpw74UPCiULqe9Z4SBE4b4neekY8evK5Y\",\n ),\n name: \"Btc Transaction Signer\",\n description: \"Production Btc Transaction Signer\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1780976122896,\n size: 41048,\n hash: \"93725b2020e1914e93f1e21bdcc75d9cb28bc0b6bc4ea9b470f112e1f068998f\",\n },\n ucdMintValidator: {\n cid: \"QmTWKgfSHfYWTosPJBzu2s4sM2U6qhvmA9pXbkUzDxdQTJ\",\n authorizedCidHex: cidToHex(\n \"QmTWKgfSHfYWTosPJBzu2s4sM2U6qhvmA9pXbkUzDxdQTJ\",\n ),\n name: \"Ucd Mint Validator\",\n description: \"Production Ucd Mint Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781116591564,\n size: 68521,\n hash: \"5a955863b32c003314ab29c37b157e06d00a2f93c2d9085a02ca73b71838a72f\",\n validatorWalletAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n pkp: {\n publicKey:\n \"0x041ab17cd91fc5c0b761eea6092d032807561b621b82c488826776e04a9158d61ba64d809a4729f0501289d980732cb06d8dfd06999dd9c8efd2f495dad78b31bb\",\n ethAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n },\n },\n processPaymentValidator: {\n cid: \"QmVJ9UaUz8vfvHCEwVY584e9RTEcqy3f3T89UNtzzFSdcz\",\n authorizedCidHex: cidToHex(\n \"QmVJ9UaUz8vfvHCEwVY584e9RTEcqy3f3T89UNtzzFSdcz\",\n ),\n name: \"Process Payment Validator\",\n description: \"Production Process Payment Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1780976120346,\n size: 64473,\n hash: \"8cf2ea8e2bf39ab02c6ac1706d8bec2aa16aa1f04f4789b11fa8215e04ac2d7e\",\n validatorWalletAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n pkp: {\n publicKey:\n \"0x04cfccb9b6c7addc79469c0e9fafebef4c70801302c62cdb26b610723a9b8527d23f98a40158c7340d83fd0e62d02b5ec74c12f7a86d98e8c6973b4811110f19ad\",\n ethAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n },\n },\n extendPositionValidator: {\n cid: \"QmW2zjWbsVzm8q4oMEHZ1SCeijygZFMvvi9zHqUQWm3jut\",\n authorizedCidHex: cidToHex(\n \"QmW2zjWbsVzm8q4oMEHZ1SCeijygZFMvvi9zHqUQWm3jut\",\n ),\n name: \"Extend Position Validator\",\n description: \"Production Extend Position Validator\",\n version: \"1.0.1\",\n deployed: true,\n deployedAt: 1781116610064,\n size: 63508,\n hash: \"187c71046858bde0753fe479634bd2901e3d7f3689b5f39a82b3c5fa3a47b53d\",\n validatorWalletAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n pkp: {\n publicKey:\n \"0x04e52338f6a0c3362800f1a94c4c8f08be5030dde0fa217388c53d1c1a4790f4443c9f2886b2d2d8f4b75a9a156e9b028011b1a1cf7648da0e556aa980ec692836\",\n ethAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n },\n },\n btcWithdrawal: {\n cid: \"QmcxHLCcXpx5Jstd1hQmwjU2KPDzP2KYEdMgbZVn84nY6n\",\n authorizedCidHex: cidToHex(\n \"QmcxHLCcXpx5Jstd1hQmwjU2KPDzP2KYEdMgbZVn84nY6n\",\n ),\n name: \"Btc Withdrawal\",\n description: \"Production Btc Withdrawal\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781116627244,\n size: 76218,\n hash: \"1e686e517ab1b8163904a27d3e1962cecb2f49b3cc7ecdc8f2ff5e5847fe3762\",\n validatorWalletAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n pkp: {\n publicKey:\n \"0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d\",\n ethAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n },\n },\n liquidationValidator: {\n cid: \"QmZv8cRhvQqEGscWufU4rYPrKNt3ruAhQWK2ei3ohJBiZA\",\n authorizedCidHex: cidToHex(\n \"QmZv8cRhvQqEGscWufU4rYPrKNt3ruAhQWK2ei3ohJBiZA\",\n ),\n name: \"Liquidation Validator\",\n description: \"Production Liquidation Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781116646357,\n size: 54901,\n hash: \"017ec04899089b98991a5aab6eeae5e3214c2cc9de7ef9b3fc0cd5ad85c3556c\",\n validatorWalletAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n pkp: {\n publicKey:\n \"0x041a241de58976c13e3d7ca5a18e494f7330151e3818706135d50176e78ffb673e58b11f0b67a87c73fade6c6b27d6e7a7377ea9f4c10bf31880f1d725f18cc6f8\",\n ethAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\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: \"0x831ddf3048547b983efe3ccbbb35a45a53191651\",\n pkp: {\n publicKey:\n \"0x043beaa1da47875601a8d6f430b1438ee2d4732eefd06e5c63a474bbdaf9e7df1797b1b951e041b627c2bf839788164825324c9cbd1e2d6f740fdd4bff69b1900b\",\n ethAddress: \"0x831DdF3048547B983EFE3ccBBB35a45a53191651\",\n },\n },\n loanVaultBtcBalance: {\n cid: \"Qmd7ZAWQzxjbFXjk39HuyRCN18FDG1LDifXceaikNFYRbm\",\n authorizedCidHex: cidToHex(\n \"Qmd7ZAWQzxjbFXjk39HuyRCN18FDG1LDifXceaikNFYRbm\",\n ),\n name: \"Loan Vault Btc Balance\",\n description: \"Production Loan Vault Btc Balance\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1780976125009,\n size: 44634,\n hash: \"f7ba0f8778a15f349122237c44391800bb082d2090a87cc1631f0a764439d029\",\n validatorWalletAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n pkp: {\n publicKey:\n \"0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d\",\n ethAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\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: \"QmVmF9CHFDhhV51bNX87tVyd95oQS56u78ThFYKzMwEbFS\",\n authorizedCidHex: cidToHex(\n \"QmVmF9CHFDhhV51bNX87tVyd95oQS56u78ThFYKzMwEbFS\",\n ),\n name: \"Btc Address Balance\",\n description: \"Address-only signed total BTC balance via registry consensus (no positionId, no price)\",\n version: \"0.1.0\",\n deployed: true,\n deployedAt: 1781116681558,\n size: 21957,\n hash: \"b17977304be6b117bcb29feafc3bb654113d72d5147ceeba92e91b4d7f5c0327\",\n validatorWalletAddress: \"0xf0bf5e3f864b87283a05d1e4a85ee0fa40493fb5\",\n pkp: {\n publicKey:\n \"0x0498cbb31facfa26e3ec83ccdabfe4fe341ca0282e0c3cb81da7113723b9726e1e49efa92165cc3faa66ced4454cea56dbab12267852d6525a55d7c4f128b912cd\",\n ethAddress: \"0xF0bF5e3f864B87283a05D1E4A85eE0FA40493fB5\",\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\n staleSpendRecoveryValidator: {\n cid: \"QmRZuRrxzsbp3WejuMfJJgws1iteRk87p1nGna82Cgun2k\",\n authorizedCidHex: cidToHex(\n \"QmRZuRrxzsbp3WejuMfJJgws1iteRk87p1nGna82Cgun2k\",\n ),\n name: \"Stale Spend Recovery Validator\",\n description: \"Production Stale Spend Recovery Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781116700324,\n size: 31148,\n hash: \"c93591c7c7f51b519243499d78bd5ac0df1e368caa76c08d6a5d7aea9e3a49cc\",\n validatorWalletAddress: \"0xa804bbb01d26f250fb3c53007fd32337b985602b\",\n pkp: {\n publicKey:\n \"0x046da0ad6da7dd4a0063cbeac6f2bdb6a9889c2178b23470833356a8ee5630f7f0eee0db348d9d9aaaadd23eccf0063c8f68ee5e446abe30b882bf1de4c932bc21\",\n ethAddress: \"0xa804bBb01D26F250FB3c53007fD32337B985602b\",\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 { 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 minConfirmations?: number; // Default: 6\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 // 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: params.chainId || 1, // Default to mainnet if not provided\n rpcUrl: params.rpcUrl,\n bitcoinProvider,\n minConfirmations: params.minConfirmations || 6,\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: params.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 * Starting liquidation threshold when loan expires (day 0 of grace period).\n * Value: 110% (11000 basis points)\n *\n * The threshold escalates from this value to MAX over the grace period.\n *\n * Governance-adjustable: YES\n */\nexport const EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11000;\n\n/**\n * Grace Period Duration\n *\n * Number of days after loan expiry before maximum liquidation threshold is reached.\n * Value: 30 days\n *\n * During this period, liquidation threshold escalates quadratically from MIN to MAX.\n *\n * Governance-adjustable: YES\n */\nexport const GRACE_PERIOD_DAYS = 30;\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 * Default Minimum Confirmations for UTXO Validity\n *\n * Number of block confirmations required before considering a UTXO as \"confirmed\".\n * Value: 6 confirmations (~60 minutes on Bitcoin mainnet)\n *\n * Bitcoin security standard:\n * - 1 confirmation: ~10 minutes, low security\n * - 3 confirmations: ~30 minutes, medium security\n * - 6 confirmations: ~60 minutes, high security (industry standard)\n *\n * This can be overridden for specific use cases (e.g., higher value requires more confirmations).\n *\n * Governance-adjustable: YES\n */\nexport const BITCOIN_DEFAULT_MIN_CONFIRMATIONS = 6;\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 * Acceptable range for Bitcoin network fees on a withdrawal transaction.\n * Fees outside this range indicate fee estimation errors or manipulation.\n *\n * Governance-adjustable: YES (may need adjustment for high-fee environments)\n */\nexport const MIN_BTC_FEE_SATS = 100; // Minimum viable Bitcoin fee\nexport const MAX_BTC_FEE_SATS = 100_000; // 0.001 BTC maximum (safety limit)\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 * 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\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 /** Minimum confirmations required for this provider/network */\n minConfirmations: number;\n\n /** Human-readable provider name */\n name: string;\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 (dh-btc-faucet Heroku app) 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 */\nexport const APPROVED_EVM_RPC_DOMAINS = [\"infura.io\", \"drpc.org\"];\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://diamond-hands-btc-faucet-6b39a1072059.herokuapp.com/api/esplora\",\n network: BitcoinNetwork.REGTEST,\n minConfirmations: 1,\n name: \"Diamond Hands\",\n },\n {\n url: \"https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/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 EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS,\n GRACE_PERIOD_DAYS,\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 * Calculate current liquidation threshold with grace period escalation\n *\n * Active loan: uses on-chain value from LoanOperationsManager.liquidationThreshold()\n * Expired:\n * Day 0: 110% (11000 bps)\n * Day 30: maxExpiredThresholdBps (read from LiquidationManager on-chain)\n * Quadratic escalation between\n *\n * Uses integer-only math for deterministic results across all platforms.\n *\n * @param isExpired - Whether loan is expired\n * @param daysIntoGracePeriod - Days past expiry (0 if not expired)\n * @param activeLoanThresholdBps - On-chain active loan threshold from LoanOperationsManager\n * @param maxExpiredThresholdBps - On-chain max escalated threshold from LiquidationManager\n * @returns Liquidation threshold in basis points\n */\nexport function calculateLiquidationThreshold(\n isExpired: boolean,\n daysIntoGracePeriod: number,\n activeLoanThresholdBps: number,\n maxExpiredThresholdBps?: number\n): number {\n // Active loan: Use on-chain value from LoanOperationsManager\n if (!isExpired) {\n return activeLoanThresholdBps;\n }\n\n // Expired: escalate from MIN to MAX over grace period\n // MAX is read from LiquidationManager.maxEscalatedThreshold() on-chain\n const maxThreshold = maxExpiredThresholdBps ?? EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS;\n\n // Cap at grace period days\n const day = Math.min(daysIntoGracePeriod, GRACE_PERIOD_DAYS);\n\n // Quadratic curve using ONLY integer math for determinism:\n // threshold = MIN + ((day^2 / GRACE_PERIOD_DAYS^2) * (MAX - MIN))\n //\n // This avoids floating point entirely while maintaining quadratic curve\n const daySquared = day * day;\n const escalation =\n (daySquared *\n (maxThreshold - EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS)) /\n (GRACE_PERIOD_DAYS * GRACE_PERIOD_DAYS);\n\n const threshold = EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS + escalation;\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 * 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\";\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}\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\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 }\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 // @ts-ignore - Lit.Actions available in LIT runtime\n rpcUrl = await Lit.Actions.getRpcUrl({ chain: this.chain });\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 { url: rpcUrl, timeout: 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 // @ts-ignore - Lit.Actions available in LIT runtime\n rpcUrl = await Lit.Actions.getRpcUrl({ chain: this.chain });\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 { url: rpcUrl, timeout: 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 // @ts-ignore - Lit.Actions available in LIT runtime\n const rpcUrl =\n this.rpcUrl || (await Lit.Actions.getRpcUrl({ chain: this.chain }));\n\n // @ts-ignore - ethers available in LIT runtime\n const provider = new ethers.providers.StaticJsonRpcProvider(\n { url: rpcUrl, timeout: 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 * Get max escalated threshold from LiquidationManager\n *\n * This is the governance-controlled ceiling for expired loan liquidation thresholds.\n * The quadratic escalation formula uses this as MAX instead of a hardcoded constant.\n *\n * @returns Max escalated threshold in basis points\n */\n async getMaxEscalatedThreshold(): Promise<number> {\n try {\n let rpcUrl: string;\n if (this.rpcUrl) {\n rpcUrl = this.rpcUrl;\n } else {\n // @ts-ignore - Lit.Actions available in LIT runtime\n rpcUrl = await Lit.Actions.getRpcUrl({ chain: this.chain });\n }\n // @ts-ignore - ethers available in LIT runtime\n const provider = new ethers.providers.StaticJsonRpcProvider(\n { url: rpcUrl, timeout: LIT_ACTION_ETH_RPC_TIMEOUT_MS },\n {\n name: \"any\",\n chainId: this.chainId,\n },\n );\n const abi = [\n {\n inputs: [],\n name: \"maxEscalatedThreshold\",\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.maxEscalatedThreshold();\n return Number(result.toString());\n } catch (error: any) {\n console.error(\n \"[ProtocolParameters] Error fetching max escalated threshold:\",\n error.message\n );\n throw new Error(\n `Failed to fetch max escalated threshold: ${error.message}`\n );\n }\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 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 { VaultBalanceResult } from \"../interfaces/chunks/vault-balance.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 {\n EVMChain,\n validateChain,\n getBitcoinNetworkForChain,\n BitcoinNetwork,\n LIT_ACTION_ETH_RPC_TIMEOUT_MS,\n} from \"../constants\";\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 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 // For timeout isolation diagnostics we can temporarily inject deterministic BTC data.\n const useStubbedBtcData =\n this.config.debugOverrides?.useStubbedBtcData === true;\n\n const [balanceResult, btcPriceUsd] = useStubbedBtcData\n ? this.buildStubbedBtcSnapshotInputs(positionState)\n : 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 || 1, // Default to mainnet if not provided\n rpcUrl: this.config.rpcUrl,\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 [liquidationThresholdBps, maxEscalatedThresholdBps, termFees] = await Promise.all([\n protocolParams.getLiquidationThreshold(),\n protocolParams.getMaxEscalatedThreshold(),\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 use on-chain values for both active and expired loans\n const currentLiquidationThreshold = calculateLiquidationThreshold(\n termStatus.isExpired,\n termStatus.daysIntoGracePeriod,\n liquidationThresholdBps,\n maxEscalatedThresholdBps\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 /**\n * Fast vault snapshot using balance method only (no UTXO validation)\n * This is optimized for speed and should be used when UTXO details are not needed.\n *\n * WARNING: This method skips UTXO validation. Use ONLY for non-critical operations.\n * For authorization/security operations, ALWAYS use getVaultSnapshot().\n *\n * @param positionId - Position to snapshot\n * @returns Complete VaultSnapshot with all metrics (using fast balance method)\n */\n async getVaultSnapshotFast(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 // For timeout isolation diagnostics we can temporarily inject deterministic BTC data.\n const useStubbedBtcData =\n this.config.debugOverrides?.useStubbedBtcData === true;\n\n const [balanceResult, btcPriceUsd] = useStubbedBtcData\n ? this.buildStubbedBtcSnapshotInputs(positionState)\n : await Promise.all([\n this.config.vaultBalance.calculateTrustedBalance(\n positionId,\n positionState.vaultAddress,\n true // Always skip UTXO validation for fast path\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 || 1, // Default to mainnet if not provided\n rpcUrl: this.config.rpcUrl,\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 [liquidationThresholdBps, maxEscalatedThresholdBps, termFees] = await Promise.all([\n protocolParams.getLiquidationThreshold(),\n protocolParams.getMaxEscalatedThreshold(),\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 use on-chain values for both active and expired loans\n const currentLiquidationThreshold = calculateLiquidationThreshold(\n termStatus.isExpired,\n termStatus.daysIntoGracePeriod,\n liquidationThresholdBps,\n maxEscalatedThresholdBps\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 private buildStubbedBtcSnapshotInputs(positionState: {\n positionId: string;\n vaultAddress: string;\n }): [VaultBalanceResult, bigint] {\n const stubbedAvailableBtcSats = BigInt(\n this.config.debugOverrides?.stubbedAvailableBtcSats ?? \"10000000\"\n ); // 0.1 BTC\n const stubbedBtcPriceUsd = BigInt(\n this.config.debugOverrides?.stubbedBtcPriceUsd ?? \"5000000000000\"\n ); // $50,000 with 8 decimals\n const stubbedAuthorizedSpendsHash =\n this.config.debugOverrides?.stubbedAuthorizedSpendsHash ??\n // keccak256(abi.encode(positionId, []))\n ethers.utils.keccak256(\n ethers.utils.defaultAbiCoder.encode(\n [\"bytes32\", \"bytes32[]\"],\n [positionState.positionId, []]\n )\n );\n\n const balanceResult: VaultBalanceResult = {\n totalUTXOs: [],\n totalBalance: stubbedAvailableBtcSats,\n authorizedUTXOs: [],\n authorizedBalance: 0n,\n authorizedSpendsHash: stubbedAuthorizedSpendsHash,\n availableUTXOs: [],\n availableBalance: stubbedAvailableBtcSats,\n vaultAddress: positionState.vaultAddress,\n positionId: positionState.positionId,\n timestamp: Date.now(),\n };\n\n return [balanceResult, stubbedBtcPriceUsd];\n }\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 // @ts-ignore - Lit.Actions available in LIT runtime\n rpcUrl = await Lit.Actions.getRpcUrl({ chain: this.config.chain });\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 { url: rpcUrl, timeout: 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 return {\n positionId: position.positionId,\n pkpId: position.pkpId,\n borrower: position.borrower,\n vaultAddress: this.parseVaultAddress(\n position.vaultAddress,\n validateChain(this.config.chain)\n ),\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 /**\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\":\"mqM3ZR2N6DzZkafSdFqxEAkWovAU3uYTAN\"}\n *\n * @param rawVaultAddress Raw vault address from contract\n * @param chain EVM chain (sepolia, ethereum)\n * @returns Parsed Bitcoin address for the appropriate network\n */\n private parseVaultAddress(rawVaultAddress: string, chain: string): string {\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 // 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 || parsed.mainnet;\n }\n\n // For other chains, use standard mapping\n const bitcoinNetwork = getBitcoinNetworkForChain(chain as EVMChain);\n if (bitcoinNetwork === BitcoinNetwork.TESTNET) {\n return parsed.testnet || parsed.regtest || parsed.mainnet;\n } else {\n // Mainnet\n return parsed.mainnet;\n }\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 /**\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 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 UTXO_QUERY_MAX_RETRIES,\n UTXO_QUERY_RETRY_DELAY_MS,\n} from \"../constants\";\nimport {\n getUnknownErrorMessage,\n isAbortError,\n} from \"./lit-global-bootstrap\";\nimport { litDebugLog } from \"./lit-action-debug\";\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 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 * 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: {\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 txid: utxo.txid,\n vout: utxo.vout,\n satoshis: BigInt(Math.round(utxo.amount * 100000000)), // BTC to satoshis as bigint\n confirmations: utxo.confirmations,\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\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}/utxos\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 const endpoint = `${providerUrl}/address/${address}/utxos`;\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: {\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 utxos) wall ${Date.now() - tParallel}ms endpoint tail .../${address.slice(0, 12)}.../utxos (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: {\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\n const confirmedBalance = fundedTxoSum - spentTxoSum;\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 });\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 try {\n const tipResp = await fetch(\n `${this.config.providerUrl}/blocks/tip/height`,\n { signal: controller.signal },\n );\n if (!tipResp.ok) {\n // Provider missing tip endpoint \u2014 return 1 as a conservative\n // \"confirmed but depth unknown\" signal so downstream callers can\n // surface a clear error rather than silently accept.\n return { txid: data.txid ?? txid, confirmations: 1 };\n }\n const tipBody = (await tipResp.text()).trim();\n const tipHeight = Number.parseInt(tipBody, 10);\n if (!Number.isFinite(tipHeight) || tipHeight <= 0) {\n return { txid: data.txid ?? txid, confirmations: 1 };\n }\n const depth = tipHeight - data.status.block_height + 1;\n return {\n txid: data.txid ?? txid,\n confirmations: depth > 0 ? depth : 0,\n };\n } catch {\n // Tip-height fetch failed \u2014 fall back to \"confirmed=1\".\n return { txid: data.txid ?? txid, confirmations: 1 };\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 // 404 means transaction not found\n if (getUnknownErrorMessage(error).includes(\"404\")) {\n return null;\n }\n throw error;\n }\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 if (!this.config.providerUrl) {\n return null;\n }\n\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 });\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 index,\n scriptpubkey: output.scriptpubkey,\n scriptpubkey_address: output.scriptpubkey_address,\n value: output.value ?? 0,\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 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\";\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 */\nexport class VaultBalanceModule implements IVaultBalance {\n private config: VaultBalanceConfig;\n private bitcoinProvider: IBitcoinDataProvider;\n\n constructor(config: VaultBalanceConfig) {\n this.config = config;\n this.bitcoinProvider = config.bitcoinProvider;\n }\n\n /**\n * Calculate balance (fast path - no UTXO validation)\n *\n * Fast balance-only calculation that skips UTXO validation.\n * Uses simple arithmetic: Total Balance - Authorized Balance = Available Balance\n *\n * Use this when you only need the balance amount and don't need:\n * - Individual UTXO details\n * - Validation that authorized UTXOs were actually spent\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 * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @param skipUTXOValidation - If true, use fast balance-only path (skips UTXO validation)\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 skipUTXOValidation?: boolean\n ): Promise<VaultBalanceResult> {\n // Fast path: skip UTXO validation if requested\n if (skipUTXOValidation) {\n return await this.calculateBalance(positionId, vaultAddress);\n }\n\n // Full validation path (default)\n const minConfirmations = this.config.minConfirmations || 6;\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. CRITICAL: Validate each authorized spend state\n // For each authorized spend, check if UTXO still exists as unspent\n for (const spend of authorizedSpends) {\n const utxoStillExists = utxoSet.utxos.some(\n (utxo) => utxo.txid === spend.txid && utxo.vout === spend.vout\n );\n\n if (utxoStillExists) {\n // ERROR B: UTXO authorized in contract but still unspent on Bitcoin network\n // This means SDK authorized but never signed/broadcasted the spending transaction\n throw new Error(\n `Authorized UTXO ${spend.txid}:${spend.vout} not yet spent. ` +\n `Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. ` +\n `Complete the transaction by signing and broadcasting it.`\n );\n }\n\n // UTXO no longer exists as unspent (it's been spent)\n // This is expected - now we verify the spending transaction has enough confirmations\n // Note: spend.txid refers to the INPUT UTXO, not the spending transaction\n // We cannot validate spending transaction confirmations without storing its txid\n // For now, we trust that if UTXO doesn't exist, it's been properly spent\n // TODO: Consider adding spendingTxid to AuthorizedSpend for full validation\n }\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 // 5. Filter out UTXOs that are authorized (not available)\n // Note: After validation above, authorized UTXOs should NOT appear in utxoSet\n // But we filter anyway for safety\n const availableUTXOs = utxoSet.utxos.filter(\n (utxo) => !this.isUTXOAuthorized(utxo, authorizedSpends)\n );\n\n // 6. Calculate available balance\n const availableBalance = availableUTXOs.reduce(\n (sum, utxo) => sum + utxo.satoshis,\n 0n\n );\n\n // 7. 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 // @ts-ignore - Lit.Actions is available in LIT runtime\n rpcUrl = await Lit.Actions.getRpcUrl({ chain: this.config.chain });\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 { url: rpcUrl, timeout: 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 * 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"],
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,KAA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B,OAAO;AAAA,IAC3B,uBAAuB,OAAO;AAAA,IAC9B,2BAA2B,OAAO;AAAA,IAClC,OAAO,OAAO;AAAA,IACd,SAAS,OAAO;AAAA,IAChB,QAAQ,OAAO;AAAA,IACf;AAAA,IACA;AAAA,EACF,CAAC;AAGD,QAAM,WAAW,MAAM,cAAc,iBAAiB,OAAO,UAAU;AAGvE,SAAQ,OAAe;AACvB,SAAQ,OAAe;AAEvB,SAAO;AACT;;;AiBrFA,eAAsB,mBACpB,QACiB;AAGjB,EAAC,OAAe,MAAM;AAAA,IACpB,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,MAMP,qBAAqB,OAAO;AAAA,QAC1B;AAAA,QACA;AAAA,MACF,MAGyB;AAEvB,eAAO,CAAC,KAAK;AAAA,MACf;AAAA,IACF;AAAA,EACF;AAGA,QAAM,SAAS,QAAQ,gBACnB,IAAI,kBAAkB,CAAC,GAAG,OAAO,eAAe,QAAQ,IAAI,IAC5D,IAAI,kBAAkB,QAAQ,gBAAgB,QAAW,QAAQ,IAAI;AAGzE,SAAO,MAAM,OAAO,YAAY;AAClC;;;ACrDO,IAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAa5B,eAAe;AAAA,IACb,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,SAAS;AAAA,EACX;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,aAAa;AAAA,IACX,MAAM;AAAA,IACN,aAAa;AAAA,IACb,UAAU;AAAA,IACV,SAAS;AAAA,EACX;AACF;",
6
- "names": ["LogLevel", "ALPHABET", "esm_default", "esm_default", "ErrorCategory", "RetryStrategy", "sessionSignatureCache", "EVMChain"]
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/bitcoin-network-config.ts", "../../src/modules/business-rules-math.module.ts", "../../src/modules/protocol-parameters.module.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.module.ts", "../../pkg-src/executors/chunks/price-oracle-executor.ts", "../../pkg-src/executors/index.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// 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: \"QmRAueBjNG78qA79x4NL4ogfNg7e6j6DiEGenEN4S3BSGg\",\n authorizedCidHex: cidToHex(\n \"QmRAueBjNG78qA79x4NL4ogfNg7e6j6DiEGenEN4S3BSGg\",\n ),\n name: \"Pkp Validator\",\n description: \"Production Pkp Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781116572961,\n size: 4110,\n hash: \"c3b121afcdc0d7d7ed7ca3be5b185fc502ffad99bf83cdf166769bbfa5194687\",\n validatorWalletAddress: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n pkp: {\n publicKey:\n \"0x04ec0e3acc40884e3f366ca469d08899eb640ad5259fa196b0238075086208a9f8732a3175704f35f0bcc28e07406cfb24c254efd1e7355640577330f0d2dd755f\",\n ethAddress: \"0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607\",\n },\n },\n btcTransactionSigner: {\n cid: \"QmZs56sVTCJv7mgvyRYfpYHFvFLcSeXa4H44qUYT7z14QP\",\n authorizedCidHex: cidToHex(\n \"QmZs56sVTCJv7mgvyRYfpYHFvFLcSeXa4H44qUYT7z14QP\",\n ),\n name: \"Btc Transaction Signer\",\n description: \"Production Btc Transaction Signer\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781542204806,\n size: 42376,\n hash: \"f4aed3d88f6fbff6623ed2047436cecd4f561a74883171ea6f4ebe0a1129973c\",\n },\n ucdMintValidator: {\n cid: \"QmPir8F8jmJ4ssQpEC3xFxkEnZxMHcgS6VxBQE1jkTLj5K\",\n authorizedCidHex: cidToHex(\n \"QmPir8F8jmJ4ssQpEC3xFxkEnZxMHcgS6VxBQE1jkTLj5K\",\n ),\n name: \"Ucd Mint Validator\",\n description: \"Production Ucd Mint Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781542207366,\n size: 72074,\n hash: \"567a51d3beaedbda4f0af2636835ca8a2af89c2264e91f8dc31f522c1a424b7b\",\n validatorWalletAddress: \"0x82DB9F515957aA380B596C6eA2Bd30CEF181f236\",\n pkp: {\n publicKey:\n \"0x041ab17cd91fc5c0b761eea6092d032807561b621b82c488826776e04a9158d61ba64d809a4729f0501289d980732cb06d8dfd06999dd9c8efd2f495dad78b31bb\",\n ethAddress: \"0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607\",\n },\n },\n processPaymentValidator: {\n cid: \"QmVq19NXJEpMMvaWQdsU5czLoqh28WGWoGgKMSYFaCmfa9\",\n authorizedCidHex: cidToHex(\n \"QmVq19NXJEpMMvaWQdsU5czLoqh28WGWoGgKMSYFaCmfa9\",\n ),\n name: \"Process Payment Validator\",\n description: \"Production Process Payment Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781542209526,\n size: 68239,\n hash: \"ada27fea57aa3f3b861c49e75ed1f80b72500fdccc1d6e88ee1a3c1396b81867\",\n validatorWalletAddress: \"0x82DB9F515957aA380B596C6eA2Bd30CEF181f236\",\n pkp: {\n publicKey:\n \"0x04cfccb9b6c7addc79469c0e9fafebef4c70801302c62cdb26b610723a9b8527d23f98a40158c7340d83fd0e62d02b5ec74c12f7a86d98e8c6973b4811110f19ad\",\n ethAddress: \"0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607\",\n },\n },\n extendPositionValidator: {\n cid: \"QmP2u3bgKLtfqsFMp6Li72zMY8ZZH3ttAqp9W2wwonUmcb\",\n authorizedCidHex: cidToHex(\n \"QmP2u3bgKLtfqsFMp6Li72zMY8ZZH3ttAqp9W2wwonUmcb\",\n ),\n name: \"Extend Position Validator\",\n description: \"Production Extend Position Validator\",\n version: \"1.0.1\",\n deployed: true,\n deployedAt: 1781542211640,\n size: 66543,\n hash: \"0db666fa2888e9acea13d8e4d79edd4ca252f5a4bb06d97e53aa14a9a34b7143\",\n validatorWalletAddress: \"0x82DB9F515957aA380B596C6eA2Bd30CEF181f236\",\n pkp: {\n publicKey:\n \"0x04e52338f6a0c3362800f1a94c4c8f08be5030dde0fa217388c53d1c1a4790f4443c9f2886b2d2d8f4b75a9a156e9b028011b1a1cf7648da0e556aa980ec692836\",\n ethAddress: \"0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607\",\n },\n },\n btcWithdrawal: {\n cid: \"QmXtmLdGuEqMKKAtV7d8sHpUV32Kt74na4dRQdpWLasbHJ\",\n authorizedCidHex: cidToHex(\n \"QmXtmLdGuEqMKKAtV7d8sHpUV32Kt74na4dRQdpWLasbHJ\",\n ),\n name: \"Btc Withdrawal\",\n description: \"Production Btc Withdrawal\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781542212709,\n size: 79782,\n hash: \"e824eb473df8eba3a025ac3adc46730dbf89f90884d7c05a78cc07b90d6bc4df\",\n validatorWalletAddress: \"0x82DB9F515957aA380B596C6eA2Bd30CEF181f236\",\n pkp: {\n publicKey:\n \"0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d\",\n ethAddress: \"0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607\",\n },\n },\n liquidationValidator: {\n cid: \"QmVicBXuZVY8t4DXLPjvXjzLqnBtnogAh5HT7BaL9VeDwF\",\n authorizedCidHex: cidToHex(\n \"QmVicBXuZVY8t4DXLPjvXjzLqnBtnogAh5HT7BaL9VeDwF\",\n ),\n name: \"Liquidation Validator\",\n description: \"Production Liquidation Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781542213421,\n size: 58444,\n hash: \"0f42e9f8984433fef95875d35eb3c8d985e7ce15ad309e6aa1093d6fd1ba0bb5\",\n validatorWalletAddress: \"0x82DB9F515957aA380B596C6eA2Bd30CEF181f236\",\n pkp: {\n publicKey:\n \"0x041a241de58976c13e3d7ca5a18e494f7330151e3818706135d50176e78ffb673e58b11f0b67a87c73fade6c6b27d6e7a7377ea9f4c10bf31880f1d725f18cc6f8\",\n ethAddress: \"0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607\",\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: \"0x82db9f515957aa380b596c6ea2bd30cef181f236\",\n pkp: {\n publicKey:\n \"0x043beaa1da47875601a8d6f430b1438ee2d4732eefd06e5c63a474bbdaf9e7df1797b1b951e041b627c2bf839788164825324c9cbd1e2d6f740fdd4bff69b1900b\",\n ethAddress: \"0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607\",\n },\n },\n loanVaultBtcBalance: {\n cid: \"QmUmqL4LcjDSpw2TtuWMcw8xYk8hPxgagY2qHDU8Mx1PLG\",\n authorizedCidHex: cidToHex(\n \"QmUmqL4LcjDSpw2TtuWMcw8xYk8hPxgagY2qHDU8Mx1PLG\",\n ),\n name: \"Loan Vault Btc Balance\",\n description: \"Production Loan Vault Btc Balance\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781542215432,\n size: 48397,\n hash: \"da3750a70e532b87f3590a3e2d8c2d51e700589f6e111bb291384ab01304af35\",\n validatorWalletAddress: \"0x82DB9F515957aA380B596C6eA2Bd30CEF181f236\",\n pkp: {\n publicKey:\n \"0x043616787c5432415c24378c4ef48de2bcd6bb7b575b837e3cff09171802662da7105d79586c7659677a0ecbaddac4cce06cb2a11f69a16fa0c4d7002ac7d51a4d\",\n ethAddress: \"0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607\",\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: \"QmWRDAg7ZCBFFhGfdXR7aUtQsG5qqBb1yVdLCxh8dPD7G5\",\n authorizedCidHex: cidToHex(\n \"QmWRDAg7ZCBFFhGfdXR7aUtQsG5qqBb1yVdLCxh8dPD7G5\",\n ),\n name: \"Btc Address Balance\",\n description: \"Address-only signed total BTC balance via registry consensus (no positionId, no price)\",\n version: \"0.1.0\",\n deployed: true,\n deployedAt: 1781542217452,\n size: 25519,\n hash: \"000e2f8bdbccdc95b0db0fb3f12412e2e76eea16a8456d37914d324437ae291c\",\n validatorWalletAddress: \"0x82DB9F515957aA380B596C6eA2Bd30CEF181f236\",\n pkp: {\n publicKey:\n \"0x0498cbb31facfa26e3ec83ccdabfe4fe341ca0282e0c3cb81da7113723b9726e1e49efa92165cc3faa66ced4454cea56dbab12267852d6525a55d7c4f128b912cd\",\n ethAddress: \"0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607\",\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\n staleSpendRecoveryValidator: {\n cid: \"QmWqJZqoKUqMaGTXe9WUSwdDyeBwXJ9dnR3ioFnVK4RkN5\",\n authorizedCidHex: cidToHex(\n \"QmWqJZqoKUqMaGTXe9WUSwdDyeBwXJ9dnR3ioFnVK4RkN5\",\n ),\n name: \"Stale Spend Recovery Validator\",\n description: \"Production Stale Spend Recovery Validator\",\n version: \"1.0.0\",\n deployed: true,\n deployedAt: 1781542219438,\n size: 34413,\n hash: \"26b11730cf5d9eb4af0b1fe65192d26ccee50369c0472211a0ea11e26ef51cc5\",\n validatorWalletAddress: \"0x82DB9F515957aA380B596C6eA2Bd30CEF181f236\",\n pkp: {\n publicKey:\n \"0x046da0ad6da7dd4a0063cbeac6f2bdb6a9889c2178b23470833356a8ee5630f7f0eee0db348d9d9aaaadd23eccf0063c8f68ee5e446abe30b882bf1de4c932bc21\",\n ethAddress: \"0xc7e1588Db94Bbe92Ab209B833235144Fc5b97607\",\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 { 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 minConfirmations?: number; // Default: 6\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 // 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: params.chainId || 1, // Default to mainnet if not provided\n rpcUrl: params.rpcUrl,\n bitcoinProvider,\n minConfirmations: params.minConfirmations || 6,\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: params.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 * Starting liquidation threshold when loan expires (day 0 of grace period).\n * Value: 110% (11000 basis points)\n *\n * The threshold escalates from this value to MAX over the grace period.\n *\n * Governance-adjustable: YES\n */\nexport const EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS = 11000;\n\n/**\n * Grace Period Duration\n *\n * Number of days after loan expiry before maximum liquidation threshold is reached.\n * Value: 30 days\n *\n * During this period, liquidation threshold escalates quadratically from MIN to MAX.\n *\n * Governance-adjustable: YES\n */\nexport const GRACE_PERIOD_DAYS = 30;\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 * Default Minimum Confirmations for UTXO Validity\n *\n * Number of block confirmations required before considering a UTXO as \"confirmed\".\n * Value: 6 confirmations (~60 minutes on Bitcoin mainnet)\n *\n * Bitcoin security standard:\n * - 1 confirmation: ~10 minutes, low security\n * - 3 confirmations: ~30 minutes, medium security\n * - 6 confirmations: ~60 minutes, high security (industry standard)\n *\n * This can be overridden for specific use cases (e.g., higher value requires more confirmations).\n *\n * Governance-adjustable: YES\n */\nexport const BITCOIN_DEFAULT_MIN_CONFIRMATIONS = 6;\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 * Acceptable range for Bitcoin network fees on a withdrawal transaction.\n * Fees outside this range indicate fee estimation errors or manipulation.\n *\n * Governance-adjustable: YES (may need adjustment for high-fee environments)\n */\nexport const MIN_BTC_FEE_SATS = 100; // Minimum viable Bitcoin fee\nexport const MAX_BTC_FEE_SATS = 100_000; // 0.001 BTC maximum (safety limit)\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 * 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 /** Minimum confirmations required for this provider/network */\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 (dh-btc-faucet Heroku app) 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 */\nexport const APPROVED_EVM_RPC_DOMAINS = [\"infura.io\", \"drpc.org\"];\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://diamond-hands-btc-faucet-6b39a1072059.herokuapp.com/api/esplora\",\n network: BitcoinNetwork.REGTEST,\n minConfirmations: 1,\n name: \"Diamond Hands\",\n },\n {\n url: \"https://dh-btc-faucet-jw-bb7756976029.herokuapp.com/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 EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS,\n GRACE_PERIOD_DAYS,\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 * Calculate current liquidation threshold with grace period escalation\n *\n * Active loan: uses on-chain value from LoanOperationsManager.liquidationThreshold()\n * Expired:\n * Day 0: 110% (11000 bps)\n * Day 30: maxExpiredThresholdBps (read from LiquidationManager on-chain)\n * Quadratic escalation between\n *\n * Uses integer-only math for deterministic results across all platforms.\n *\n * @param isExpired - Whether loan is expired\n * @param daysIntoGracePeriod - Days past expiry (0 if not expired)\n * @param activeLoanThresholdBps - On-chain active loan threshold from LoanOperationsManager\n * @param maxExpiredThresholdBps - On-chain max escalated threshold from LiquidationManager\n * @returns Liquidation threshold in basis points\n */\nexport function calculateLiquidationThreshold(\n isExpired: boolean,\n daysIntoGracePeriod: number,\n activeLoanThresholdBps: number,\n maxExpiredThresholdBps?: number\n): number {\n // Active loan: Use on-chain value from LoanOperationsManager\n if (!isExpired) {\n return activeLoanThresholdBps;\n }\n\n // Expired: escalate from MIN to MAX over grace period\n // MAX is read from LiquidationManager.maxEscalatedThreshold() on-chain\n const maxThreshold = maxExpiredThresholdBps ?? EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS;\n\n // Cap at grace period days\n const day = Math.min(daysIntoGracePeriod, GRACE_PERIOD_DAYS);\n\n // Quadratic curve using ONLY integer math for determinism:\n // threshold = MIN + ((day^2 / GRACE_PERIOD_DAYS^2) * (MAX - MIN))\n //\n // This avoids floating point entirely while maintaining quadratic curve\n const daySquared = day * day;\n const escalation =\n (daySquared *\n (maxThreshold - EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS)) /\n (GRACE_PERIOD_DAYS * GRACE_PERIOD_DAYS);\n\n const threshold = EXPIRED_LOAN_MIN_LIQUIDATION_THRESHOLD_BPS + escalation;\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 * 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\";\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}\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\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 }\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 // @ts-ignore - Lit.Actions available in LIT runtime\n rpcUrl = await Lit.Actions.getRpcUrl({ chain: this.chain });\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 { url: rpcUrl, timeout: 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 // @ts-ignore - Lit.Actions available in LIT runtime\n rpcUrl = await Lit.Actions.getRpcUrl({ chain: this.chain });\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 { url: rpcUrl, timeout: 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 // @ts-ignore - Lit.Actions available in LIT runtime\n const rpcUrl =\n this.rpcUrl || (await Lit.Actions.getRpcUrl({ chain: this.chain }));\n\n // @ts-ignore - ethers available in LIT runtime\n const provider = new ethers.providers.StaticJsonRpcProvider(\n { url: rpcUrl, timeout: 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 * Get max escalated threshold from LiquidationManager\n *\n * This is the governance-controlled ceiling for expired loan liquidation thresholds.\n * The quadratic escalation formula uses this as MAX instead of a hardcoded constant.\n *\n * @returns Max escalated threshold in basis points\n */\n async getMaxEscalatedThreshold(): Promise<number> {\n try {\n let rpcUrl: string;\n if (this.rpcUrl) {\n rpcUrl = this.rpcUrl;\n } else {\n // @ts-ignore - Lit.Actions available in LIT runtime\n rpcUrl = await Lit.Actions.getRpcUrl({ chain: this.chain });\n }\n // @ts-ignore - ethers available in LIT runtime\n const provider = new ethers.providers.StaticJsonRpcProvider(\n { url: rpcUrl, timeout: LIT_ACTION_ETH_RPC_TIMEOUT_MS },\n {\n name: \"any\",\n chainId: this.chainId,\n },\n );\n const abi = [\n {\n inputs: [],\n name: \"maxEscalatedThreshold\",\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.maxEscalatedThreshold();\n return Number(result.toString());\n } catch (error: any) {\n console.error(\n \"[ProtocolParameters] Error fetching max escalated threshold:\",\n error.message\n );\n throw new Error(\n `Failed to fetch max escalated threshold: ${error.message}`\n );\n }\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 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 { VaultBalanceResult } from \"../interfaces/chunks/vault-balance.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 {\n EVMChain,\n validateChain,\n getBitcoinNetworkForChain,\n BitcoinNetwork,\n LIT_ACTION_ETH_RPC_TIMEOUT_MS,\n} from \"../constants\";\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 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 // For timeout isolation diagnostics we can temporarily inject deterministic BTC data.\n const useStubbedBtcData =\n this.config.debugOverrides?.useStubbedBtcData === true;\n\n const [balanceResult, btcPriceUsd] = useStubbedBtcData\n ? this.buildStubbedBtcSnapshotInputs(positionState)\n : 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 || 1, // Default to mainnet if not provided\n rpcUrl: this.config.rpcUrl,\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 [liquidationThresholdBps, maxEscalatedThresholdBps, termFees] = await Promise.all([\n protocolParams.getLiquidationThreshold(),\n protocolParams.getMaxEscalatedThreshold(),\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 use on-chain values for both active and expired loans\n const currentLiquidationThreshold = calculateLiquidationThreshold(\n termStatus.isExpired,\n termStatus.daysIntoGracePeriod,\n liquidationThresholdBps,\n maxEscalatedThresholdBps\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 /**\n * Fast vault snapshot using balance method only (no UTXO validation)\n * This is optimized for speed and should be used when UTXO details are not needed.\n *\n * WARNING: This method skips UTXO validation. Use ONLY for non-critical operations.\n * For authorization/security operations, ALWAYS use getVaultSnapshot().\n *\n * @param positionId - Position to snapshot\n * @returns Complete VaultSnapshot with all metrics (using fast balance method)\n */\n async getVaultSnapshotFast(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 // For timeout isolation diagnostics we can temporarily inject deterministic BTC data.\n const useStubbedBtcData =\n this.config.debugOverrides?.useStubbedBtcData === true;\n\n const [balanceResult, btcPriceUsd] = useStubbedBtcData\n ? this.buildStubbedBtcSnapshotInputs(positionState)\n : await Promise.all([\n this.config.vaultBalance.calculateTrustedBalance(\n positionId,\n positionState.vaultAddress,\n true // Always skip UTXO validation for fast path\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 || 1, // Default to mainnet if not provided\n rpcUrl: this.config.rpcUrl,\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 [liquidationThresholdBps, maxEscalatedThresholdBps, termFees] = await Promise.all([\n protocolParams.getLiquidationThreshold(),\n protocolParams.getMaxEscalatedThreshold(),\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 use on-chain values for both active and expired loans\n const currentLiquidationThreshold = calculateLiquidationThreshold(\n termStatus.isExpired,\n termStatus.daysIntoGracePeriod,\n liquidationThresholdBps,\n maxEscalatedThresholdBps\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 private buildStubbedBtcSnapshotInputs(positionState: {\n positionId: string;\n vaultAddress: string;\n }): [VaultBalanceResult, bigint] {\n const stubbedAvailableBtcSats = BigInt(\n this.config.debugOverrides?.stubbedAvailableBtcSats ?? \"10000000\"\n ); // 0.1 BTC\n const stubbedBtcPriceUsd = BigInt(\n this.config.debugOverrides?.stubbedBtcPriceUsd ?? \"5000000000000\"\n ); // $50,000 with 8 decimals\n const stubbedAuthorizedSpendsHash =\n this.config.debugOverrides?.stubbedAuthorizedSpendsHash ??\n // keccak256(abi.encode(positionId, []))\n ethers.utils.keccak256(\n ethers.utils.defaultAbiCoder.encode(\n [\"bytes32\", \"bytes32[]\"],\n [positionState.positionId, []]\n )\n );\n\n const balanceResult: VaultBalanceResult = {\n totalUTXOs: [],\n totalBalance: stubbedAvailableBtcSats,\n authorizedUTXOs: [],\n authorizedBalance: 0n,\n authorizedSpendsHash: stubbedAuthorizedSpendsHash,\n availableUTXOs: [],\n availableBalance: stubbedAvailableBtcSats,\n vaultAddress: positionState.vaultAddress,\n positionId: positionState.positionId,\n timestamp: Date.now(),\n };\n\n return [balanceResult, stubbedBtcPriceUsd];\n }\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 // @ts-ignore - Lit.Actions available in LIT runtime\n rpcUrl = await Lit.Actions.getRpcUrl({ chain: this.config.chain });\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 { url: rpcUrl, timeout: 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 return {\n positionId: position.positionId,\n pkpId: position.pkpId,\n borrower: position.borrower,\n vaultAddress: this.parseVaultAddress(\n position.vaultAddress,\n validateChain(this.config.chain)\n ),\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 /**\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\":\"mqM3ZR2N6DzZkafSdFqxEAkWovAU3uYTAN\"}\n *\n * @param rawVaultAddress Raw vault address from contract\n * @param chain EVM chain (sepolia, ethereum)\n * @returns Parsed Bitcoin address for the appropriate network\n */\n private parseVaultAddress(rawVaultAddress: string, chain: string): string {\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 // 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 || parsed.mainnet;\n }\n\n // For other chains, use standard mapping\n const bitcoinNetwork = getBitcoinNetworkForChain(chain as EVMChain);\n if (bitcoinNetwork === BitcoinNetwork.TESTNET) {\n return parsed.testnet || parsed.regtest || parsed.mainnet;\n } else {\n // Mainnet\n return parsed.mainnet;\n }\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 /**\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. Public esplora (no credentials) is exempt and may use http\n * (e.g. the local regtest faucet).\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/**\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 */\nexport function parseProviderPlaintext(plaintext: string): 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 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 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 UTXO_QUERY_MAX_RETRIES,\n UTXO_QUERY_RETRY_DELAY_MS,\n} from \"../constants\";\nimport {\n getUnknownErrorMessage,\n isAbortError,\n} from \"./lit-global-bootstrap\";\nimport { litDebugLog } from \"./lit-action-debug\";\nimport { authHeaders } from \"./bitcoin-provider-auth\";\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 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 txid: utxo.txid,\n vout: utxo.vout,\n satoshis: BigInt(Math.round(utxo.amount * 100000000)), // BTC to satoshis as bigint\n confirmations: utxo.confirmations,\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\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\n const confirmedBalance = fundedTxoSum - spentTxoSum;\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 try {\n const tipResp = await fetch(\n `${this.config.providerUrl}/blocks/tip/height`,\n { signal: controller.signal, headers: await this.withAuth() },\n );\n if (!tipResp.ok) {\n // Provider missing tip endpoint \u2014 return 1 as a conservative\n // \"confirmed but depth unknown\" signal so downstream callers can\n // surface a clear error rather than silently accept.\n return { txid: data.txid ?? txid, confirmations: 1 };\n }\n const tipBody = (await tipResp.text()).trim();\n const tipHeight = Number.parseInt(tipBody, 10);\n if (!Number.isFinite(tipHeight) || tipHeight <= 0) {\n return { txid: data.txid ?? txid, confirmations: 1 };\n }\n const depth = tipHeight - data.status.block_height + 1;\n return {\n txid: data.txid ?? txid,\n confirmations: depth > 0 ? depth : 0,\n };\n } catch {\n // Tip-height fetch failed \u2014 fall back to \"confirmed=1\".\n return { txid: data.txid ?? txid, confirmations: 1 };\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 // 404 means transaction not found\n if (getUnknownErrorMessage(error).includes(\"404\")) {\n return null;\n }\n throw error;\n }\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 if (!this.config.providerUrl) {\n return null;\n }\n\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 index,\n scriptpubkey: output.scriptpubkey,\n scriptpubkey_address: output.scriptpubkey_address,\n value: output.value ?? 0,\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 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\";\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 */\nexport class VaultBalanceModule implements IVaultBalance {\n private config: VaultBalanceConfig;\n private bitcoinProvider: IBitcoinDataProvider;\n\n constructor(config: VaultBalanceConfig) {\n this.config = config;\n this.bitcoinProvider = config.bitcoinProvider;\n }\n\n /**\n * Calculate balance (fast path - no UTXO validation)\n *\n * Fast balance-only calculation that skips UTXO validation.\n * Uses simple arithmetic: Total Balance - Authorized Balance = Available Balance\n *\n * Use this when you only need the balance amount and don't need:\n * - Individual UTXO details\n * - Validation that authorized UTXOs were actually spent\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 * @param positionId - The position ID to check\n * @param vaultAddress - Bitcoin address of the vault\n * @param skipUTXOValidation - If true, use fast balance-only path (skips UTXO validation)\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 skipUTXOValidation?: boolean\n ): Promise<VaultBalanceResult> {\n // Fast path: skip UTXO validation if requested\n if (skipUTXOValidation) {\n return await this.calculateBalance(positionId, vaultAddress);\n }\n\n // Full validation path (default)\n const minConfirmations = this.config.minConfirmations || 6;\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. CRITICAL: Validate each authorized spend state\n // For each authorized spend, check if UTXO still exists as unspent\n for (const spend of authorizedSpends) {\n const utxoStillExists = utxoSet.utxos.some(\n (utxo) => utxo.txid === spend.txid && utxo.vout === spend.vout\n );\n\n if (utxoStillExists) {\n // ERROR B: UTXO authorized in contract but still unspent on Bitcoin network\n // This means SDK authorized but never signed/broadcasted the spending transaction\n throw new Error(\n `Authorized UTXO ${spend.txid}:${spend.vout} not yet spent. ` +\n `Transaction was authorized in smart contract but not signed and broadcasted to Bitcoin network. ` +\n `Complete the transaction by signing and broadcasting it.`\n );\n }\n\n // UTXO no longer exists as unspent (it's been spent)\n // This is expected - now we verify the spending transaction has enough confirmations\n // Note: spend.txid refers to the INPUT UTXO, not the spending transaction\n // We cannot validate spending transaction confirmations without storing its txid\n // For now, we trust that if UTXO doesn't exist, it's been properly spent\n // TODO: Consider adding spendingTxid to AuthorizedSpend for full validation\n }\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 // 5. Filter out UTXOs that are authorized (not available)\n // Note: After validation above, authorized UTXOs should NOT appear in utxoSet\n // But we filter anyway for safety\n const availableUTXOs = utxoSet.utxos.filter(\n (utxo) => !this.isUTXOAuthorized(utxo, authorizedSpends)\n );\n\n // 6. Calculate available balance\n const availableBalance = availableUTXOs.reduce(\n (sum, utxo) => sum + utxo.satoshis,\n 0n\n );\n\n // 7. 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 // @ts-ignore - Lit.Actions is available in LIT runtime\n rpcUrl = await Lit.Actions.getRpcUrl({ chain: this.config.chain });\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 { url: rpcUrl, timeout: 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 * 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"],
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,SA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