@babylonlabs-io/ts-sdk 0.45.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/{PeginManager-CL1Esl1c.cjs → PeginManager-CeloRUHV.cjs} +2 -2
  2. package/dist/{PeginManager-CL1Esl1c.cjs.map → PeginManager-CeloRUHV.cjs.map} +1 -1
  3. package/dist/{PeginManager-CFGjwYtC.js → PeginManager-CxSbzoYs.js} +2 -2
  4. package/dist/{PeginManager-CFGjwYtC.js.map → PeginManager-CxSbzoYs.js.map} +1 -1
  5. package/dist/{buildAndBroadcastRefund-CZj2z7PJ.js → buildAndBroadcastRefund-BssyvGWW.js} +2 -2
  6. package/dist/{buildAndBroadcastRefund-CZj2z7PJ.js.map → buildAndBroadcastRefund-BssyvGWW.js.map} +1 -1
  7. package/dist/{buildAndBroadcastRefund-Ux587SFf.cjs → buildAndBroadcastRefund-CgUJ7Mpf.cjs} +2 -2
  8. package/dist/{buildAndBroadcastRefund-Ux587SFf.cjs.map → buildAndBroadcastRefund-CgUJ7Mpf.cjs.map} +1 -1
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.js +5 -5
  11. package/dist/mempoolApi-BxT89SAq.js +471 -0
  12. package/dist/mempoolApi-BxT89SAq.js.map +1 -0
  13. package/dist/mempoolApi-C_9JhjCI.cjs +2 -0
  14. package/dist/mempoolApi-C_9JhjCI.cjs.map +1 -0
  15. package/dist/primeVpAuth-Br6RwE3r.cjs +2 -0
  16. package/dist/{primeVpAuth-BihAGyNf.cjs.map → primeVpAuth-Br6RwE3r.cjs.map} +1 -1
  17. package/dist/{primeVpAuth-DXl9wGBR.js → primeVpAuth-rbejoBPu.js} +208 -200
  18. package/dist/{primeVpAuth-DXl9wGBR.js.map → primeVpAuth-rbejoBPu.js.map} +1 -1
  19. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  20. package/dist/tbv/core/clients/index.cjs +1 -1
  21. package/dist/tbv/core/clients/index.js +3 -3
  22. package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts +6 -0
  23. package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts.map +1 -1
  24. package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts +8 -0
  25. package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts.map +1 -1
  26. package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts +14 -4
  27. package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts.map +1 -1
  28. package/dist/tbv/core/clients/vault-provider/types.d.ts +3 -0
  29. package/dist/tbv/core/clients/vault-provider/types.d.ts.map +1 -1
  30. package/dist/tbv/core/index.cjs +1 -1
  31. package/dist/tbv/core/index.js +5 -5
  32. package/dist/tbv/core/managers/index.cjs +1 -1
  33. package/dist/tbv/core/managers/index.js +1 -1
  34. package/dist/tbv/core/services/index.cjs +1 -1
  35. package/dist/tbv/core/services/index.js +1 -1
  36. package/dist/tbv/index.cjs +1 -1
  37. package/dist/tbv/index.js +5 -5
  38. package/dist/tbv/integrations/aave/clients/index.d.ts +1 -1
  39. package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
  40. package/dist/tbv/integrations/aave/clients/oracle.d.ts +8 -1
  41. package/dist/tbv/integrations/aave/clients/oracle.d.ts.map +1 -1
  42. package/dist/tbv/integrations/aave/clients/spoke.d.ts +27 -0
  43. package/dist/tbv/integrations/aave/clients/spoke.d.ts.map +1 -1
  44. package/dist/tbv/integrations/aave/constants.d.ts +3 -3
  45. package/dist/tbv/integrations/aave/constants.d.ts.map +1 -1
  46. package/dist/tbv/integrations/aave/index.cjs +1 -1
  47. package/dist/tbv/integrations/aave/index.cjs.map +1 -1
  48. package/dist/tbv/integrations/aave/index.d.ts +1 -1
  49. package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
  50. package/dist/tbv/integrations/aave/index.js +276 -212
  51. package/dist/tbv/integrations/aave/index.js.map +1 -1
  52. package/dist/{types-BqGAMOZM.js → types-CQDRQvV-.js} +11 -10
  53. package/dist/types-CQDRQvV-.js.map +1 -0
  54. package/dist/{types-eYlq0p1o.cjs → types-WA0LrDk1.cjs} +2 -2
  55. package/dist/types-WA0LrDk1.cjs.map +1 -0
  56. package/package.json +1 -1
  57. package/dist/mempoolApi-DcHws8jJ.cjs +0 -2
  58. package/dist/mempoolApi-DcHws8jJ.cjs.map +0 -1
  59. package/dist/mempoolApi-DnP7d084.js +0 -451
  60. package/dist/mempoolApi-DnP7d084.js.map +0 -1
  61. package/dist/primeVpAuth-BihAGyNf.cjs +0 -2
  62. package/dist/types-BqGAMOZM.js.map +0 -1
  63. package/dist/types-eYlq0p1o.cjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-CQDRQvV-.js","sources":["../src/tbv/core/clients/vault-provider/json-rpc-client.ts","../src/tbv/core/clients/vault-provider/types.ts"],"sourcesContent":["/**\n * Generic JSON-RPC 2.0 HTTP Client\n *\n * Framework-agnostic client using `fetch()` — works in browsers and Node.js 18+.\n * Includes configurable retry policy and AbortSignal passthrough.\n */\n\nexport interface JsonRpcRequest<T = unknown> {\n jsonrpc: \"2.0\";\n method: string;\n params: T;\n id: number | string;\n}\n\nexport interface JsonRpcSuccessResponse<T = unknown> {\n jsonrpc: \"2.0\";\n result: T;\n id: number | string;\n}\n\nexport interface JsonRpcErrorResponse {\n jsonrpc: \"2.0\";\n error: {\n code: number;\n message: string;\n data?: unknown;\n };\n id: number | string;\n}\n\nexport type JsonRpcResponse<T = unknown> =\n | JsonRpcSuccessResponse<T>\n | JsonRpcErrorResponse;\n\n/**\n * Injects bearer tokens into requests for auth-gated methods, and is\n * notified on auth-expired responses so it can invalidate its cache.\n *\n * The `JsonRpcClient` is agnostic to which methods are auth-gated —\n * the provider's `getToken(method)` decides. Returning `null` means\n * \"no auth required for this method\"; the client then sends the\n * request with no `Authorization` header.\n */\nexport interface BearerTokenProvider {\n /**\n * Return the bearer token to inject for `method`, or `null` if the\n * method does not require auth.\n */\n getToken(method: string): Promise<string | null>;\n /**\n * Drop the cached token. Next call to `getToken` must re-acquire.\n * Called by the client on reactive-refresh-trigger responses.\n */\n invalidate(): void;\n}\n\nexport interface JsonRpcClientConfig {\n /** Base URL of the RPC service */\n baseUrl: string;\n /** Timeout in milliseconds per request attempt */\n timeout: number;\n /** Optional custom headers */\n headers?: Record<string, string>;\n /** Number of retry attempts for transient errors (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /**\n * Maximum response body size, in bytes, for typed JSON-RPC calls.\n * `callRaw` intentionally returns the unparsed Response and is not capped here.\n * Default: 2 MiB.\n */\n maxResponseBytes?: number;\n /**\n * Predicate that decides which methods retry on transient errors.\n * Default retries only `getPeginStatus`, `batchGetPeginStatus`,\n * `batchGetPegoutStatus`, and `requestDepositorPresignTransactions`.\n * Write methods are not retried by default.\n */\n retryableFor?: (method: string) => boolean;\n /**\n * Per-request bearer-token source. A non-null return attaches\n * `Authorization: Bearer <token>`; `null` skips auth. `call`\n * additionally retries once on wire `auth_expired` (invalidate +\n * refetch + retry). `callRaw` skips reactive refresh.\n */\n tokenProvider?: BearerTokenProvider;\n}\n\n// \"wire\" = parsed from a JSON-RPC error envelope; \"local\" = timeout/network/parse failure.\nexport type JsonRpcErrorSource = \"wire\" | \"local\";\n\nexport class JsonRpcError extends Error {\n constructor(\n public code: number,\n message: string,\n /** \"wire\" for server-returned envelopes; \"local\" for SDK-side failures. */\n public source: JsonRpcErrorSource = \"local\",\n /** Structured data from the server `error.data` field, if any. */\n public data?: unknown,\n ) {\n super(message);\n this.name = \"JsonRpcError\";\n }\n}\n\nexport const JSON_RPC_ERROR_CODES = {\n TIMEOUT: -32000,\n NETWORK: -32001,\n /** VP proxy: request timed out at proxy level */\n PROXY_TIMEOUT: -32002,\n /** VP proxy: VP unreachable / DNS failure / response too large */\n PROXY_UNAVAILABLE: -32003,\n /** SDK client: response missing \"result\" field (malformed JSON-RPC) */\n INVALID_RESPONSE: -32700,\n /** SDK client: response body exceeded the configured byte limit */\n RESPONSE_TOO_LARGE: -32701,\n} as const;\n\n/** JSON-RPC protocol version */\nconst JSON_RPC_VERSION = \"2.0\" as const;\n\n/** Default number of retry attempts for transient errors */\nconst DEFAULT_RETRY_ATTEMPTS = 3;\n\n/** Default initial retry delay in milliseconds */\nconst DEFAULT_RETRY_DELAY_MS = 1000;\n\n/** Default maximum JSON-RPC response size for typed calls (2 MiB) */\nconst DEFAULT_MAX_RESPONSE_BYTES = 2 * 1024 * 1024;\n\n/**\n * TODO: Temporary typed-call exceptions for methods that currently return large\n * artifact payloads as JSON-RPC results.\n */\nconst UNCAPPED_TYPED_RESPONSE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_requestDepositorClaimerArtifacts\",\n]);\n\n/** HTTP status codes that indicate transient server errors and are safe to retry */\nconst RETRYABLE_HTTP_STATUS_CODES: ReadonlySet<number> = new Set([\n 408, // Request Timeout\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n]);\n\n/** Default retry predicate: only retry read-only / idempotent methods */\nconst DEFAULT_RETRYABLE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_getPeginStatus\",\n \"vaultProvider_batchGetPeginStatus\",\n \"vaultProvider_batchGetPegoutStatus\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nfunction defaultRetryableFor(method: string): boolean {\n return DEFAULT_RETRYABLE_METHODS.has(method);\n}\n\n/**\n * Token-expired marker the server emits in `error.data.kind`. When\n * present on a wire-origin error, the client invalidates its cached\n * token and retries the request once with a freshly-acquired bearer.\n *\n * Kept in sync with btc-vault's auth middleware. Absence of the marker\n * means the server does not support reactive refresh yet; we fall back\n * to proactive-only refresh via `BearerTokenProvider.getToken()` TTL\n * checks.\n */\nexport const AUTH_EXPIRED_DATA_KIND = \"auth_expired\";\n\nfunction isAuthExpiredError(error: unknown): boolean {\n if (!(error instanceof JsonRpcError)) return false;\n if (error.source !== \"wire\") return false;\n const data = error.data;\n if (data === null || typeof data !== \"object\") return false;\n const kind = (data as { kind?: unknown }).kind;\n return kind === AUTH_EXPIRED_DATA_KIND;\n}\n\n/**\n * Generic JSON-RPC 2.0 HTTP client with safe retry policy.\n */\nexport class JsonRpcClient {\n private baseUrl: string;\n private timeout: number;\n private headers: Record<string, string>;\n private requestId = 0;\n private retries: number;\n private retryDelay: number;\n private maxResponseBytes: number;\n private retryableFor: (method: string) => boolean;\n private tokenProvider?: BearerTokenProvider;\n\n constructor(config: JsonRpcClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, \"\");\n this.timeout = config.timeout;\n this.headers = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n this.retries = config.retries ?? DEFAULT_RETRY_ATTEMPTS;\n this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;\n this.maxResponseBytes =\n config.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;\n if (!Number.isFinite(this.maxResponseBytes) || this.maxResponseBytes <= 0) {\n throw new Error(\"maxResponseBytes must be a positive finite number\");\n }\n this.retryableFor = config.retryableFor ?? defaultRetryableFor;\n this.tokenProvider = config.tokenProvider;\n }\n\n private async buildHeaders(method: string): Promise<Record<string, string>> {\n const headers: Record<string, string> = { ...this.headers };\n if (this.tokenProvider) {\n const token = await this.tokenProvider.getToken(method);\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n }\n }\n return headers;\n }\n\n /**\n * Make a JSON-RPC request with optional retry for safe methods.\n *\n * If the request fails with a wire-origin `auth_expired` error and a\n * `tokenProvider` is configured, the client invalidates its cached\n * token and retries the request once with a freshly-acquired bearer.\n *\n * @param method - The RPC method name\n * @param params - The method parameters\n * @param signal - Optional AbortSignal for caller-controlled cancellation\n * @returns The result from the RPC method\n * @throws JsonRpcError if the RPC call fails\n */\n async call<TParams, TResult>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<TResult> {\n try {\n return await this.callOnce<TParams, TResult>(method, params, signal);\n } catch (error) {\n // The auth-expired retry fires for ALL methods, including mutating\n // ones. This is intentional and safe: the server's auth middleware\n // validates the bearer token BEFORE dispatching to the method\n // handler, so an `auth_expired` error means the handler never ran\n // and no state was mutated. Confirmed against btc-vault at\n // `crates/btc-auth/src/middleware/jsonrpc.rs` — token validation\n // is pre-handler only. The `retryableFor` guard on\n // HTTP-transient-error retries doesn't apply here because that\n // guard is about retrying after a request the server may have\n // started processing; auth_expired is categorically different.\n if (this.tokenProvider && isAuthExpiredError(error)) {\n this.tokenProvider.invalidate();\n return await this.callOnce<TParams, TResult>(method, params, signal);\n }\n throw error;\n }\n }\n\n private async callOnce<TParams, TResult>(\n method: string,\n params: TParams,\n signal: AbortSignal | undefined,\n ): Promise<TResult> {\n const response = await this.fetchWithRetry(method, params, signal);\n\n let jsonResponse: unknown;\n try {\n const responseText = UNCAPPED_TYPED_RESPONSE_METHODS.has(method)\n ? await response.text()\n : await readResponseTextWithLimit(response, this.maxResponseBytes);\n jsonResponse = JSON.parse(responseText);\n } catch (error) {\n if (error instanceof JsonRpcError) {\n throw error;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n \"Invalid JSON-RPC response: body is not valid JSON\",\n \"local\",\n );\n }\n\n if (\n jsonResponse === null ||\n typeof jsonResponse !== \"object\" ||\n Array.isArray(jsonResponse)\n ) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: expected an object, got ${typeof jsonResponse}`,\n \"local\",\n );\n }\n\n const rpcResponse = jsonResponse as Record<string, unknown>;\n\n if (\"error\" in rpcResponse && rpcResponse.error != null) {\n const err = rpcResponse.error as {\n code?: number;\n message?: string;\n data?: unknown;\n };\n throw new JsonRpcError(\n err.code ?? JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n err.message ?? \"Unknown RPC error\",\n \"wire\",\n err.data,\n );\n }\n\n if (!(\"result\" in rpcResponse)) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: missing \"result\" field`,\n \"local\",\n );\n }\n\n return rpcResponse.result as TResult;\n }\n\n /**\n * Make a JSON-RPC request returning the raw Response (unparsed body).\n *\n * Bearer tokens are injected identically to `call`. **Reactive refresh\n * is NOT performed here** — the response body may be unbounded (e.g.\n * claimer-artifact downloads), so the client refuses to parse it to\n * detect auth errors. Callers relying on token-expired retries for\n * large downloads must read the body themselves and re-invoke\n * `callRaw` after `tokenProvider.invalidate()`.\n */\n async callRaw<TParams>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<Response> {\n return this.fetchWithRetry(method, params, signal);\n }\n\n private async fetchWithRetry<TParams>(\n method: string,\n params: TParams,\n callerSignal?: AbortSignal,\n ): Promise<Response> {\n const requestId = ++this.requestId;\n const maxRetries = this.retryableFor(method) ? this.retries : 0;\n\n // jsonrpsee (Rust backend) expects params as an array (positional parameters)\n const request: JsonRpcRequest<TParams[]> = {\n jsonrpc: JSON_RPC_VERSION,\n method,\n params: [params],\n id: requestId,\n };\n\n const body = JSON.stringify(request);\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n // Merge caller signal with per-request timeout signal\n const timeoutController = new AbortController();\n const timeoutId = setTimeout(\n () => timeoutController.abort(),\n this.timeout,\n );\n\n const merged = callerSignal\n ? mergeAbortSignals(callerSignal, timeoutController.signal)\n : null;\n const signal = merged ? merged.signal : timeoutController.signal;\n\n try {\n // Build headers per-attempt so the token provider can return a\n // freshly-acquired bearer after a prior invalidate() on this\n // request (retry loop path) without plumbing state through.\n const headers = await this.buildHeaders(method);\n\n const response = await fetch(this.baseUrl, {\n method: \"POST\",\n headers,\n body,\n signal,\n });\n\n clearTimeout(timeoutId);\n merged?.cleanup();\n\n if (!response.ok) {\n const shouldRetry =\n attempt < maxRetries &&\n RETRYABLE_HTTP_STATUS_CODES.has(response.status);\n\n if (shouldRetry) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n\n throw new Error(\n `HTTP error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n merged?.cleanup();\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check if caller aborted (not our timeout)\n if (callerSignal?.aborted) {\n throw new Error(\"Request aborted\");\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.TIMEOUT,\n `Request timeout after ${this.timeout}ms (${maxRetries + 1} attempts)`,\n \"local\",\n );\n }\n\n // Handle network errors (CORS, connection refused, etc.)\n if (error instanceof TypeError) {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.NETWORK,\n `Network error: ${error.message} (${maxRetries + 1} attempts)`,\n \"local\",\n );\n }\n\n // Don't retry JSON-RPC errors (business logic errors)\n throw error;\n }\n }\n\n throw lastError || new Error(\"Unknown error after retries\");\n }\n\n private sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error(\"Request aborted\"));\n return;\n }\n const timeoutId = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timeoutId);\n reject(new Error(\"Request aborted\"));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n getBaseUrl(): string {\n return this.baseUrl;\n }\n}\n\ninterface MergedSignal {\n signal: AbortSignal;\n /** Remove listeners from the source signals. Call after the request completes. */\n cleanup: () => void;\n}\n\n/**\n * Merge two AbortSignals — the returned signal aborts if either input aborts.\n * Returns a cleanup function to remove listeners when the request completes\n * normally, preventing listener accumulation in long-lived polling flows.\n */\nfunction mergeAbortSignals(a: AbortSignal, b: AbortSignal): MergedSignal {\n if (a.aborted) return { signal: a, cleanup: () => {} };\n if (b.aborted) return { signal: b, cleanup: () => {} };\n\n const controller = new AbortController();\n const onAbortA = () => {\n b.removeEventListener(\"abort\", onAbortB);\n controller.abort();\n };\n const onAbortB = () => {\n a.removeEventListener(\"abort\", onAbortA);\n controller.abort();\n };\n a.addEventListener(\"abort\", onAbortA, { once: true });\n b.addEventListener(\"abort\", onAbortB, { once: true });\n\n const cleanup = () => {\n a.removeEventListener(\"abort\", onAbortA);\n b.removeEventListener(\"abort\", onAbortB);\n };\n\n return { signal: controller.signal, cleanup };\n}\n\nasync function readResponseTextWithLimit(\n response: Response,\n maxBytes: number,\n): Promise<string> {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength !== null) {\n const parsedContentLength = Number(contentLength);\n if (\n Number.isFinite(parsedContentLength) &&\n parsedContentLength > maxBytes\n ) {\n throw responseTooLargeError(maxBytes);\n }\n }\n\n if (!response.body) {\n return \"\";\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let totalBytes = 0;\n let responseText = \"\";\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n\n totalBytes += value.byteLength;\n if (totalBytes > maxBytes) {\n await reader.cancel();\n throw responseTooLargeError(maxBytes);\n }\n responseText += decoder.decode(value, { stream: true });\n }\n } finally {\n reader.releaseLock();\n }\n\n return responseText + decoder.decode();\n}\n\nfunction responseTooLargeError(maxBytes: number): JsonRpcError {\n return new JsonRpcError(\n JSON_RPC_ERROR_CODES.RESPONSE_TOO_LARGE,\n `JSON-RPC response exceeds maximum size of ${maxBytes} bytes`,\n \"local\",\n );\n}\n","/**\n * Type definitions for Vault Provider JSON-RPC API.\n *\n * These types match the `vaultProvider_*` RPC namespace defined by the\n * btc-vault daemon. They are the SDK's canonical copy of the VP protocol\n * contract, independent of any frontend framework.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\n// ============================================================================\n// Daemon Status\n// ============================================================================\n\n/**\n * Backend daemon status (vault provider database).\n * Source: btc-vault crates/vaultd/src/workers/claimer/mod.rs PegInStatus enum\n *\n * State flow (happy path):\n * PendingIngestion -> PendingDepositorWotsPK -> PendingBabeSetup -> PendingChallengerPresigning\n * -> PendingPeginSigsAvailability -> PendingPrePegInConfirmations\n * -> PendingDepositorSignatures -> PendingACKs -> PendingActivation\n * -> ActivatedPendingBroadcast -> Activated\n *\n * Branching / terminal states:\n * - IngestionRejected: terminal — ingestion permanently failed (e.g. malformed\n * Pre-PegIn, invalid HTLC outputs); reachable directly from PendingIngestion.\n * - Expired: activation timed out; non-terminal during the grace window\n * (RFC 003) — transitions to ExpiredCleanedUp or ExpiredInClaim.\n * - InvalidSigInContract: terminal — pegin input signature posted on\n * chain failed verification.\n * - AmlRejected: terminal — AML address screening rejected the pegin.\n * - ExpiredCleanedUp: terminal — grace window expired, per-pegin\n * artifacts deleted.\n * - ExpiredInClaim: terminal at the pegin-state-machine level; pegout-side\n * work continues on the pegout_tracking row.\n */\nexport enum DaemonStatus {\n PENDING_INGESTION = \"PendingIngestion\",\n PENDING_DEPOSITOR_WOTS_PK = \"PendingDepositorWotsPK\",\n PENDING_BABE_SETUP = \"PendingBabeSetup\",\n PENDING_CHALLENGER_PRESIGNING = \"PendingChallengerPresigning\",\n PENDING_PEGIN_SIGS_AVAILABILITY = \"PendingPeginSigsAvailability\",\n PENDING_PRE_PEGIN_CONFIRMATIONS = \"PendingPrePegInConfirmations\",\n PENDING_DEPOSITOR_SIGNATURES = \"PendingDepositorSignatures\",\n PENDING_ACKS = \"PendingACKs\",\n PENDING_ACTIVATION = \"PendingActivation\",\n ACTIVATED_PENDING_BROADCAST = \"ActivatedPendingBroadcast\",\n ACTIVATED = \"Activated\",\n EXPIRED = \"Expired\",\n INGESTION_REJECTED = \"IngestionRejected\",\n INVALID_SIG_IN_CONTRACT = \"InvalidSigInContract\",\n AML_REJECTED = \"AmlRejected\",\n EXPIRED_CLEANED_UP = \"ExpiredCleanedUp\",\n EXPIRED_IN_CLAIM = \"ExpiredInClaim\",\n}\n\n// ============================================================================\n// Status Groups\n// ============================================================================\n\n/**\n * States where the VP is still processing (no depositor action needed).\n * Excludes PENDING_DEPOSITOR_WOTS_PK (requires depositor action).\n */\nexport const PRE_DEPOSITOR_SIGNATURES_STATES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_INGESTION,\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n];\n\n/** States after PendingDepositorSignatures where the depositor has no action. */\nconst POST_PAYOUT_SIGNATURE_STATUSES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_ACKS,\n DaemonStatus.PENDING_ACTIVATION,\n DaemonStatus.ACTIVATED_PENDING_BROADCAST,\n DaemonStatus.ACTIVATED,\n];\n\n/**\n * Statuses where no depositor action is needed (VP processing or already past\n * depositor interaction). Excludes PENDING_INGESTION and PENDING_DEPOSITOR_WOTS_PK.\n */\nexport const VP_TRANSIENT_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n ...POST_PAYOUT_SIGNATURE_STATUSES,\n]);\n\n/**\n * Terminal VP statuses that represent failure outcomes — polling should\n * stop immediately with an error rather than wait for timeout.\n *\n * Mirrors the failure subset of the server-side terminals\n * (`allowed_transitions()` empty, see\n * `btc-vault/crates/vaultd/src/workers/claimer/mod.rs:230-242`).\n * `Activated` IS terminal on-chain but is the success outcome, so it is\n * intentionally excluded — a caller polling for an earlier state that\n * races straight to `Activated` should treat that as success-via-overshoot,\n * not failure. `Expired` is also excluded — under RFC 003 it is a\n * grace-window interim that transitions to `ExpiredCleanedUp` or\n * `ExpiredInClaim`. Callers that want to stop polling on any expiry\n * should check `status === DaemonStatus.EXPIRED ||\n * VP_TERMINAL_FAILURE_STATUSES.has(status)`.\n */\nexport const VP_TERMINAL_FAILURE_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.INGESTION_REJECTED,\n DaemonStatus.INVALID_SIG_IN_CONTRACT,\n DaemonStatus.AML_REJECTED,\n DaemonStatus.EXPIRED_CLEANED_UP,\n DaemonStatus.EXPIRED_IN_CLAIM,\n]);\n\n/**\n * Statuses that come after WOTS key submission.\n * If the VP is already in one of these states, the WOTS key was already\n * submitted and we can skip.\n */\nexport const POST_WOTS_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n ...VP_TRANSIENT_STATUSES,\n DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,\n]);\n\n// ============================================================================\n// WOTS Types (needed by SubmitDepositorWotsKeyParams)\n// ============================================================================\n\n/**\n * WOTS configuration for a single block.\n * Matches Rust `babe::wots::Config` serde format.\n */\nexport interface WotsConfig {\n /** Digit bit-width (e.g. 4 → base-16 digits). */\n d: number;\n /** Number of message digits in this block. */\n n: number;\n /** Radix used for the checksum computation. */\n checksum_radix: number;\n}\n\n/**\n * A single block of WOTS public keys.\n * Chain values are arrays of byte values (matching Rust `[u8; 20]`).\n */\nexport interface WotsBlockPublicKey {\n config: WotsConfig;\n message_terminals: number[][];\n checksum_major_terminal: number[];\n checksum_minor_terminal: number[];\n}\n\n// ============================================================================\n// Request Parameter Types\n// ============================================================================\n\n/** Params for requesting the payout/claim/assert transactions to pre-sign. */\nexport interface RequestDepositorPresignTransactionsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for submitting the depositor's WOTS public key to the VP. */\nexport interface SubmitDepositorWotsKeyParams {\n pegin_txid: string;\n depositor_pk: string;\n wots_public_keys: WotsBlockPublicKey[];\n}\n\n/** Per-challenger signatures for the depositor-as-claimer flow. */\nexport interface DepositorPreSigsPerChallenger {\n nopayout_signature: string;\n}\n\n/** Depositor-as-claimer pre-signatures (payout + per-challenger). */\nexport interface DepositorAsClaimerPresignatures {\n payout_signatures: ClaimerSignatures;\n per_challenger: Record<string, DepositorPreSigsPerChallenger>;\n}\n\n/** Params for submitting depositor pre-signatures including claimer presignatures. */\nexport interface SubmitDepositorPresignaturesParams {\n pegin_txid: string;\n depositor_pk: string;\n signatures: Record<string, ClaimerSignatures>;\n depositor_claimer_presignatures: DepositorAsClaimerPresignatures;\n}\n\n/** Payout signatures per claimer. */\nexport interface ClaimerSignatures {\n payout_signature: string;\n}\n\n/** Params for requesting BaBe DecryptorArtifacts from the VP. */\nexport interface RequestDepositorClaimerArtifactsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for querying pegin status. Either pegin_txid or vault_id must be provided. */\nexport type GetPeginStatusParams =\n | { pegin_txid: string; vault_id?: never }\n | { vault_id: string; pegin_txid?: never };\n\n// ============================================================================\n// Response Types\n// ============================================================================\n\n/** A raw Bitcoin transaction with its hex encoding. */\nexport interface TransactionData {\n tx_hex: string;\n}\n\n/** Set of transactions the depositor must pre-sign for a single claimer. */\nexport interface ClaimerTransactions {\n claimer_pubkey: string;\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n}\n\n/** Per-segment connector data for ChallengeAssert inputs. */\nexport interface ChallengeAssertConnectorData {\n wots_pks_json: string;\n gc_wots_keys_json: string;\n}\n\n/** Challenger-specific transactions and signing data for the depositor graph. */\nexport interface PresignDataPerChallenger {\n challenger_pubkey: string;\n challenge_assert_x_tx: TransactionData;\n challenge_assert_y_tx: TransactionData;\n nopayout_tx: TransactionData;\n nopayout_psbt: string;\n challenge_assert_connectors: ChallengeAssertConnectorData[];\n output_label_hashes: string[];\n}\n\n/** Depositor-as-claimer TxGraph transactions. */\nexport interface DepositorGraphTransactions {\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n challenger_presign_data: PresignDataPerChallenger[];\n offchain_params_version: number;\n}\n\n/** Response from `requestDepositorPresignTransactions`. */\nexport interface RequestDepositorPresignTransactionsResponse {\n txs: ClaimerTransactions[];\n depositor_graph: DepositorGraphTransactions;\n}\n\n/** BaBe garbled-circuit session data for a single challenger. */\nexport interface BaBeSessionData {\n decryptor_artifacts_hex: string;\n}\n\n/** Response from `requestDepositorClaimerArtifacts`. */\nexport interface RequestDepositorClaimerArtifactsResponse {\n tx_graph_json: string;\n verifying_key_hex: string;\n babe_sessions: Record<string, BaBeSessionData>;\n}\n\n/** Progress tracker for a multi-challenger operation. */\nexport interface ChallengerProgress {\n total_challengers: number;\n completed_challengers: number;\n completed_challenger_pubkeys: string[];\n pending_challenger_pubkeys: string[];\n}\n\nexport type GcDataProgress = ChallengerProgress;\nexport type AckCollectionProgress = ChallengerProgress;\n\n/** Extended presigning progress with all 3 concurrent phases. */\nexport interface PresigningProgress extends ChallengerProgress {\n depositor_graph_created?: boolean;\n vk_challenger_presigning_completed?: number;\n vk_challenger_presigning_total?: number;\n}\n\n/** Detailed progress breakdown for an in-progress pegin. */\nexport interface PeginProgressDetails {\n gc_data?: GcDataProgress;\n presigning?: PresigningProgress;\n ack_collection?: AckCollectionProgress;\n claimer_graphs?: ClaimerGraphStatus[];\n}\n\n/** Per-claimer graph status (challenger perspective). */\nexport interface ClaimerGraphStatus {\n claimer_pubkey: string;\n presigned: boolean;\n}\n\n/** Response from `getPeginStatus`. */\nexport interface GetPeginStatusResponse {\n pegin_txid: string;\n status: string;\n progress: PeginProgressDetails;\n health_info: string;\n last_error?: string;\n}\n\n// ============================================================================\n// Pegout Types\n// ============================================================================\n\n/**\n * Claimer-side pegout progress.\n * Source: btc-vault crates/vaultd/src/rpc/server/pegout_status.rs ClaimerPegoutStatus.\n */\nexport interface ClaimerPegoutStatus {\n /** Wire string from PegoutStatus enum. */\n status: string;\n failed: boolean;\n claim_txid: string;\n claimer_pubkey: string;\n assert_txid: string;\n /** Unix epoch seconds. */\n created_at: number;\n /** Unix epoch seconds. */\n updated_at: number;\n}\n\n/**\n * Challenger-side pegout progress.\n * Source: btc-vault crates/vaultd/src/rpc/server/pegout_status.rs ChallengerStatus.\n */\nexport interface ChallengerStatus {\n status: string;\n claim_txid: string;\n claimer_pubkey: string;\n assert_txid: string | null;\n challenge_assert_x_txid: string | null;\n challenge_assert_y_txid: string | null;\n nopayout_txid: string | null;\n created_at: number;\n updated_at: number;\n}\n\n/**\n * Pegout status response. Embedded by `batchGetPegoutStatus` per-result\n * envelopes. Mirrors btc-vault `GetPegoutStatusResponse`.\n */\nexport interface GetPegoutStatusResponse {\n pegin_txid: string;\n found: boolean;\n claimer: ClaimerPegoutStatus | null;\n challengers: ChallengerStatus[];\n}\n\n// ============================================================================\n// Batch Status Types (peginStatus + pegoutStatus)\n// ============================================================================\n\n/** Params for `batchGetPeginStatus`. */\nexport interface BatchGetPeginStatusParams {\n /** Up to MAX_BATCH_SIZE (50) txids per call. */\n pegin_txids: string[];\n}\n\n/** Per-pegin entry in a `batchGetPeginStatus` response. */\nexport interface BatchPeginStatusResult {\n pegin_txid: string;\n result: GetPeginStatusResponse | null;\n error: string | null;\n}\n\n/** Response from `batchGetPeginStatus`. Results are returned in request order. */\nexport interface BatchGetPeginStatusResponse {\n results: BatchPeginStatusResult[];\n}\n\n/** Params for `batchGetPegoutStatus`. */\nexport interface BatchGetPegoutStatusParams {\n pegin_txids: string[];\n}\n\n/** Per-vault entry in a `batchGetPegoutStatus` response. */\nexport interface BatchPegoutStatusResult {\n pegin_txid: string;\n result: GetPegoutStatusResponse | null;\n error: string | null;\n}\n\n/** Response from `batchGetPegoutStatus`. Results are returned in request order. */\nexport interface BatchGetPegoutStatusResponse {\n results: BatchPegoutStatusResult[];\n}\n\n/**\n * Maximum number of items per batch call. Mirrors the server-side\n * `MAX_BATCH_SIZE` in btc-vault (`crates/vaultd/src/rpc/server/vault_provider.rs:7`).\n * Callers must chunk requests larger than this.\n */\nexport const VP_BATCH_MAX_SIZE = 50;\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/**\n * JSON-RPC error codes returned by the vault provider.\n * Source: btc-vault `crates/vaultd/src/rpc/error.rs::RpcError::error_code`.\n */\nexport enum RpcErrorCode {\n PEGIN_NOT_FOUND = 4001,\n}\n"],"names":["JsonRpcError","code","message","source","data","JSON_RPC_ERROR_CODES","JSON_RPC_VERSION","DEFAULT_RETRY_ATTEMPTS","DEFAULT_RETRY_DELAY_MS","DEFAULT_MAX_RESPONSE_BYTES","UNCAPPED_TYPED_RESPONSE_METHODS","RETRYABLE_HTTP_STATUS_CODES","DEFAULT_RETRYABLE_METHODS","defaultRetryableFor","method","AUTH_EXPIRED_DATA_KIND","isAuthExpiredError","error","JsonRpcClient","config","__publicField","headers","token","params","signal","response","jsonResponse","responseText","readResponseTextWithLimit","rpcResponse","err","callerSignal","requestId","maxRetries","body","lastError","attempt","timeoutController","timeoutId","merged","mergeAbortSignals","delay","ms","resolve","reject","onAbort","a","b","controller","onAbortA","onAbortB","cleanup","maxBytes","contentLength","parsedContentLength","responseTooLargeError","reader","decoder","totalBytes","done","value","DaemonStatus","PRE_DEPOSITOR_SIGNATURES_STATES","POST_PAYOUT_SIGNATURE_STATUSES","VP_TRANSIENT_STATUSES","VP_TERMINAL_FAILURE_STATUSES","POST_WOTS_STATUSES","VP_BATCH_MAX_SIZE","RpcErrorCode"],"mappings":";;;AA4FO,MAAMA,UAAqB,MAAM;AAAA,EACtC,YACSC,GACPC,GAEOC,IAA6B,SAE7BC,GACP;AACA,UAAMF,CAAO,GAPN,KAAA,OAAAD,GAGA,KAAA,SAAAE,GAEA,KAAA,OAAAC,GAGP,KAAK,OAAO;AAAA,EACd;AACF;AAEO,MAAMC,IAAu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,EAAA,+BAA+B,8BAC/BA,EAAA,eAAe,eACfA,EAAA,qBAAqB,qBACrBA,EAAA,8BAA8B,6BAC9BA,EAAA,YAAY,aACZA,EAAA,UAAU,WACVA,EAAA,qBAAqB,qBACrBA,EAAA,0BAA0B,wBAC1BA,EAAA,eAAe,eACfA,EAAA,qBAAqB,oBACrBA,EAAA,mBAAmB,kBAjBTA,IAAAA,KAAA,CAAA,CAAA;AA4BL,MAAMC,IAA2D;AAAA,EACtE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AACF,GAGMC,IAA0D;AAAA,EAC9D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AACF,GAMaC,wBAAuD,IAAI;AAAA,EACtE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAGD;AACL,CAAC,GAkBYE,wBAA8D,IAAI;AAAA,EAC7E;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AACF,CAAC,GAOYC,wBAAoD,IAAI;AAAA,EACnE,GAAGF;AAAA,EACH;AAAA;AACF,CAAC,GAsRYG,IAAoB;AAU1B,IAAKC,sBAAAA,OACVA,EAAAA,EAAA,kBAAkB,IAAA,IAAlB,mBADUA,IAAAA,KAAA,CAAA,CAAA;"}
@@ -1,2 +1,2 @@
1
- "use strict";var y=Object.defineProperty;var b=(t,e,r)=>e in t?y(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var c=(t,e,r)=>b(t,typeof e!="symbol"?e+"":e,r);class d extends Error{constructor(e,r,n="local",s){super(r),this.code=e,this.source=n,this.data=s,this.name="JsonRpcError"}}const l={TIMEOUT:-32e3,NETWORK:-32001,PROXY_TIMEOUT:-32002,PROXY_UNAVAILABLE:-32003,INVALID_RESPONSE:-32700,RESPONSE_TOO_LARGE:-32701},f="2.0",v=3,C=1e3,D=2*1024*1024,g=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),L=new Set([408,429,500,502,503,504]),U=new Set(["vaultProvider_getPeginStatus","vaultProvider_batchGetPeginStatus","vaultProvider_batchGetPegoutStatus","vaultProvider_requestDepositorPresignTransactions"]);function m(t){return U.has(t)}const I="auth_expired";function G(t){if(!(t instanceof d)||t.source!=="wire")return!1;const e=t.data;return e===null||typeof e!="object"?!1:e.kind===I}class B{constructor(e){c(this,"baseUrl");c(this,"timeout");c(this,"headers");c(this,"requestId",0);c(this,"retries");c(this,"retryDelay");c(this,"maxResponseBytes");c(this,"retryableFor");c(this,"tokenProvider");if(this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.headers={"Content-Type":"application/json",...e.headers},this.retries=e.retries??v,this.retryDelay=e.retryDelay??C,this.maxResponseBytes=e.maxResponseBytes??D,!Number.isFinite(this.maxResponseBytes)||this.maxResponseBytes<=0)throw new Error("maxResponseBytes must be a positive finite number");this.retryableFor=e.retryableFor??m,this.tokenProvider=e.tokenProvider}async buildHeaders(e){const r={...this.headers};if(this.tokenProvider){const n=await this.tokenProvider.getToken(e);n&&(r.Authorization=`Bearer ${n}`)}return r}async call(e,r,n){try{return await this.callOnce(e,r,n)}catch(s){if(this.tokenProvider&&G(s))return this.tokenProvider.invalidate(),await this.callOnce(e,r,n);throw s}}async callOnce(e,r,n){const s=await this.fetchWithRetry(e,r,n);let o;try{const i=g.has(e)?await s.text():await k(s,this.maxResponseBytes);o=JSON.parse(i)}catch(i){throw i instanceof d?i:new d(l.INVALID_RESPONSE,"Invalid JSON-RPC response: body is not valid JSON","local")}if(o===null||typeof o!="object"||Array.isArray(o))throw new d(l.INVALID_RESPONSE,`Invalid JSON-RPC response: expected an object, got ${typeof o}`,"local");const a=o;if("error"in a&&a.error!=null){const i=a.error;throw new d(i.code??l.INVALID_RESPONSE,i.message??"Unknown RPC error","wire",i.data)}if(!("result"in a))throw new d(l.INVALID_RESPONSE,'Invalid JSON-RPC response: missing "result" field',"local");return a.result}async callRaw(e,r,n){return this.fetchWithRetry(e,r,n)}async fetchWithRetry(e,r,n){const s=++this.requestId,o=this.retryableFor(e)?this.retries:0,i=JSON.stringify({jsonrpc:f,method:e,params:[r],id:s});let u=null;for(let T=0;T<=o;T++){const A=new AbortController,R=setTimeout(()=>A.abort(),this.timeout),_=n?x(n,A.signal):null,O=_?_.signal:A.signal;try{const E=await this.buildHeaders(e),P=await fetch(this.baseUrl,{method:"POST",headers:E,body:i,signal:O});if(clearTimeout(R),_==null||_.cleanup(),!P.ok){if(T<o&&L.has(P.status)){const w=this.retryDelay*Math.pow(2,T);await this.sleep(w,n);continue}throw new Error(`HTTP error: ${P.status} ${P.statusText}`)}return P}catch(E){if(clearTimeout(R),_==null||_.cleanup(),u=E instanceof Error?E:new Error(String(E)),n!=null&&n.aborted)throw new Error("Request aborted");if(E instanceof Error&&E.name==="AbortError"){if(T<o){const P=this.retryDelay*Math.pow(2,T);await this.sleep(P,n);continue}throw new d(l.TIMEOUT,`Request timeout after ${this.timeout}ms (${o+1} attempts)`,"local")}if(E instanceof TypeError){if(T<o){const P=this.retryDelay*Math.pow(2,T);await this.sleep(P,n);continue}throw new d(l.NETWORK,`Network error: ${E.message} (${o+1} attempts)`,"local")}throw E}}throw u||new Error("Unknown error after retries")}sleep(e,r){return new Promise((n,s)=>{if(r!=null&&r.aborted){s(new Error("Request aborted"));return}const o=setTimeout(()=>{r==null||r.removeEventListener("abort",a),n()},e),a=()=>{clearTimeout(o),s(new Error("Request aborted"))};r==null||r.addEventListener("abort",a,{once:!0})})}getBaseUrl(){return this.baseUrl}}function x(t,e){if(t.aborted)return{signal:t,cleanup:()=>{}};if(e.aborted)return{signal:e,cleanup:()=>{}};const r=new AbortController,n=()=>{e.removeEventListener("abort",s),r.abort()},s=()=>{t.removeEventListener("abort",n),r.abort()};t.addEventListener("abort",n,{once:!0}),e.addEventListener("abort",s,{once:!0});const o=()=>{t.removeEventListener("abort",n),e.removeEventListener("abort",s)};return{signal:r.signal,cleanup:o}}async function k(t,e){const r=t.headers.get("content-length");if(r!==null){const i=Number(r);if(Number.isFinite(i)&&i>e)throw S(e)}if(!t.body)return"";const n=t.body.getReader(),s=new TextDecoder;let o=0,a="";try{for(;;){const{done:i,value:u}=await n.read();if(i)break;if(u){if(o+=u.byteLength,o>e)throw await n.cancel(),S(e);a+=s.decode(u,{stream:!0})}}}finally{n.releaseLock()}return a+s.decode()}function S(t){return new d(l.RESPONSE_TOO_LARGE,`JSON-RPC response exceeds maximum size of ${t} bytes`,"local")}var h=(t=>(t.PENDING_INGESTION="PendingIngestion",t.PENDING_DEPOSITOR_WOTS_PK="PendingDepositorWotsPK",t.PENDING_BABE_SETUP="PendingBabeSetup",t.PENDING_CHALLENGER_PRESIGNING="PendingChallengerPresigning",t.PENDING_PEGIN_SIGS_AVAILABILITY="PendingPeginSigsAvailability",t.PENDING_PRE_PEGIN_CONFIRMATIONS="PendingPrePegInConfirmations",t.PENDING_DEPOSITOR_SIGNATURES="PendingDepositorSignatures",t.PENDING_ACKS="PendingACKs",t.PENDING_ACTIVATION="PendingActivation",t.ACTIVATED_PENDING_BROADCAST="ActivatedPendingBroadcast",t.ACTIVATED="Activated",t.EXPIRED="Expired",t.INVALID_SIG_IN_CONTRACT="InvalidSigInContract",t.AML_REJECTED="AmlRejected",t.EXPIRED_CLEANED_UP="ExpiredCleanedUp",t.EXPIRED_IN_CLAIM="ExpiredInClaim",t))(h||{});const M=["PendingIngestion","PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations"],V=["PendingACKs","PendingActivation","ActivatedPendingBroadcast","Activated"],N=new Set(["PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations",...V]),F=new Set(["InvalidSigInContract","AmlRejected","ExpiredCleanedUp","ExpiredInClaim"]),J=new Set([...N,"PendingDepositorSignatures"]),q=50;var p=(t=>(t[t.PEGIN_NOT_FOUND=4001]="PEGIN_NOT_FOUND",t))(p||{});exports.AUTH_EXPIRED_DATA_KIND=I;exports.DaemonStatus=h;exports.JSON_RPC_ERROR_CODES=l;exports.JsonRpcClient=B;exports.JsonRpcError=d;exports.POST_WOTS_STATUSES=J;exports.PRE_DEPOSITOR_SIGNATURES_STATES=M;exports.RpcErrorCode=p;exports.VP_BATCH_MAX_SIZE=q;exports.VP_TERMINAL_FAILURE_STATUSES=F;exports.VP_TRANSIENT_STATUSES=N;
2
- //# sourceMappingURL=types-eYlq0p1o.cjs.map
1
+ "use strict";var y=Object.defineProperty;var b=(t,e,r)=>e in t?y(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var c=(t,e,r)=>b(t,typeof e!="symbol"?e+"":e,r);class d extends Error{constructor(e,r,n="local",s){super(r),this.code=e,this.source=n,this.data=s,this.name="JsonRpcError"}}const l={TIMEOUT:-32e3,NETWORK:-32001,PROXY_TIMEOUT:-32002,PROXY_UNAVAILABLE:-32003,INVALID_RESPONSE:-32700,RESPONSE_TOO_LARGE:-32701},f="2.0",v=3,C=1e3,D=2*1024*1024,g=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),L=new Set([408,429,500,502,503,504]),U=new Set(["vaultProvider_getPeginStatus","vaultProvider_batchGetPeginStatus","vaultProvider_batchGetPegoutStatus","vaultProvider_requestDepositorPresignTransactions"]);function m(t){return U.has(t)}const S="auth_expired";function G(t){if(!(t instanceof d)||t.source!=="wire")return!1;const e=t.data;return e===null||typeof e!="object"?!1:e.kind===S}class B{constructor(e){c(this,"baseUrl");c(this,"timeout");c(this,"headers");c(this,"requestId",0);c(this,"retries");c(this,"retryDelay");c(this,"maxResponseBytes");c(this,"retryableFor");c(this,"tokenProvider");if(this.baseUrl=e.baseUrl.replace(/\/$/,""),this.timeout=e.timeout,this.headers={"Content-Type":"application/json",...e.headers},this.retries=e.retries??v,this.retryDelay=e.retryDelay??C,this.maxResponseBytes=e.maxResponseBytes??D,!Number.isFinite(this.maxResponseBytes)||this.maxResponseBytes<=0)throw new Error("maxResponseBytes must be a positive finite number");this.retryableFor=e.retryableFor??m,this.tokenProvider=e.tokenProvider}async buildHeaders(e){const r={...this.headers};if(this.tokenProvider){const n=await this.tokenProvider.getToken(e);n&&(r.Authorization=`Bearer ${n}`)}return r}async call(e,r,n){try{return await this.callOnce(e,r,n)}catch(s){if(this.tokenProvider&&G(s))return this.tokenProvider.invalidate(),await this.callOnce(e,r,n);throw s}}async callOnce(e,r,n){const s=await this.fetchWithRetry(e,r,n);let o;try{const i=g.has(e)?await s.text():await k(s,this.maxResponseBytes);o=JSON.parse(i)}catch(i){throw i instanceof d?i:new d(l.INVALID_RESPONSE,"Invalid JSON-RPC response: body is not valid JSON","local")}if(o===null||typeof o!="object"||Array.isArray(o))throw new d(l.INVALID_RESPONSE,`Invalid JSON-RPC response: expected an object, got ${typeof o}`,"local");const a=o;if("error"in a&&a.error!=null){const i=a.error;throw new d(i.code??l.INVALID_RESPONSE,i.message??"Unknown RPC error","wire",i.data)}if(!("result"in a))throw new d(l.INVALID_RESPONSE,'Invalid JSON-RPC response: missing "result" field',"local");return a.result}async callRaw(e,r,n){return this.fetchWithRetry(e,r,n)}async fetchWithRetry(e,r,n){const s=++this.requestId,o=this.retryableFor(e)?this.retries:0,i=JSON.stringify({jsonrpc:f,method:e,params:[r],id:s});let R=null;for(let T=0;T<=o;T++){const u=new AbortController,A=setTimeout(()=>u.abort(),this.timeout),_=n?x(n,u.signal):null,O=_?_.signal:u.signal;try{const E=await this.buildHeaders(e),P=await fetch(this.baseUrl,{method:"POST",headers:E,body:i,signal:O});if(clearTimeout(A),_==null||_.cleanup(),!P.ok){if(T<o&&L.has(P.status)){const w=this.retryDelay*Math.pow(2,T);await this.sleep(w,n);continue}throw new Error(`HTTP error: ${P.status} ${P.statusText}`)}return P}catch(E){if(clearTimeout(A),_==null||_.cleanup(),R=E instanceof Error?E:new Error(String(E)),n!=null&&n.aborted)throw new Error("Request aborted");if(E instanceof Error&&E.name==="AbortError"){if(T<o){const P=this.retryDelay*Math.pow(2,T);await this.sleep(P,n);continue}throw new d(l.TIMEOUT,`Request timeout after ${this.timeout}ms (${o+1} attempts)`,"local")}if(E instanceof TypeError){if(T<o){const P=this.retryDelay*Math.pow(2,T);await this.sleep(P,n);continue}throw new d(l.NETWORK,`Network error: ${E.message} (${o+1} attempts)`,"local")}throw E}}throw R||new Error("Unknown error after retries")}sleep(e,r){return new Promise((n,s)=>{if(r!=null&&r.aborted){s(new Error("Request aborted"));return}const o=setTimeout(()=>{r==null||r.removeEventListener("abort",a),n()},e),a=()=>{clearTimeout(o),s(new Error("Request aborted"))};r==null||r.addEventListener("abort",a,{once:!0})})}getBaseUrl(){return this.baseUrl}}function x(t,e){if(t.aborted)return{signal:t,cleanup:()=>{}};if(e.aborted)return{signal:e,cleanup:()=>{}};const r=new AbortController,n=()=>{e.removeEventListener("abort",s),r.abort()},s=()=>{t.removeEventListener("abort",n),r.abort()};t.addEventListener("abort",n,{once:!0}),e.addEventListener("abort",s,{once:!0});const o=()=>{t.removeEventListener("abort",n),e.removeEventListener("abort",s)};return{signal:r.signal,cleanup:o}}async function k(t,e){const r=t.headers.get("content-length");if(r!==null){const i=Number(r);if(Number.isFinite(i)&&i>e)throw I(e)}if(!t.body)return"";const n=t.body.getReader(),s=new TextDecoder;let o=0,a="";try{for(;;){const{done:i,value:R}=await n.read();if(i)break;if(R){if(o+=R.byteLength,o>e)throw await n.cancel(),I(e);a+=s.decode(R,{stream:!0})}}}finally{n.releaseLock()}return a+s.decode()}function I(t){return new d(l.RESPONSE_TOO_LARGE,`JSON-RPC response exceeds maximum size of ${t} bytes`,"local")}var h=(t=>(t.PENDING_INGESTION="PendingIngestion",t.PENDING_DEPOSITOR_WOTS_PK="PendingDepositorWotsPK",t.PENDING_BABE_SETUP="PendingBabeSetup",t.PENDING_CHALLENGER_PRESIGNING="PendingChallengerPresigning",t.PENDING_PEGIN_SIGS_AVAILABILITY="PendingPeginSigsAvailability",t.PENDING_PRE_PEGIN_CONFIRMATIONS="PendingPrePegInConfirmations",t.PENDING_DEPOSITOR_SIGNATURES="PendingDepositorSignatures",t.PENDING_ACKS="PendingACKs",t.PENDING_ACTIVATION="PendingActivation",t.ACTIVATED_PENDING_BROADCAST="ActivatedPendingBroadcast",t.ACTIVATED="Activated",t.EXPIRED="Expired",t.INGESTION_REJECTED="IngestionRejected",t.INVALID_SIG_IN_CONTRACT="InvalidSigInContract",t.AML_REJECTED="AmlRejected",t.EXPIRED_CLEANED_UP="ExpiredCleanedUp",t.EXPIRED_IN_CLAIM="ExpiredInClaim",t))(h||{});const M=["PendingIngestion","PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations"],V=["PendingACKs","PendingActivation","ActivatedPendingBroadcast","Activated"],N=new Set(["PendingBabeSetup","PendingChallengerPresigning","PendingPeginSigsAvailability","PendingPrePegInConfirmations",...V]),J=new Set(["IngestionRejected","InvalidSigInContract","AmlRejected","ExpiredCleanedUp","ExpiredInClaim"]),F=new Set([...N,"PendingDepositorSignatures"]),q=50;var p=(t=>(t[t.PEGIN_NOT_FOUND=4001]="PEGIN_NOT_FOUND",t))(p||{});exports.AUTH_EXPIRED_DATA_KIND=S;exports.DaemonStatus=h;exports.JSON_RPC_ERROR_CODES=l;exports.JsonRpcClient=B;exports.JsonRpcError=d;exports.POST_WOTS_STATUSES=F;exports.PRE_DEPOSITOR_SIGNATURES_STATES=M;exports.RpcErrorCode=p;exports.VP_BATCH_MAX_SIZE=q;exports.VP_TERMINAL_FAILURE_STATUSES=J;exports.VP_TRANSIENT_STATUSES=N;
2
+ //# sourceMappingURL=types-WA0LrDk1.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-WA0LrDk1.cjs","sources":["../src/tbv/core/clients/vault-provider/json-rpc-client.ts","../src/tbv/core/clients/vault-provider/types.ts"],"sourcesContent":["/**\n * Generic JSON-RPC 2.0 HTTP Client\n *\n * Framework-agnostic client using `fetch()` — works in browsers and Node.js 18+.\n * Includes configurable retry policy and AbortSignal passthrough.\n */\n\nexport interface JsonRpcRequest<T = unknown> {\n jsonrpc: \"2.0\";\n method: string;\n params: T;\n id: number | string;\n}\n\nexport interface JsonRpcSuccessResponse<T = unknown> {\n jsonrpc: \"2.0\";\n result: T;\n id: number | string;\n}\n\nexport interface JsonRpcErrorResponse {\n jsonrpc: \"2.0\";\n error: {\n code: number;\n message: string;\n data?: unknown;\n };\n id: number | string;\n}\n\nexport type JsonRpcResponse<T = unknown> =\n | JsonRpcSuccessResponse<T>\n | JsonRpcErrorResponse;\n\n/**\n * Injects bearer tokens into requests for auth-gated methods, and is\n * notified on auth-expired responses so it can invalidate its cache.\n *\n * The `JsonRpcClient` is agnostic to which methods are auth-gated —\n * the provider's `getToken(method)` decides. Returning `null` means\n * \"no auth required for this method\"; the client then sends the\n * request with no `Authorization` header.\n */\nexport interface BearerTokenProvider {\n /**\n * Return the bearer token to inject for `method`, or `null` if the\n * method does not require auth.\n */\n getToken(method: string): Promise<string | null>;\n /**\n * Drop the cached token. Next call to `getToken` must re-acquire.\n * Called by the client on reactive-refresh-trigger responses.\n */\n invalidate(): void;\n}\n\nexport interface JsonRpcClientConfig {\n /** Base URL of the RPC service */\n baseUrl: string;\n /** Timeout in milliseconds per request attempt */\n timeout: number;\n /** Optional custom headers */\n headers?: Record<string, string>;\n /** Number of retry attempts for transient errors (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /**\n * Maximum response body size, in bytes, for typed JSON-RPC calls.\n * `callRaw` intentionally returns the unparsed Response and is not capped here.\n * Default: 2 MiB.\n */\n maxResponseBytes?: number;\n /**\n * Predicate that decides which methods retry on transient errors.\n * Default retries only `getPeginStatus`, `batchGetPeginStatus`,\n * `batchGetPegoutStatus`, and `requestDepositorPresignTransactions`.\n * Write methods are not retried by default.\n */\n retryableFor?: (method: string) => boolean;\n /**\n * Per-request bearer-token source. A non-null return attaches\n * `Authorization: Bearer <token>`; `null` skips auth. `call`\n * additionally retries once on wire `auth_expired` (invalidate +\n * refetch + retry). `callRaw` skips reactive refresh.\n */\n tokenProvider?: BearerTokenProvider;\n}\n\n// \"wire\" = parsed from a JSON-RPC error envelope; \"local\" = timeout/network/parse failure.\nexport type JsonRpcErrorSource = \"wire\" | \"local\";\n\nexport class JsonRpcError extends Error {\n constructor(\n public code: number,\n message: string,\n /** \"wire\" for server-returned envelopes; \"local\" for SDK-side failures. */\n public source: JsonRpcErrorSource = \"local\",\n /** Structured data from the server `error.data` field, if any. */\n public data?: unknown,\n ) {\n super(message);\n this.name = \"JsonRpcError\";\n }\n}\n\nexport const JSON_RPC_ERROR_CODES = {\n TIMEOUT: -32000,\n NETWORK: -32001,\n /** VP proxy: request timed out at proxy level */\n PROXY_TIMEOUT: -32002,\n /** VP proxy: VP unreachable / DNS failure / response too large */\n PROXY_UNAVAILABLE: -32003,\n /** SDK client: response missing \"result\" field (malformed JSON-RPC) */\n INVALID_RESPONSE: -32700,\n /** SDK client: response body exceeded the configured byte limit */\n RESPONSE_TOO_LARGE: -32701,\n} as const;\n\n/** JSON-RPC protocol version */\nconst JSON_RPC_VERSION = \"2.0\" as const;\n\n/** Default number of retry attempts for transient errors */\nconst DEFAULT_RETRY_ATTEMPTS = 3;\n\n/** Default initial retry delay in milliseconds */\nconst DEFAULT_RETRY_DELAY_MS = 1000;\n\n/** Default maximum JSON-RPC response size for typed calls (2 MiB) */\nconst DEFAULT_MAX_RESPONSE_BYTES = 2 * 1024 * 1024;\n\n/**\n * TODO: Temporary typed-call exceptions for methods that currently return large\n * artifact payloads as JSON-RPC results.\n */\nconst UNCAPPED_TYPED_RESPONSE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_requestDepositorClaimerArtifacts\",\n]);\n\n/** HTTP status codes that indicate transient server errors and are safe to retry */\nconst RETRYABLE_HTTP_STATUS_CODES: ReadonlySet<number> = new Set([\n 408, // Request Timeout\n 429, // Too Many Requests\n 500, // Internal Server Error\n 502, // Bad Gateway\n 503, // Service Unavailable\n 504, // Gateway Timeout\n]);\n\n/** Default retry predicate: only retry read-only / idempotent methods */\nconst DEFAULT_RETRYABLE_METHODS: ReadonlySet<string> = new Set([\n \"vaultProvider_getPeginStatus\",\n \"vaultProvider_batchGetPeginStatus\",\n \"vaultProvider_batchGetPegoutStatus\",\n \"vaultProvider_requestDepositorPresignTransactions\",\n]);\n\nfunction defaultRetryableFor(method: string): boolean {\n return DEFAULT_RETRYABLE_METHODS.has(method);\n}\n\n/**\n * Token-expired marker the server emits in `error.data.kind`. When\n * present on a wire-origin error, the client invalidates its cached\n * token and retries the request once with a freshly-acquired bearer.\n *\n * Kept in sync with btc-vault's auth middleware. Absence of the marker\n * means the server does not support reactive refresh yet; we fall back\n * to proactive-only refresh via `BearerTokenProvider.getToken()` TTL\n * checks.\n */\nexport const AUTH_EXPIRED_DATA_KIND = \"auth_expired\";\n\nfunction isAuthExpiredError(error: unknown): boolean {\n if (!(error instanceof JsonRpcError)) return false;\n if (error.source !== \"wire\") return false;\n const data = error.data;\n if (data === null || typeof data !== \"object\") return false;\n const kind = (data as { kind?: unknown }).kind;\n return kind === AUTH_EXPIRED_DATA_KIND;\n}\n\n/**\n * Generic JSON-RPC 2.0 HTTP client with safe retry policy.\n */\nexport class JsonRpcClient {\n private baseUrl: string;\n private timeout: number;\n private headers: Record<string, string>;\n private requestId = 0;\n private retries: number;\n private retryDelay: number;\n private maxResponseBytes: number;\n private retryableFor: (method: string) => boolean;\n private tokenProvider?: BearerTokenProvider;\n\n constructor(config: JsonRpcClientConfig) {\n this.baseUrl = config.baseUrl.replace(/\\/$/, \"\");\n this.timeout = config.timeout;\n this.headers = {\n \"Content-Type\": \"application/json\",\n ...config.headers,\n };\n this.retries = config.retries ?? DEFAULT_RETRY_ATTEMPTS;\n this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;\n this.maxResponseBytes =\n config.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES;\n if (!Number.isFinite(this.maxResponseBytes) || this.maxResponseBytes <= 0) {\n throw new Error(\"maxResponseBytes must be a positive finite number\");\n }\n this.retryableFor = config.retryableFor ?? defaultRetryableFor;\n this.tokenProvider = config.tokenProvider;\n }\n\n private async buildHeaders(method: string): Promise<Record<string, string>> {\n const headers: Record<string, string> = { ...this.headers };\n if (this.tokenProvider) {\n const token = await this.tokenProvider.getToken(method);\n if (token) {\n headers.Authorization = `Bearer ${token}`;\n }\n }\n return headers;\n }\n\n /**\n * Make a JSON-RPC request with optional retry for safe methods.\n *\n * If the request fails with a wire-origin `auth_expired` error and a\n * `tokenProvider` is configured, the client invalidates its cached\n * token and retries the request once with a freshly-acquired bearer.\n *\n * @param method - The RPC method name\n * @param params - The method parameters\n * @param signal - Optional AbortSignal for caller-controlled cancellation\n * @returns The result from the RPC method\n * @throws JsonRpcError if the RPC call fails\n */\n async call<TParams, TResult>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<TResult> {\n try {\n return await this.callOnce<TParams, TResult>(method, params, signal);\n } catch (error) {\n // The auth-expired retry fires for ALL methods, including mutating\n // ones. This is intentional and safe: the server's auth middleware\n // validates the bearer token BEFORE dispatching to the method\n // handler, so an `auth_expired` error means the handler never ran\n // and no state was mutated. Confirmed against btc-vault at\n // `crates/btc-auth/src/middleware/jsonrpc.rs` — token validation\n // is pre-handler only. The `retryableFor` guard on\n // HTTP-transient-error retries doesn't apply here because that\n // guard is about retrying after a request the server may have\n // started processing; auth_expired is categorically different.\n if (this.tokenProvider && isAuthExpiredError(error)) {\n this.tokenProvider.invalidate();\n return await this.callOnce<TParams, TResult>(method, params, signal);\n }\n throw error;\n }\n }\n\n private async callOnce<TParams, TResult>(\n method: string,\n params: TParams,\n signal: AbortSignal | undefined,\n ): Promise<TResult> {\n const response = await this.fetchWithRetry(method, params, signal);\n\n let jsonResponse: unknown;\n try {\n const responseText = UNCAPPED_TYPED_RESPONSE_METHODS.has(method)\n ? await response.text()\n : await readResponseTextWithLimit(response, this.maxResponseBytes);\n jsonResponse = JSON.parse(responseText);\n } catch (error) {\n if (error instanceof JsonRpcError) {\n throw error;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n \"Invalid JSON-RPC response: body is not valid JSON\",\n \"local\",\n );\n }\n\n if (\n jsonResponse === null ||\n typeof jsonResponse !== \"object\" ||\n Array.isArray(jsonResponse)\n ) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: expected an object, got ${typeof jsonResponse}`,\n \"local\",\n );\n }\n\n const rpcResponse = jsonResponse as Record<string, unknown>;\n\n if (\"error\" in rpcResponse && rpcResponse.error != null) {\n const err = rpcResponse.error as {\n code?: number;\n message?: string;\n data?: unknown;\n };\n throw new JsonRpcError(\n err.code ?? JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n err.message ?? \"Unknown RPC error\",\n \"wire\",\n err.data,\n );\n }\n\n if (!(\"result\" in rpcResponse)) {\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.INVALID_RESPONSE,\n `Invalid JSON-RPC response: missing \"result\" field`,\n \"local\",\n );\n }\n\n return rpcResponse.result as TResult;\n }\n\n /**\n * Make a JSON-RPC request returning the raw Response (unparsed body).\n *\n * Bearer tokens are injected identically to `call`. **Reactive refresh\n * is NOT performed here** — the response body may be unbounded (e.g.\n * claimer-artifact downloads), so the client refuses to parse it to\n * detect auth errors. Callers relying on token-expired retries for\n * large downloads must read the body themselves and re-invoke\n * `callRaw` after `tokenProvider.invalidate()`.\n */\n async callRaw<TParams>(\n method: string,\n params: TParams,\n signal?: AbortSignal,\n ): Promise<Response> {\n return this.fetchWithRetry(method, params, signal);\n }\n\n private async fetchWithRetry<TParams>(\n method: string,\n params: TParams,\n callerSignal?: AbortSignal,\n ): Promise<Response> {\n const requestId = ++this.requestId;\n const maxRetries = this.retryableFor(method) ? this.retries : 0;\n\n // jsonrpsee (Rust backend) expects params as an array (positional parameters)\n const request: JsonRpcRequest<TParams[]> = {\n jsonrpc: JSON_RPC_VERSION,\n method,\n params: [params],\n id: requestId,\n };\n\n const body = JSON.stringify(request);\n let lastError: Error | null = null;\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n // Merge caller signal with per-request timeout signal\n const timeoutController = new AbortController();\n const timeoutId = setTimeout(\n () => timeoutController.abort(),\n this.timeout,\n );\n\n const merged = callerSignal\n ? mergeAbortSignals(callerSignal, timeoutController.signal)\n : null;\n const signal = merged ? merged.signal : timeoutController.signal;\n\n try {\n // Build headers per-attempt so the token provider can return a\n // freshly-acquired bearer after a prior invalidate() on this\n // request (retry loop path) without plumbing state through.\n const headers = await this.buildHeaders(method);\n\n const response = await fetch(this.baseUrl, {\n method: \"POST\",\n headers,\n body,\n signal,\n });\n\n clearTimeout(timeoutId);\n merged?.cleanup();\n\n if (!response.ok) {\n const shouldRetry =\n attempt < maxRetries &&\n RETRYABLE_HTTP_STATUS_CODES.has(response.status);\n\n if (shouldRetry) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n\n throw new Error(\n `HTTP error: ${response.status} ${response.statusText}`,\n );\n }\n\n return response;\n } catch (error) {\n clearTimeout(timeoutId);\n merged?.cleanup();\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check if caller aborted (not our timeout)\n if (callerSignal?.aborted) {\n throw new Error(\"Request aborted\");\n }\n\n if (error instanceof Error && error.name === \"AbortError\") {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.TIMEOUT,\n `Request timeout after ${this.timeout}ms (${maxRetries + 1} attempts)`,\n \"local\",\n );\n }\n\n // Handle network errors (CORS, connection refused, etc.)\n if (error instanceof TypeError) {\n if (attempt < maxRetries) {\n const delay = this.retryDelay * Math.pow(2, attempt);\n await this.sleep(delay, callerSignal);\n continue;\n }\n throw new JsonRpcError(\n JSON_RPC_ERROR_CODES.NETWORK,\n `Network error: ${error.message} (${maxRetries + 1} attempts)`,\n \"local\",\n );\n }\n\n // Don't retry JSON-RPC errors (business logic errors)\n throw error;\n }\n }\n\n throw lastError || new Error(\"Unknown error after retries\");\n }\n\n private sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(new Error(\"Request aborted\"));\n return;\n }\n const timeoutId = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timeoutId);\n reject(new Error(\"Request aborted\"));\n };\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n }\n\n getBaseUrl(): string {\n return this.baseUrl;\n }\n}\n\ninterface MergedSignal {\n signal: AbortSignal;\n /** Remove listeners from the source signals. Call after the request completes. */\n cleanup: () => void;\n}\n\n/**\n * Merge two AbortSignals — the returned signal aborts if either input aborts.\n * Returns a cleanup function to remove listeners when the request completes\n * normally, preventing listener accumulation in long-lived polling flows.\n */\nfunction mergeAbortSignals(a: AbortSignal, b: AbortSignal): MergedSignal {\n if (a.aborted) return { signal: a, cleanup: () => {} };\n if (b.aborted) return { signal: b, cleanup: () => {} };\n\n const controller = new AbortController();\n const onAbortA = () => {\n b.removeEventListener(\"abort\", onAbortB);\n controller.abort();\n };\n const onAbortB = () => {\n a.removeEventListener(\"abort\", onAbortA);\n controller.abort();\n };\n a.addEventListener(\"abort\", onAbortA, { once: true });\n b.addEventListener(\"abort\", onAbortB, { once: true });\n\n const cleanup = () => {\n a.removeEventListener(\"abort\", onAbortA);\n b.removeEventListener(\"abort\", onAbortB);\n };\n\n return { signal: controller.signal, cleanup };\n}\n\nasync function readResponseTextWithLimit(\n response: Response,\n maxBytes: number,\n): Promise<string> {\n const contentLength = response.headers.get(\"content-length\");\n if (contentLength !== null) {\n const parsedContentLength = Number(contentLength);\n if (\n Number.isFinite(parsedContentLength) &&\n parsedContentLength > maxBytes\n ) {\n throw responseTooLargeError(maxBytes);\n }\n }\n\n if (!response.body) {\n return \"\";\n }\n\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let totalBytes = 0;\n let responseText = \"\";\n\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n if (!value) continue;\n\n totalBytes += value.byteLength;\n if (totalBytes > maxBytes) {\n await reader.cancel();\n throw responseTooLargeError(maxBytes);\n }\n responseText += decoder.decode(value, { stream: true });\n }\n } finally {\n reader.releaseLock();\n }\n\n return responseText + decoder.decode();\n}\n\nfunction responseTooLargeError(maxBytes: number): JsonRpcError {\n return new JsonRpcError(\n JSON_RPC_ERROR_CODES.RESPONSE_TOO_LARGE,\n `JSON-RPC response exceeds maximum size of ${maxBytes} bytes`,\n \"local\",\n );\n}\n","/**\n * Type definitions for Vault Provider JSON-RPC API.\n *\n * These types match the `vaultProvider_*` RPC namespace defined by the\n * btc-vault daemon. They are the SDK's canonical copy of the VP protocol\n * contract, independent of any frontend framework.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\n// ============================================================================\n// Daemon Status\n// ============================================================================\n\n/**\n * Backend daemon status (vault provider database).\n * Source: btc-vault crates/vaultd/src/workers/claimer/mod.rs PegInStatus enum\n *\n * State flow (happy path):\n * PendingIngestion -> PendingDepositorWotsPK -> PendingBabeSetup -> PendingChallengerPresigning\n * -> PendingPeginSigsAvailability -> PendingPrePegInConfirmations\n * -> PendingDepositorSignatures -> PendingACKs -> PendingActivation\n * -> ActivatedPendingBroadcast -> Activated\n *\n * Branching / terminal states:\n * - IngestionRejected: terminal — ingestion permanently failed (e.g. malformed\n * Pre-PegIn, invalid HTLC outputs); reachable directly from PendingIngestion.\n * - Expired: activation timed out; non-terminal during the grace window\n * (RFC 003) — transitions to ExpiredCleanedUp or ExpiredInClaim.\n * - InvalidSigInContract: terminal — pegin input signature posted on\n * chain failed verification.\n * - AmlRejected: terminal — AML address screening rejected the pegin.\n * - ExpiredCleanedUp: terminal — grace window expired, per-pegin\n * artifacts deleted.\n * - ExpiredInClaim: terminal at the pegin-state-machine level; pegout-side\n * work continues on the pegout_tracking row.\n */\nexport enum DaemonStatus {\n PENDING_INGESTION = \"PendingIngestion\",\n PENDING_DEPOSITOR_WOTS_PK = \"PendingDepositorWotsPK\",\n PENDING_BABE_SETUP = \"PendingBabeSetup\",\n PENDING_CHALLENGER_PRESIGNING = \"PendingChallengerPresigning\",\n PENDING_PEGIN_SIGS_AVAILABILITY = \"PendingPeginSigsAvailability\",\n PENDING_PRE_PEGIN_CONFIRMATIONS = \"PendingPrePegInConfirmations\",\n PENDING_DEPOSITOR_SIGNATURES = \"PendingDepositorSignatures\",\n PENDING_ACKS = \"PendingACKs\",\n PENDING_ACTIVATION = \"PendingActivation\",\n ACTIVATED_PENDING_BROADCAST = \"ActivatedPendingBroadcast\",\n ACTIVATED = \"Activated\",\n EXPIRED = \"Expired\",\n INGESTION_REJECTED = \"IngestionRejected\",\n INVALID_SIG_IN_CONTRACT = \"InvalidSigInContract\",\n AML_REJECTED = \"AmlRejected\",\n EXPIRED_CLEANED_UP = \"ExpiredCleanedUp\",\n EXPIRED_IN_CLAIM = \"ExpiredInClaim\",\n}\n\n// ============================================================================\n// Status Groups\n// ============================================================================\n\n/**\n * States where the VP is still processing (no depositor action needed).\n * Excludes PENDING_DEPOSITOR_WOTS_PK (requires depositor action).\n */\nexport const PRE_DEPOSITOR_SIGNATURES_STATES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_INGESTION,\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n];\n\n/** States after PendingDepositorSignatures where the depositor has no action. */\nconst POST_PAYOUT_SIGNATURE_STATUSES: readonly DaemonStatus[] = [\n DaemonStatus.PENDING_ACKS,\n DaemonStatus.PENDING_ACTIVATION,\n DaemonStatus.ACTIVATED_PENDING_BROADCAST,\n DaemonStatus.ACTIVATED,\n];\n\n/**\n * Statuses where no depositor action is needed (VP processing or already past\n * depositor interaction). Excludes PENDING_INGESTION and PENDING_DEPOSITOR_WOTS_PK.\n */\nexport const VP_TRANSIENT_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.PENDING_BABE_SETUP,\n DaemonStatus.PENDING_CHALLENGER_PRESIGNING,\n DaemonStatus.PENDING_PEGIN_SIGS_AVAILABILITY,\n DaemonStatus.PENDING_PRE_PEGIN_CONFIRMATIONS,\n ...POST_PAYOUT_SIGNATURE_STATUSES,\n]);\n\n/**\n * Terminal VP statuses that represent failure outcomes — polling should\n * stop immediately with an error rather than wait for timeout.\n *\n * Mirrors the failure subset of the server-side terminals\n * (`allowed_transitions()` empty, see\n * `btc-vault/crates/vaultd/src/workers/claimer/mod.rs:230-242`).\n * `Activated` IS terminal on-chain but is the success outcome, so it is\n * intentionally excluded — a caller polling for an earlier state that\n * races straight to `Activated` should treat that as success-via-overshoot,\n * not failure. `Expired` is also excluded — under RFC 003 it is a\n * grace-window interim that transitions to `ExpiredCleanedUp` or\n * `ExpiredInClaim`. Callers that want to stop polling on any expiry\n * should check `status === DaemonStatus.EXPIRED ||\n * VP_TERMINAL_FAILURE_STATUSES.has(status)`.\n */\nexport const VP_TERMINAL_FAILURE_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.INGESTION_REJECTED,\n DaemonStatus.INVALID_SIG_IN_CONTRACT,\n DaemonStatus.AML_REJECTED,\n DaemonStatus.EXPIRED_CLEANED_UP,\n DaemonStatus.EXPIRED_IN_CLAIM,\n]);\n\n/**\n * Statuses that come after WOTS key submission.\n * If the VP is already in one of these states, the WOTS key was already\n * submitted and we can skip.\n */\nexport const POST_WOTS_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n ...VP_TRANSIENT_STATUSES,\n DaemonStatus.PENDING_DEPOSITOR_SIGNATURES,\n]);\n\n// ============================================================================\n// WOTS Types (needed by SubmitDepositorWotsKeyParams)\n// ============================================================================\n\n/**\n * WOTS configuration for a single block.\n * Matches Rust `babe::wots::Config` serde format.\n */\nexport interface WotsConfig {\n /** Digit bit-width (e.g. 4 → base-16 digits). */\n d: number;\n /** Number of message digits in this block. */\n n: number;\n /** Radix used for the checksum computation. */\n checksum_radix: number;\n}\n\n/**\n * A single block of WOTS public keys.\n * Chain values are arrays of byte values (matching Rust `[u8; 20]`).\n */\nexport interface WotsBlockPublicKey {\n config: WotsConfig;\n message_terminals: number[][];\n checksum_major_terminal: number[];\n checksum_minor_terminal: number[];\n}\n\n// ============================================================================\n// Request Parameter Types\n// ============================================================================\n\n/** Params for requesting the payout/claim/assert transactions to pre-sign. */\nexport interface RequestDepositorPresignTransactionsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for submitting the depositor's WOTS public key to the VP. */\nexport interface SubmitDepositorWotsKeyParams {\n pegin_txid: string;\n depositor_pk: string;\n wots_public_keys: WotsBlockPublicKey[];\n}\n\n/** Per-challenger signatures for the depositor-as-claimer flow. */\nexport interface DepositorPreSigsPerChallenger {\n nopayout_signature: string;\n}\n\n/** Depositor-as-claimer pre-signatures (payout + per-challenger). */\nexport interface DepositorAsClaimerPresignatures {\n payout_signatures: ClaimerSignatures;\n per_challenger: Record<string, DepositorPreSigsPerChallenger>;\n}\n\n/** Params for submitting depositor pre-signatures including claimer presignatures. */\nexport interface SubmitDepositorPresignaturesParams {\n pegin_txid: string;\n depositor_pk: string;\n signatures: Record<string, ClaimerSignatures>;\n depositor_claimer_presignatures: DepositorAsClaimerPresignatures;\n}\n\n/** Payout signatures per claimer. */\nexport interface ClaimerSignatures {\n payout_signature: string;\n}\n\n/** Params for requesting BaBe DecryptorArtifacts from the VP. */\nexport interface RequestDepositorClaimerArtifactsParams {\n pegin_txid: string;\n depositor_pk: string;\n}\n\n/** Params for querying pegin status. Either pegin_txid or vault_id must be provided. */\nexport type GetPeginStatusParams =\n | { pegin_txid: string; vault_id?: never }\n | { vault_id: string; pegin_txid?: never };\n\n// ============================================================================\n// Response Types\n// ============================================================================\n\n/** A raw Bitcoin transaction with its hex encoding. */\nexport interface TransactionData {\n tx_hex: string;\n}\n\n/** Set of transactions the depositor must pre-sign for a single claimer. */\nexport interface ClaimerTransactions {\n claimer_pubkey: string;\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n}\n\n/** Per-segment connector data for ChallengeAssert inputs. */\nexport interface ChallengeAssertConnectorData {\n wots_pks_json: string;\n gc_wots_keys_json: string;\n}\n\n/** Challenger-specific transactions and signing data for the depositor graph. */\nexport interface PresignDataPerChallenger {\n challenger_pubkey: string;\n challenge_assert_x_tx: TransactionData;\n challenge_assert_y_tx: TransactionData;\n nopayout_tx: TransactionData;\n nopayout_psbt: string;\n challenge_assert_connectors: ChallengeAssertConnectorData[];\n output_label_hashes: string[];\n}\n\n/** Depositor-as-claimer TxGraph transactions. */\nexport interface DepositorGraphTransactions {\n claim_tx: TransactionData;\n assert_tx: TransactionData;\n payout_tx: TransactionData;\n payout_psbt: string;\n challenger_presign_data: PresignDataPerChallenger[];\n offchain_params_version: number;\n}\n\n/** Response from `requestDepositorPresignTransactions`. */\nexport interface RequestDepositorPresignTransactionsResponse {\n txs: ClaimerTransactions[];\n depositor_graph: DepositorGraphTransactions;\n}\n\n/** BaBe garbled-circuit session data for a single challenger. */\nexport interface BaBeSessionData {\n decryptor_artifacts_hex: string;\n}\n\n/** Response from `requestDepositorClaimerArtifacts`. */\nexport interface RequestDepositorClaimerArtifactsResponse {\n tx_graph_json: string;\n verifying_key_hex: string;\n babe_sessions: Record<string, BaBeSessionData>;\n}\n\n/** Progress tracker for a multi-challenger operation. */\nexport interface ChallengerProgress {\n total_challengers: number;\n completed_challengers: number;\n completed_challenger_pubkeys: string[];\n pending_challenger_pubkeys: string[];\n}\n\nexport type GcDataProgress = ChallengerProgress;\nexport type AckCollectionProgress = ChallengerProgress;\n\n/** Extended presigning progress with all 3 concurrent phases. */\nexport interface PresigningProgress extends ChallengerProgress {\n depositor_graph_created?: boolean;\n vk_challenger_presigning_completed?: number;\n vk_challenger_presigning_total?: number;\n}\n\n/** Detailed progress breakdown for an in-progress pegin. */\nexport interface PeginProgressDetails {\n gc_data?: GcDataProgress;\n presigning?: PresigningProgress;\n ack_collection?: AckCollectionProgress;\n claimer_graphs?: ClaimerGraphStatus[];\n}\n\n/** Per-claimer graph status (challenger perspective). */\nexport interface ClaimerGraphStatus {\n claimer_pubkey: string;\n presigned: boolean;\n}\n\n/** Response from `getPeginStatus`. */\nexport interface GetPeginStatusResponse {\n pegin_txid: string;\n status: string;\n progress: PeginProgressDetails;\n health_info: string;\n last_error?: string;\n}\n\n// ============================================================================\n// Pegout Types\n// ============================================================================\n\n/**\n * Claimer-side pegout progress.\n * Source: btc-vault crates/vaultd/src/rpc/server/pegout_status.rs ClaimerPegoutStatus.\n */\nexport interface ClaimerPegoutStatus {\n /** Wire string from PegoutStatus enum. */\n status: string;\n failed: boolean;\n claim_txid: string;\n claimer_pubkey: string;\n assert_txid: string;\n /** Unix epoch seconds. */\n created_at: number;\n /** Unix epoch seconds. */\n updated_at: number;\n}\n\n/**\n * Challenger-side pegout progress.\n * Source: btc-vault crates/vaultd/src/rpc/server/pegout_status.rs ChallengerStatus.\n */\nexport interface ChallengerStatus {\n status: string;\n claim_txid: string;\n claimer_pubkey: string;\n assert_txid: string | null;\n challenge_assert_x_txid: string | null;\n challenge_assert_y_txid: string | null;\n nopayout_txid: string | null;\n created_at: number;\n updated_at: number;\n}\n\n/**\n * Pegout status response. Embedded by `batchGetPegoutStatus` per-result\n * envelopes. Mirrors btc-vault `GetPegoutStatusResponse`.\n */\nexport interface GetPegoutStatusResponse {\n pegin_txid: string;\n found: boolean;\n claimer: ClaimerPegoutStatus | null;\n challengers: ChallengerStatus[];\n}\n\n// ============================================================================\n// Batch Status Types (peginStatus + pegoutStatus)\n// ============================================================================\n\n/** Params for `batchGetPeginStatus`. */\nexport interface BatchGetPeginStatusParams {\n /** Up to MAX_BATCH_SIZE (50) txids per call. */\n pegin_txids: string[];\n}\n\n/** Per-pegin entry in a `batchGetPeginStatus` response. */\nexport interface BatchPeginStatusResult {\n pegin_txid: string;\n result: GetPeginStatusResponse | null;\n error: string | null;\n}\n\n/** Response from `batchGetPeginStatus`. Results are returned in request order. */\nexport interface BatchGetPeginStatusResponse {\n results: BatchPeginStatusResult[];\n}\n\n/** Params for `batchGetPegoutStatus`. */\nexport interface BatchGetPegoutStatusParams {\n pegin_txids: string[];\n}\n\n/** Per-vault entry in a `batchGetPegoutStatus` response. */\nexport interface BatchPegoutStatusResult {\n pegin_txid: string;\n result: GetPegoutStatusResponse | null;\n error: string | null;\n}\n\n/** Response from `batchGetPegoutStatus`. Results are returned in request order. */\nexport interface BatchGetPegoutStatusResponse {\n results: BatchPegoutStatusResult[];\n}\n\n/**\n * Maximum number of items per batch call. Mirrors the server-side\n * `MAX_BATCH_SIZE` in btc-vault (`crates/vaultd/src/rpc/server/vault_provider.rs:7`).\n * Callers must chunk requests larger than this.\n */\nexport const VP_BATCH_MAX_SIZE = 50;\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/**\n * JSON-RPC error codes returned by the vault provider.\n * Source: btc-vault `crates/vaultd/src/rpc/error.rs::RpcError::error_code`.\n */\nexport enum RpcErrorCode {\n PEGIN_NOT_FOUND = 4001,\n}\n"],"names":["JsonRpcError","code","message","source","data","JSON_RPC_ERROR_CODES","JSON_RPC_VERSION","DEFAULT_RETRY_ATTEMPTS","DEFAULT_RETRY_DELAY_MS","DEFAULT_MAX_RESPONSE_BYTES","UNCAPPED_TYPED_RESPONSE_METHODS","RETRYABLE_HTTP_STATUS_CODES","DEFAULT_RETRYABLE_METHODS","defaultRetryableFor","method","AUTH_EXPIRED_DATA_KIND","isAuthExpiredError","error","JsonRpcClient","config","__publicField","headers","token","params","signal","response","jsonResponse","responseText","readResponseTextWithLimit","rpcResponse","err","callerSignal","requestId","maxRetries","body","lastError","attempt","timeoutController","timeoutId","merged","mergeAbortSignals","delay","ms","resolve","reject","onAbort","a","b","controller","onAbortA","onAbortB","cleanup","maxBytes","contentLength","parsedContentLength","responseTooLargeError","reader","decoder","totalBytes","done","value","DaemonStatus","PRE_DEPOSITOR_SIGNATURES_STATES","POST_PAYOUT_SIGNATURE_STATUSES","VP_TRANSIENT_STATUSES","VP_TERMINAL_FAILURE_STATUSES","POST_WOTS_STATUSES","VP_BATCH_MAX_SIZE","RpcErrorCode"],"mappings":"iLA4FO,MAAMA,UAAqB,KAAM,CACtC,YACSC,EACPC,EAEOC,EAA6B,QAE7BC,EACP,CACA,MAAMF,CAAO,EAPN,KAAA,KAAAD,EAGA,KAAA,OAAAE,EAEA,KAAA,KAAAC,EAGP,KAAK,KAAO,cACd,CACF,CAEO,MAAMC,EAAuB,CAClC,QAAS,MACT,QAAS,OAET,cAAe,OAEf,kBAAmB,OAEnB,iBAAkB,OAElB,mBAAoB,MACtB,EAGMC,EAAmB,MAGnBC,EAAyB,EAGzBC,EAAyB,IAGzBC,EAA6B,EAAI,KAAO,KAMxCC,MAA2D,IAAI,CACnE,gDACF,CAAC,EAGKC,MAAuD,IAAI,CAC/D,IACA,IACA,IACA,IACA,IACA,GACF,CAAC,EAGKC,MAAqD,IAAI,CAC7D,+BACA,oCACA,qCACA,mDACF,CAAC,EAED,SAASC,EAAoBC,EAAyB,CACpD,OAAOF,EAA0B,IAAIE,CAAM,CAC7C,CAYO,MAAMC,EAAyB,eAEtC,SAASC,EAAmBC,EAAyB,CAEnD,GADI,EAAEA,aAAiBjB,IACnBiB,EAAM,SAAW,OAAQ,MAAO,GACpC,MAAMb,EAAOa,EAAM,KACnB,OAAIb,IAAS,MAAQ,OAAOA,GAAS,SAAiB,GACxCA,EAA4B,OAC1BW,CAClB,CAKO,MAAMG,CAAc,CAWzB,YAAYC,EAA6B,CAVjCC,EAAA,gBACAA,EAAA,gBACAA,EAAA,gBACAA,EAAA,iBAAY,GACZA,EAAA,gBACAA,EAAA,mBACAA,EAAA,yBACAA,EAAA,qBACAA,EAAA,sBAa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4BACF,CAAC,EAsRYG,EAAoB,GAU1B,IAAKC,GAAAA,IACVA,EAAAA,EAAA,gBAAkB,IAAA,EAAlB,kBADUA,IAAAA,GAAA,CAAA,CAAA"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babylonlabs-io/ts-sdk",
3
- "version": "0.45.0",
3
+ "version": "0.47.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1,2 +0,0 @@
1
- "use strict";const C=require("@bitcoin-js/tiny-secp256k1-asmjs"),E=require("./bitcoin-CHfKAhcI.cjs"),s=require("./BTCVaultRegistry.abi-JdeqLz4x.cjs"),l=require("./validation-u8W7Lp2x.cjs");function B(e){const o=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const t in e)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(o,t,r.get?r:{enumerable:!0,get:()=>e[t]})}}return o.default=e,Object.freeze(o)}const F=B(C),m=65535,d=1e4,f=4294967295,p=255;function u(e){if(!Number.isInteger(e)||e<0||e>f)throw new Error(`Invalid offchainParamsVersion from contract: must be a uint32, got ${e}`)}function b(e){const o=[];if(e.timelockAssert<=0n&&o.push(`timelockAssert must be positive, got ${e.timelockAssert}`),e.timelockAssert>BigInt(m)&&o.push(`timelockAssert ${e.timelockAssert} exceeds uint16 max (${m})`),e.timelockChallengeAssert<=0n&&o.push(`timelockChallengeAssert must be positive, got ${e.timelockChallengeAssert}`),e.tRefund<=0&&o.push(`tRefund must be positive, got ${e.tRefund}`),e.tStale<=0&&o.push(`tStale must be positive, got ${e.tStale}`),e.securityCouncilKeys.length===0&&o.push("securityCouncilKeys must not be empty"),e.councilQuorum<=0&&o.push(`councilQuorum must be positive, got ${e.councilQuorum}`),e.councilQuorum>e.securityCouncilKeys.length&&o.push(`councilQuorum (${e.councilQuorum}) exceeds securityCouncilKeys count (${e.securityCouncilKeys.length})`),e.feeRate<=0n&&o.push(`feeRate must be positive, got ${e.feeRate}`),e.minPeginFeeRate<=0n&&o.push(`minPeginFeeRate must be positive, got ${e.minPeginFeeRate}`),(!Number.isInteger(e.proverCircuitVersion)||e.proverCircuitVersion<0||e.proverCircuitVersion>m)&&o.push(`proverCircuitVersion must be a uint16, got ${e.proverCircuitVersion}`),(!Number.isInteger(e.minPrepeginDepth)||e.minPrepeginDepth<=0||e.minPrepeginDepth>f)&&o.push(`minPrepeginDepth must be a uint32 in [1, ${f}], got ${e.minPrepeginDepth}`),e.babeTotalInstances<=0&&o.push(`babeTotalInstances must be positive, got ${e.babeTotalInstances}`),e.babeInstancesToFinalize<=0&&o.push(`babeInstancesToFinalize must be positive, got ${e.babeInstancesToFinalize}`),e.babeInstancesToFinalize>e.babeTotalInstances&&o.push(`babeInstancesToFinalize (${e.babeInstancesToFinalize}) exceeds babeTotalInstances (${e.babeTotalInstances})`),(e.minVpCommissionBps<0||e.minVpCommissionBps>d)&&o.push(`minVpCommissionBps must be in [0, ${d}], got ${e.minVpCommissionBps}`),o.length>0)throw new Error(`Invalid offchain protocol parameters: ${o.join("; ")}`)}function I(e){const o=[];if(e.minimumPegInAmount<=0n&&o.push(`minimumPegInAmount must be positive, got ${e.minimumPegInAmount}`),e.maxPegInAmount<e.minimumPegInAmount&&o.push(`maxPegInAmount (${e.maxPegInAmount}) must be >= minimumPegInAmount (${e.minimumPegInAmount})`),e.pegInAckTimeout<=0n&&o.push(`pegInAckTimeout must be positive, got ${e.pegInAckTimeout}`),e.pegInActivationTimeout<=0n&&o.push(`pegInActivationTimeout must be positive, got ${e.pegInActivationTimeout}`),(!Number.isInteger(e.maxHtlcOutputCount)||e.maxHtlcOutputCount<=0||e.maxHtlcOutputCount>p)&&o.push(`maxHtlcOutputCount must be an integer in [1, ${p}], got ${e.maxHtlcOutputCount}`),(typeof e.expiredPegInGraceBlocks!="bigint"||e.expiredPegInGraceBlocks<=0n)&&o.push(`expiredPegInGraceBlocks must be a positive bigint, got ${e.expiredPegInGraceBlocks}`),o.length>0)throw new Error(`Invalid TBV protocol parameters: ${o.join("; ")}`)}function k(e){if(I(e),b(e.offchainParams),!Number.isInteger(e.offchainParamsVersion)||e.offchainParamsVersion<0||e.offchainParamsVersion>f)throw new Error(`Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${e.offchainParamsVersion}`)}const P=9999;class S{constructor(o,t){this.publicClient=o,this.contractAddress=t}async getVaultProviderBtcPubKey(o){const r=(await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getVaultProviderBTCKey",args:[o]})).toLowerCase();if(!/^0x[0-9a-f]{64}$/.test(r))throw new Error(`getVaultProviderBTCKey returned an unexpected value (vp=${o}, length ${r.length}, prefix "${r.slice(0,2)}")`);const i=r.slice(2);if(!F.isXOnlyPoint(E.hexToUint8Array(i)))throw new Error(`getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${o})`);return i}async getVaultBasicInfo(o){const t=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[o]});return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}async getVaultProtocolInfo(o){const t=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[o]}),r=Number(t.offchainParamsVersion);return u(r),{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:r,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps,claimExpiredUntil:t.claimExpiredUntil,vaultCoreVersion:t.vaultCoreVersion}}async getProtocolInfoBatch(o){return o.length===0?[]:(await this.publicClient.multicall({contracts:o.map(r=>({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[r]})),allowFailure:!1})).map((r,i)=>{const n=r;if(!n.depositorSignedPeginTx||n.depositorSignedPeginTx==="0x")throw new Error(`Vault ${o[i]} not found on-chain or has no pegin transaction`);const a=Number(n.offchainParamsVersion);return u(a),{depositorSignedPeginTx:n.depositorSignedPeginTx,universalChallengersVersion:n.universalChallengersVersion,appVaultKeepersVersion:n.appVaultKeepersVersion,offchainParamsVersion:a,verifiedAt:n.verifiedAt,depositorWotsPkHash:n.depositorWotsPkHash,hashlock:n.hashlock,htlcVout:n.htlcVout,depositorPopSignature:n.depositorPopSignature,prePeginTxHash:n.prePeginTxHash,vaultProviderCommissionBps:n.vaultProviderCommissionBps,claimExpiredUntil:n.claimExpiredUntil,vaultCoreVersion:n.vaultCoreVersion}})}async getPegInFee(o){return await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getPegInFee",args:[o]})}async getVaultProviderCommission(o){const t=await this.publicClient.readContract({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getVaultProviderCommission",args:[o]});if(!Number.isInteger(t)||t<0||t>P)throw new Error(`getVaultProviderCommission returned ${t} bps for ${o}, outside the protocol range [0, ${P}]`);return t}async getVaultData(o){const[t,r]=await Promise.all([this.getVaultBasicInfo(o),this.getVaultProtocolInfo(o)]);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${o} not found on-chain or has no pegin transaction`);return{basic:t,protocol:r}}async getOffchainParamsVersionsByVaultIds(o){return o.length===0?[]:(await this.publicClient.multicall({contracts:o.map(r=>({address:this.contractAddress,abi:s.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[r]})),allowFailure:!1})).map(r=>{const i=r;if(!i.depositorSignedPeginTx||i.depositorSignedPeginTx==="0x")throw new Error("Vault not found on-chain or has no pegin transaction while reading offchain params version");const n=Number(i.offchainParamsVersion);return u(n),n})}}const O=21e6*1e8,w=3e4;async function h(e,o){const t=new AbortController,r=setTimeout(()=>t.abort(),w),i=[t.signal,o==null?void 0:o.signal].filter(Boolean);try{return await fetch(e,{...o,signal:AbortSignal.any(i)})}catch(n){throw clearTimeout(r),n!=null&&typeof n=="object"&&"name"in n&&n.name==="AbortError"?new Error(`Mempool API request timed out after ${w}ms: ${e}`):n}}const $=1e4;function T(e){return Number.isInteger(e)&&e>0&&e<=O}function N(e){return Number.isInteger(e)&&e>0&&e<=$}function v(e,o){return!Number.isInteger(e)||e<0?!1:o===void 0||e<o}function g(e){if(!l.TXID_RE.test(e))throw new Error(`Invalid transaction ID format: ${e}`)}function V(e){if(!l.BITCOIN_ADDRESS_RE.test(e))throw new Error(`Invalid Bitcoin address format: ${e}`)}function y(e,o){if(!l.HEX_RE.test(e))throw new Error(`Invalid scriptPubKey: not valid hex for ${o}`);if(!l.KNOWN_SCRIPT_PREFIXES.some(r=>e.toLowerCase().startsWith(r)))throw new Error(`Unrecognized scriptPubKey type for ${o}: prefix ${e.slice(0,6)} does not match any known Bitcoin script type`)}const x={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function c(e,o){try{const t=await h(e,o);if(!t.ok){const i=await t.text();throw new Error(`Mempool API error (${t.status}): ${i||t.statusText}`)}const r=t.headers.get("content-type");return r!=null&&r.includes("application/json")?await t.json():await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to fetch from mempool API: ${t.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function R(e,o){try{const t=await h(`${o}/tx`,{method:"POST",body:e,headers:{"Content-Type":"text/plain"}});if(!t.ok){const i=await t.text();let n;try{n=JSON.parse(i).message}catch{n=i}throw new Error(n||`Failed to broadcast transaction: ${t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to broadcast BTC transaction: ${t.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function A(e,o){return g(e),c(`${o}/tx/${e}`)}async function U(e){const o=await c(`${e}/blocks/tip/height`),t=o.trim();if(!/^\d+$/.test(t))throw new Error(`Mempool API returned an invalid block tip height: "${o}"`);return Number.parseInt(t,10)}async function _(e,o){g(e);try{const t=await h(`${o}/tx/${e}/hex`);if(!t.ok){const r=await t.text();throw new Error(`Mempool API error (${t.status}): ${r||t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to get transaction hex for ${e}: ${t.message}`):new Error(`Failed to get transaction hex for ${e}: Unknown error`)}}async function M(e,o,t){g(e);const r=await A(e,t);if(!v(o,r.vout.length))throw new Error(`Invalid vout ${o} for transaction ${e} (has ${r.vout.length} outputs)`);const i=r.vout[o];if(!T(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${e}:${o}`);return y(i.scriptpubkey,`${e}:${o}`),{txid:e,vout:o,value:i.value,scriptPubKey:i.scriptpubkey}}async function H(e,o){V(e);try{const t=await c(`${o}/address/${e}/utxo`),r=await c(`${o}/v1/validate-address/${e}`);if(!r.isvalid)throw new Error(`Invalid Bitcoin address: ${e}. Mempool API validation failed.`);y(r.scriptPubKey,e);for(const n of t){if(g(n.txid),!v(n.vout))throw new Error(`Invalid vout ${n.vout} for ${n.txid}`);if(!T(n.value))throw new Error(`Invalid UTXO value ${n.value} for ${n.txid}:${n.vout}`)}return t.sort((n,a)=>a.value-n.value).map(n=>({txid:n.txid,vout:n.vout,value:n.value,scriptPubKey:r.scriptPubKey,confirmed:n.status.confirmed}))}catch(t){throw t instanceof Error?new Error(`Failed to get UTXOs for address ${e}: ${t.message}`):new Error(`Failed to get UTXOs for address ${e}: Unknown error`)}}function K(e){return x[e]}async function X(e,o){return V(e),c(`${o}/address/${e}/txs`)}async function D(e){const o=await h(`${e}/v1/fees/recommended`);if(!o.ok)throw new Error(`Failed to fetch network fees: ${o.status} ${o.statusText}`);const t=await o.json(),r=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const i of r)if(!N(t[i]))throw new Error(`Invalid fee rate ${i}=${t[i]} from mempool API: expected a positive number ≤ ${$}`);if(t.minimumFee>t.economyFee||t.economyFee>t.hourFee||t.hourFee>t.halfHourFee||t.halfHourFee>t.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${t.minimumFee}) <= economyFee (${t.economyFee}) <= hourFee (${t.hourFee}) <= halfHourFee (${t.halfHourFee}) <= fastestFee (${t.fastestFee}).`);return t}exports.MEMPOOL_API_URLS=x;exports.ViemVaultRegistryReader=S;exports.assertValidOffchainParamsVersion=u;exports.getAddressTxs=X;exports.getAddressUtxos=H;exports.getMempoolApiUrl=K;exports.getNetworkFees=D;exports.getTipHeight=U;exports.getTxHex=_;exports.getTxInfo=A;exports.getUtxoInfo=M;exports.pushTx=R;exports.validateOffchainParams=b;exports.validatePegInConfiguration=k;exports.validateTBVProtocolParams=I;
2
- //# sourceMappingURL=mempoolApi-DcHws8jJ.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"mempoolApi-DcHws8jJ.cjs","sources":["../src/tbv/core/clients/eth/protocol-params-validation.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts","../src/tbv/core/clients/mempool/mempoolApi.ts"],"sourcesContent":["/**\n * Validation for protocol parameters fetched from the ProtocolParams contract.\n *\n * These values feed Bitcoin script construction and deposit validation.\n * Invalid params must be caught before they reach transaction-building code,\n * since errors after wallet signing prompts are unrecoverable.\n *\n * The {@link ViemProtocolParamsReader} runs these on every read; consumers\n * implementing their own reader against the same `ProtocolParamsReader`\n * interface should call them too.\n */\n\nimport type {\n PegInConfiguration,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/** Maximum valid value for basis points (100%) */\nconst MAX_BASIS_POINTS = 10000;\n\n/** Maximum value for a Solidity uint32. */\nconst UINT32_MAX = 4_294_967_295;\n\n/** Maximum valid value for a uint8 (e.g. maxHtlcOutputCount). */\nconst UINT8_MAX = 255;\n\n/**\n * Validate an `offchainParamsVersion` value sourced from a contract read.\n * `Number()` on a malformed payload yields `NaN` or a non-integer; both\n * silently break consumers that loop `1..version` or use the value as a\n * map key. Used by reader entry points that surface the version to JS.\n */\nexport function assertValidOffchainParamsVersion(version: number): void {\n if (\n !Number.isInteger(version) ||\n version < 0 ||\n version > UINT32_MAX\n ) {\n throw new Error(\n `Invalid offchainParamsVersion from contract: must be a uint32, got ${version}`,\n );\n }\n}\n\n/**\n * Validate offchain params consistency and bounds.\n * @throws Error on invalid values to prevent constructing invalid Bitcoin scripts.\n */\nexport function validateOffchainParams(params: VersionedOffchainParams): void {\n const errors: string[] = [];\n\n if (params.timelockAssert <= 0n) {\n errors.push(\n `timelockAssert must be positive, got ${params.timelockAssert}`,\n );\n }\n if (params.timelockAssert > BigInt(UINT16_MAX)) {\n errors.push(\n `timelockAssert ${params.timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n\n if (params.timelockChallengeAssert <= 0n) {\n errors.push(\n `timelockChallengeAssert must be positive, got ${params.timelockChallengeAssert}`,\n );\n }\n\n if (params.tRefund <= 0) {\n errors.push(`tRefund must be positive, got ${params.tRefund}`);\n }\n\n if (params.tStale <= 0) {\n errors.push(`tStale must be positive, got ${params.tStale}`);\n }\n\n if (params.securityCouncilKeys.length === 0) {\n errors.push(\"securityCouncilKeys must not be empty\");\n }\n\n if (params.councilQuorum <= 0) {\n errors.push(`councilQuorum must be positive, got ${params.councilQuorum}`);\n }\n if (params.councilQuorum > params.securityCouncilKeys.length) {\n errors.push(\n `councilQuorum (${params.councilQuorum}) exceeds securityCouncilKeys count (${params.securityCouncilKeys.length})`,\n );\n }\n\n if (params.feeRate <= 0n) {\n errors.push(`feeRate must be positive, got ${params.feeRate}`);\n }\n\n if (params.minPeginFeeRate <= 0n) {\n errors.push(\n `minPeginFeeRate must be positive, got ${params.minPeginFeeRate}`,\n );\n }\n\n if (\n !Number.isInteger(params.proverCircuitVersion) ||\n params.proverCircuitVersion < 0 ||\n params.proverCircuitVersion > UINT16_MAX\n ) {\n errors.push(\n `proverCircuitVersion must be a uint16, got ${params.proverCircuitVersion}`,\n );\n }\n\n if (\n !Number.isInteger(params.minPrepeginDepth) ||\n params.minPrepeginDepth <= 0 ||\n params.minPrepeginDepth > UINT32_MAX\n ) {\n errors.push(\n `minPrepeginDepth must be a uint32 in [1, ${UINT32_MAX}], got ${params.minPrepeginDepth}`,\n );\n }\n\n if (params.babeTotalInstances <= 0) {\n errors.push(\n `babeTotalInstances must be positive, got ${params.babeTotalInstances}`,\n );\n }\n if (params.babeInstancesToFinalize <= 0) {\n errors.push(\n `babeInstancesToFinalize must be positive, got ${params.babeInstancesToFinalize}`,\n );\n }\n if (params.babeInstancesToFinalize > params.babeTotalInstances) {\n errors.push(\n `babeInstancesToFinalize (${params.babeInstancesToFinalize}) exceeds babeTotalInstances (${params.babeTotalInstances})`,\n );\n }\n\n if (\n params.minVpCommissionBps < 0 ||\n params.minVpCommissionBps > MAX_BASIS_POINTS\n ) {\n errors.push(\n `minVpCommissionBps must be in [0, ${MAX_BASIS_POINTS}], got ${params.minVpCommissionBps}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(\n `Invalid offchain protocol parameters: ${errors.join(\"; \")}`,\n );\n }\n}\n\n/**\n * Validate TBV protocol params returned from the contract.\n * @throws Error on invalid amounts or out-of-range bounded fields.\n */\nexport function validateTBVProtocolParams(params: TBVProtocolParams): void {\n const errors: string[] = [];\n\n if (params.minimumPegInAmount <= 0n) {\n errors.push(\n `minimumPegInAmount must be positive, got ${params.minimumPegInAmount}`,\n );\n }\n\n if (params.maxPegInAmount < params.minimumPegInAmount) {\n errors.push(\n `maxPegInAmount (${params.maxPegInAmount}) must be >= minimumPegInAmount (${params.minimumPegInAmount})`,\n );\n }\n\n if (params.pegInAckTimeout <= 0n) {\n errors.push(\n `pegInAckTimeout must be positive, got ${params.pegInAckTimeout}`,\n );\n }\n\n if (params.pegInActivationTimeout <= 0n) {\n errors.push(\n `pegInActivationTimeout must be positive, got ${params.pegInActivationTimeout}`,\n );\n }\n\n if (\n !Number.isInteger(params.maxHtlcOutputCount) ||\n params.maxHtlcOutputCount <= 0 ||\n params.maxHtlcOutputCount > UINT8_MAX\n ) {\n errors.push(\n `maxHtlcOutputCount must be an integer in [1, ${UINT8_MAX}], got ${params.maxHtlcOutputCount}`,\n );\n }\n\n if (\n typeof params.expiredPegInGraceBlocks !== \"bigint\" ||\n params.expiredPegInGraceBlocks <= 0n\n ) {\n errors.push(\n `expiredPegInGraceBlocks must be a positive bigint, got ${params.expiredPegInGraceBlocks}`,\n );\n }\n\n if (errors.length > 0) {\n throw new Error(`Invalid TBV protocol parameters: ${errors.join(\"; \")}`);\n }\n}\n\n/**\n * Validate the full peg-in configuration after assembly.\n * Checks both TBV params and offchain params consistency, and the\n * top-level `offchainParamsVersion` (which originates from a separate\n * multicall result and so must be range-checked alongside the params it\n * names).\n */\nexport function validatePegInConfiguration(config: PegInConfiguration): void {\n validateTBVProtocolParams(config);\n validateOffchainParams(config.offchainParams);\n\n if (\n !Number.isInteger(config.offchainParamsVersion) ||\n config.offchainParamsVersion < 0 ||\n config.offchainParamsVersion > UINT32_MAX\n ) {\n throw new Error(\n `Invalid peg-in configuration: offchainParamsVersion must be a uint32, got ${config.offchainParamsVersion}`,\n );\n }\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport * as ecc from \"@bitcoin-js/tiny-secp256k1-asmjs\";\nimport type { Abi, Address, Hex, PublicClient } from \"viem\";\n\nimport { hexToUint8Array } from \"../../primitives/utils/bitcoin\";\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport { assertValidOffchainParamsVersion } from \"./protocol-params-validation\";\nimport type {\n OnChainBtcPubkey,\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Inclusive upper bound the BTCVaultRegistry contract enforces on a vault\n * provider's commission (the contract check is `< 10000`).\n */\nconst MAX_VP_COMMISSION_BPS = 9999;\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n /**\n * Read the VP's persistent x-only BTC pubkey from the on-chain\n * registry. Validates length, hex form, and secp256k1 curve\n * membership before minting the brand. Returns 64-char lowercase\n * hex without the `0x` prefix.\n */\n async getVaultProviderBtcPubKey(\n vpAddress: Address,\n ): Promise<OnChainBtcPubkey> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderBTCKey\",\n args: [vpAddress],\n })) as Hex;\n const lowered = result.toLowerCase();\n if (!/^0x[0-9a-f]{64}$/.test(lowered)) {\n throw new Error(\n `getVaultProviderBTCKey returned an unexpected value (vp=${vpAddress}, length ${lowered.length}, prefix \"${lowered.slice(0, 2)}\")`,\n );\n }\n const stripped = lowered.slice(2);\n if (!ecc.isXOnlyPoint(hexToUint8Array(stripped))) {\n throw new Error(\n `getVaultProviderBTCKey returned a value that is not on the secp256k1 curve (vp=${vpAddress})`,\n );\n }\n return stripped as OnChainBtcPubkey;\n }\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as {\n depositor: Address;\n depositorBtcPubKey: Hex;\n amount: bigint;\n vaultProvider: Address;\n status: number;\n applicationEntryPoint: Address;\n createdAt: bigint;\n };\n\n return {\n depositor: result.depositor,\n depositorBtcPubKey: result.depositorBtcPubKey,\n amount: result.amount,\n vaultProvider: result.vaultProvider,\n status: result.status,\n applicationEntryPoint: result.applicationEntryPoint,\n createdAt: result.createdAt,\n };\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n };\n\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n }\n\n async getProtocolInfoBatch(\n vaultIds: readonly Hex[],\n ): Promise<VaultProtocolInfo[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info, i) => {\n const result = info as unknown as {\n depositorSignedPeginTx: Hex;\n universalChallengersVersion: number;\n appVaultKeepersVersion: number;\n offchainParamsVersion: number;\n verifiedAt: bigint;\n depositorWotsPkHash: Hex;\n hashlock: Hex;\n htlcVout: number;\n depositorPopSignature: Hex;\n prePeginTxHash: Hex;\n vaultProviderCommissionBps: number;\n claimExpiredUntil: bigint;\n vaultCoreVersion: number;\n };\n if (\n !result.depositorSignedPeginTx ||\n result.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultIds[i]} not found on-chain or has no pegin transaction`,\n );\n }\n const offchainParamsVersion = Number(result.offchainParamsVersion);\n assertValidOffchainParamsVersion(offchainParamsVersion);\n return {\n depositorSignedPeginTx: result.depositorSignedPeginTx,\n universalChallengersVersion: result.universalChallengersVersion,\n appVaultKeepersVersion: result.appVaultKeepersVersion,\n offchainParamsVersion,\n verifiedAt: result.verifiedAt,\n depositorWotsPkHash: result.depositorWotsPkHash,\n hashlock: result.hashlock,\n htlcVout: result.htlcVout,\n depositorPopSignature: result.depositorPopSignature,\n prePeginTxHash: result.prePeginTxHash,\n vaultProviderCommissionBps: result.vaultProviderCommissionBps,\n claimExpiredUntil: result.claimExpiredUntil,\n vaultCoreVersion: result.vaultCoreVersion,\n };\n });\n }\n\n /**\n * Read the protocol pegin fee (in wei) for a given vault provider.\n * Mirrors the `getPegInFee(address)` view on BTCVaultRegistry.\n */\n async getPegInFee(vaultProvider: Address): Promise<bigint> {\n return (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getPegInFee\",\n args: [vaultProvider],\n })) as bigint;\n }\n\n /**\n * Read a vault provider's current commission in basis points from\n * BTCVaultRegistry. The contract enforces `commissionBps < 10000`, so the\n * legitimate range is `[0, 9999]`; anything outside indicates a wrong\n * contract address or ABI drift and is surfaced as an error rather than\n * trusted.\n */\n async getVaultProviderCommission(vaultProvider: Address): Promise<number> {\n // viem infers `number` from the `uint16` return in the `as const` ABI.\n const bps = await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getVaultProviderCommission\",\n args: [vaultProvider],\n });\n\n if (!Number.isInteger(bps) || bps < 0 || bps > MAX_VP_COMMISSION_BPS) {\n throw new Error(\n `getVaultProviderCommission returned ${bps} bps for ${vaultProvider}, ` +\n `outside the protocol range [0, ${MAX_VP_COMMISSION_BPS}]`,\n );\n }\n\n return bps;\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n const [basic, protocol] = await Promise.all([\n this.getVaultBasicInfo(vaultId),\n this.getVaultProtocolInfo(vaultId),\n ]);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n\n /**\n * Read `offchainParamsVersion` for many vaults in a single multicall.\n * Reads only `getBtcVaultProtocolInfo` (one read per vault), so an N-vault\n * batch costs one RPC round-trip instead of 2N parallel `eth_call`s.\n */\n async getOffchainParamsVersionsByVaultIds(\n vaultIds: readonly Hex[],\n ): Promise<number[]> {\n if (vaultIds.length === 0) return [];\n\n const results = await this.publicClient.multicall({\n contracts: vaultIds.map((vaultId) => ({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI as Abi,\n functionName: \"getBtcVaultProtocolInfo\" as const,\n args: [vaultId] as const,\n })),\n allowFailure: false,\n });\n\n return results.map((info) => {\n const protocolInfo = info as unknown as VaultProtocolInfo;\n if (\n !protocolInfo.depositorSignedPeginTx ||\n protocolInfo.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n \"Vault not found on-chain or has no pegin transaction while reading offchain params version\",\n );\n }\n const version = Number(protocolInfo.offchainParamsVersion);\n assertValidOffchainParamsVersion(version);\n return version;\n });\n }\n}\n","/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport {\n BITCOIN_ADDRESS_RE,\n HEX_RE,\n KNOWN_SCRIPT_PREFIXES,\n TXID_RE,\n} from \"../../utils/validation\";\n\nimport type { MempoolUTXO, NetworkFees, TxInfo, UtxoInfo } from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n\nfunction assertValidTxid(txid: string): void {\n if (!TXID_RE.test(txid)) {\n throw new Error(`Invalid transaction ID format: ${txid}`);\n }\n}\n\nfunction assertValidAddress(address: string): void {\n if (!BITCOIN_ADDRESS_RE.test(address)) {\n throw new Error(`Invalid Bitcoin address format: ${address}`);\n }\n}\n\nfunction assertValidScriptPubKey(scriptPubKey: string, context: string): void {\n if (!HEX_RE.test(scriptPubKey)) {\n throw new Error(\n `Invalid scriptPubKey: not valid hex for ${context}`,\n );\n }\n const matchesKnownType = KNOWN_SCRIPT_PREFIXES.some((prefix) =>\n scriptPubKey.toLowerCase().startsWith(prefix),\n );\n if (!matchesKnownType) {\n throw new Error(\n `Unrecognized scriptPubKey type for ${context}: ` +\n `prefix ${scriptPubKey.slice(0, 6)} does not match any known Bitcoin script type`,\n );\n }\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n assertValidTxid(txid);\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the current block tip height.\n *\n * Source: mempool.space API — `GET /api/blocks/tip/height` returns the height\n * of the most recent block as a plain-text integer.\n *\n * @param apiUrl - Mempool API base URL\n * @returns The height of the most recent block\n * @throws Error if the response is not a whole number\n */\nexport async function getTipHeight(apiUrl: string): Promise<number> {\n const raw = await fetchApi<string>(`${apiUrl}/blocks/tip/height`);\n const trimmed = raw.trim();\n if (!/^\\d+$/.test(trimmed)) {\n throw new Error(\n `Mempool API returned an invalid block tip height: \"${raw}\"`,\n );\n }\n return Number.parseInt(trimmed, 10);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n assertValidTxid(txid);\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n assertValidTxid(txid);\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n assertValidScriptPubKey(output.scriptpubkey, `${txid}:${vout}`);\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n assertValidAddress(address);\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n assertValidScriptPubKey(addressInfo.scriptPubKey, address);\n\n // Validate UTXO fields from the listing endpoint.\n // Per-UTXO cross-verification against /tx/{txid} is intentionally NOT done\n // here — it would be expensive (N API calls) and redundant: the broadcast\n // path already verifies each selected input via getUtxoInfo before signing.\n // Both endpoints come from the same mempool API, so cross-checking one\n // against the other on the same server does not add real security.\n for (const utxo of utxos) {\n assertValidTxid(utxo.txid);\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n assertValidAddress(address);\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n"],"names":["UINT16_MAX","MAX_BASIS_POINTS","UINT32_MAX","UINT8_MAX","assertValidOffchainParamsVersion","version","validateOffchainParams","params","errors","validateTBVProtocolParams","validatePegInConfiguration","config","MAX_VP_COMMISSION_BPS","ViemVaultRegistryReader","publicClient","contractAddress","vpAddress","lowered","BTCVaultRegistryABI","stripped","ecc","hexToUint8Array","vaultId","result","offchainParamsVersion","vaultIds","info","vaultProvider","bps","basic","protocol","protocolInfo","MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","assertValidTxid","txid","TXID_RE","assertValidAddress","address","BITCOIN_ADDRESS_RE","assertValidScriptPubKey","scriptPubKey","context","HEX_RE","KNOWN_SCRIPT_PREFIXES","prefix","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","getTxInfo","getTipHeight","raw","trimmed","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field"],"mappings":"udAsBMA,EAAa,MAGbC,EAAmB,IAGnBC,EAAa,WAGbC,EAAY,IAQX,SAASC,EAAiCC,EAAuB,CACtE,GACE,CAAC,OAAO,UAAUA,CAAO,GACzBA,EAAU,GACVA,EAAUH,EAEV,MAAM,IAAI,MACR,sEAAsEG,CAAO,EAAA,CAGnF,CAMO,SAASC,EAAuBC,EAAuC,CAC5E,MAAMC,EAAmB,CAAA,EA+FzB,GA7FID,EAAO,gBAAkB,IAC3BC,EAAO,KACL,wCAAwCD,EAAO,cAAc,EAAA,EAG7DA,EAAO,eAAiB,OAAOP,CAAU,GAC3CQ,EAAO,KACL,kBAAkBD,EAAO,cAAc,wBAAwBP,CAAU,GAAA,EAIzEO,EAAO,yBAA2B,IACpCC,EAAO,KACL,iDAAiDD,EAAO,uBAAuB,EAAA,EAI/EA,EAAO,SAAW,GACpBC,EAAO,KAAK,iCAAiCD,EAAO,OAAO,EAAE,EAG3DA,EAAO,QAAU,GACnBC,EAAO,KAAK,gCAAgCD,EAAO,MAAM,EAAE,EAGzDA,EAAO,oBAAoB,SAAW,GACxCC,EAAO,KAAK,uCAAuC,EAGjDD,EAAO,eAAiB,GAC1BC,EAAO,KAAK,uCAAuCD,EAAO,aAAa,EA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