@babylonlabs-io/ts-sdk 0.32.0 → 0.33.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 (83) hide show
  1. package/dist/{PeginManager-DUR1BTKM.js → PeginManager-BMrWtTji.js} +136 -124
  2. package/dist/PeginManager-BMrWtTji.js.map +1 -0
  3. package/dist/PeginManager-DUMF84XK.cjs +2 -0
  4. package/dist/PeginManager-DUMF84XK.cjs.map +1 -0
  5. package/dist/{buildAndBroadcastRefund-CIHhUmRv.cjs → buildAndBroadcastRefund-6pR681fI.cjs} +2 -2
  6. package/dist/buildAndBroadcastRefund-6pR681fI.cjs.map +1 -0
  7. package/dist/{buildAndBroadcastRefund-DwrX_IBf.js → buildAndBroadcastRefund-Ba56IKL7.js} +38 -38
  8. package/dist/buildAndBroadcastRefund-Ba56IKL7.js.map +1 -0
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.js +74 -70
  11. package/dist/tbv/core/clients/eth/index.d.ts +1 -1
  12. package/dist/tbv/core/clients/eth/index.d.ts.map +1 -1
  13. package/dist/tbv/core/clients/eth/types.d.ts +13 -0
  14. package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
  15. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts +8 -1
  16. package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
  17. package/dist/tbv/core/clients/index.cjs +1 -1
  18. package/dist/tbv/core/clients/index.js +30 -27
  19. package/dist/tbv/core/clients/vault-provider/api.d.ts +13 -2
  20. package/dist/tbv/core/clients/vault-provider/api.d.ts.map +1 -1
  21. package/dist/tbv/core/clients/vault-provider/auth/__tests__/createAuthenticatedVpClient.test.d.ts +11 -0
  22. package/dist/tbv/core/clients/vault-provider/auth/__tests__/createAuthenticatedVpClient.test.d.ts.map +1 -0
  23. package/dist/tbv/core/clients/vault-provider/auth/__tests__/tokenRegistry.test.d.ts +2 -0
  24. package/dist/tbv/core/clients/vault-provider/auth/__tests__/tokenRegistry.test.d.ts.map +1 -0
  25. package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts +16 -0
  26. package/dist/tbv/core/clients/vault-provider/auth/createAuthenticatedVpClient.d.ts.map +1 -0
  27. package/dist/tbv/core/clients/vault-provider/auth/gatedMethods.d.ts +10 -0
  28. package/dist/tbv/core/clients/vault-provider/auth/gatedMethods.d.ts.map +1 -0
  29. package/dist/tbv/core/clients/vault-provider/auth/index.d.ts +5 -2
  30. package/dist/tbv/core/clients/vault-provider/auth/index.d.ts.map +1 -1
  31. package/dist/tbv/core/clients/vault-provider/auth/innerTokenClient.d.ts +4 -0
  32. package/dist/tbv/core/clients/vault-provider/auth/innerTokenClient.d.ts.map +1 -0
  33. package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts +11 -0
  34. package/dist/tbv/core/clients/vault-provider/auth/primeVpAuth.d.ts.map +1 -0
  35. package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts +18 -23
  36. package/dist/tbv/core/clients/vault-provider/auth/tokenProvider.d.ts.map +1 -1
  37. package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts +48 -0
  38. package/dist/tbv/core/clients/vault-provider/auth/tokenRegistry.d.ts.map +1 -0
  39. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +8 -12
  40. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -1
  41. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +14 -0
  42. package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
  43. package/dist/tbv/core/index.cjs +1 -1
  44. package/dist/tbv/core/index.js +65 -61
  45. package/dist/tbv/core/managers/index.d.ts +1 -1
  46. package/dist/tbv/core/services/deposit/__tests__/runDepositorPresignFlow.test.d.ts +2 -0
  47. package/dist/tbv/core/services/deposit/__tests__/runDepositorPresignFlow.test.d.ts.map +1 -0
  48. package/dist/tbv/core/services/deposit/index.d.ts +2 -2
  49. package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
  50. package/dist/tbv/core/services/deposit/{signAndSubmitPayouts.d.ts → runDepositorPresignFlow.d.ts} +3 -3
  51. package/dist/tbv/core/services/deposit/runDepositorPresignFlow.d.ts.map +1 -0
  52. package/dist/tbv/core/services/index.cjs +1 -1
  53. package/dist/tbv/core/services/index.js +11 -11
  54. package/dist/tbv/core/vault-secrets/__tests__/parseFundingOutpoints.test.d.ts +2 -0
  55. package/dist/tbv/core/vault-secrets/__tests__/parseFundingOutpoints.test.d.ts.map +1 -0
  56. package/dist/tbv/core/vault-secrets/index.d.ts +1 -0
  57. package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
  58. package/dist/tbv/core/vault-secrets/parseFundingOutpoints.d.ts +3 -0
  59. package/dist/tbv/core/vault-secrets/parseFundingOutpoints.d.ts.map +1 -0
  60. package/dist/tbv/index.cjs +1 -1
  61. package/dist/tbv/index.js +65 -61
  62. package/dist/{types-jmEyzzhY.cjs → types-C2IUB0Jd.cjs} +2 -2
  63. package/dist/types-C2IUB0Jd.cjs.map +1 -0
  64. package/dist/{types-CnG3JsRs.js → types-D1o_3Q__.js} +20 -9
  65. package/dist/types-D1o_3Q__.js.map +1 -0
  66. package/dist/{vault-registry-reader-CG6bea1S.js → vault-registry-reader-BeIEh62N.js} +436 -292
  67. package/dist/vault-registry-reader-BeIEh62N.js.map +1 -0
  68. package/dist/vault-registry-reader-DdUgC5IF.cjs +2 -0
  69. package/dist/vault-registry-reader-DdUgC5IF.cjs.map +1 -0
  70. package/package.json +1 -1
  71. package/dist/PeginManager-CTRPJo8m.cjs +0 -2
  72. package/dist/PeginManager-CTRPJo8m.cjs.map +0 -1
  73. package/dist/PeginManager-DUR1BTKM.js.map +0 -1
  74. package/dist/buildAndBroadcastRefund-CIHhUmRv.cjs.map +0 -1
  75. package/dist/buildAndBroadcastRefund-DwrX_IBf.js.map +0 -1
  76. package/dist/tbv/core/services/deposit/__tests__/signAndSubmitPayouts.test.d.ts +0 -2
  77. package/dist/tbv/core/services/deposit/__tests__/signAndSubmitPayouts.test.d.ts.map +0 -1
  78. package/dist/tbv/core/services/deposit/signAndSubmitPayouts.d.ts.map +0 -1
  79. package/dist/types-CnG3JsRs.js.map +0 -1
  80. package/dist/types-jmEyzzhY.cjs.map +0 -1
  81. package/dist/vault-registry-reader-BBS1_AON.cjs +0 -2
  82. package/dist/vault-registry-reader-BBS1_AON.cjs.map +0 -1
  83. package/dist/vault-registry-reader-CG6bea1S.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"types-CnG3JsRs.js","sources":["../src/tbv/core/contracts/abis/BTCVaultRegistry.abi.ts","../src/tbv/core/clients/vault-provider/json-rpc-client.ts","../src/tbv/core/clients/vault-provider/types.ts"],"sourcesContent":["/**\n * BTCVaultRegistry Contract ABI\n *\n * Minimal ABI containing only the functions needed by the SDK.\n * Full ABI is available in the vault service package.\n *\n * @module contracts/abis/BTCVaultRegistry\n */\n\n/**\n * Minimal ABI for BTCVaultRegistry contract.\n * Contains submitPeginRequest, submitPeginRequestBatch, activateVaultWithSecret, getPegInFee, and getBtcVaultBasicInfo.\n */\nexport const BTCVaultRegistryABI = [\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"referralCode\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequestBatch\",\n inputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n {\n name: \"requests\",\n type: \"tuple[]\",\n internalType: \"struct IBTCVaultRegistry.BatchPeginRequest[]\",\n components: [\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"btcPopSignature\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"unsignedPrePeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorSignedPeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"hashlock\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"htlcVout\", type: \"uint8\", internalType: \"uint8\" },\n { name: \"referralCode\", type: \"uint32\", internalType: \"uint32\" },\n { name: \"depositorPayoutBtcAddress\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorWotsPkHash\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n },\n ],\n outputs: [\n { name: \"vaultIds\", type: \"bytes32[]\", internalType: \"bytes32[]\" },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"activateVaultWithSecret\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"s\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"activationMetadata\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getPegInFee\",\n inputs: [\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"totalFee\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getBtcVaultBasicInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"vBasic\",\n type: \"tuple\",\n internalType: \"struct BTCVaultTypes.BTCVaultBasicInfo\",\n components: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"status\",\n type: \"uint8\",\n internalType: \"enum IBTCVaultRegistry.BTCVaultStatus\",\n },\n {\n name: \"applicationEntryPoint\",\n type: \"address\",\n internalType: \"address\",\n },\n { name: \"createdAt\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"error\",\n name: \"InvalidPeginFee\",\n inputs: [\n {\n name: \"provided\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"required\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n },\n {\n type: \"error\",\n name: \"InvalidSecret\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"ActivationDeadlineExpired\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"DuplicateHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"CapExceeded\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidOutputIndex\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"PeginSignaturesIncomplete\",\n inputs: [],\n },\n {\n type: \"function\",\n name: \"getBtcVaultProtocolInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"vProtocol\",\n type: \"tuple\",\n internalType:\n \"struct BTCVaultRegistryTypes.BTCVaultProtocolInfo\",\n components: [\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"universalChallengersVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"appVaultKeepersVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"offchainParamsVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"verifiedAt\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"prePeginTxHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"vaultProviderCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"protocolParams\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"address\",\n internalType: \"contract IProtocolParams\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"applicationRegistry\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"address\",\n internalType: \"contract IApplicationRegistry\",\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n","/**\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 * Predicate to determine if a method is safe to retry.\n * Default: only retry `vaultProvider_getPeginStatus` and `vaultProvider_getPegoutStatus`.\n * Write/mutating methods are NOT retried by default.\n */\n retryableFor?: (method: string) => boolean;\n /**\n * Optional bearer-token provider. If set, the client injects\n * `Authorization: Bearer <token>` for every method the provider\n * returns a non-null token for (`call` and `callRaw` alike).\n *\n * `call` also performs a one-shot reactive refresh when a wire-origin\n * JSON-RPC error carries `error.data.kind === \"auth_expired\"` —\n * it calls `invalidate()`, fetches a fresh token, and retries the\n * request once. `callRaw` does NOT perform reactive refresh (its\n * body may be unbounded; we don't parse it).\n */\n tokenProvider?: BearerTokenProvider;\n}\n\n/**\n * Identifies whether an error was produced locally (timeout, network\n * failure, malformed response) or parsed from a wire-format JSON-RPC\n * error envelope returned by the server.\n *\n * This matters for anyone inspecting the shared `-32001` code: the SDK\n * uses it internally for network failures AND the server uses it for\n * auth-middleware rejections. The `source` field disambiguates.\n */\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} 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/** 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_getPegoutStatus\",\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 */\nconst 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 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.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 jsonResponse = await response.json();\n } catch {\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","/**\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 -> Activated\n *\n * Terminal / branching states:\n * - Expired: vault timed out before activation\n * - ClaimPosted: claim transaction posted on-chain\n * - PeggedOut: BTC has been returned to the depositor\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 = \"Activated\",\n EXPIRED = \"Expired\",\n CLAIM_POSTED = \"ClaimPosted\",\n PEGGED_OUT = \"PeggedOut\",\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,\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 where no further progress is possible.\n * If the VP reaches one of these states while polling, polling should\n * stop immediately with an error rather than waiting for timeout.\n */\nexport const VP_TERMINAL_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.EXPIRED,\n DaemonStatus.CLAIM_POSTED,\n DaemonStatus.PEGGED_OUT,\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/** Params for querying pegout status from the VP daemon. */\nexport interface GetPegoutStatusParams {\n pegin_txid: string;\n}\n\n/** Claimer-side pegout progress. */\nexport interface ClaimerPegoutStatus {\n status: string;\n failed: boolean;\n claim_txid?: string;\n claimer_pubkey?: string;\n challenger_pubkey?: string;\n created_at?: string;\n updated_at?: string;\n}\n\n/** Challenger-side pegout progress. */\nexport interface ChallengerPegoutStatus {\n status: string;\n claim_txid?: string;\n claimer_pubkey?: string;\n assert_txid?: string;\n challenge_assert_txid?: string;\n nopayout_txid?: string;\n created_at?: string;\n updated_at?: string;\n}\n\n/** Response from `getPegoutStatus`. */\nexport interface GetPegoutStatusResponse {\n pegin_txid: string;\n found: boolean;\n claimer?: ClaimerPegoutStatus;\n challenger?: ChallengerPegoutStatus;\n}\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/** JSON-RPC error codes returned by the vault provider. */\nexport enum RpcErrorCode {\n DATABASE_ERROR = -32005,\n PRESIGN_ERROR = -32006,\n JSON_SERIALIZATION_ERROR = -32007,\n TX_GRAPH_ERROR = -32008,\n INVALID_GRAPH = -32009,\n VALIDATION_ERROR = -32010,\n NOT_FOUND = -32011,\n INTERNAL_ERROR = -32603,\n}\n"],"names":["BTCVaultRegistryABI","JsonRpcError","code","message","source","data","JSON_RPC_ERROR_CODES","JSON_RPC_VERSION","DEFAULT_RETRY_ATTEMPTS","DEFAULT_RETRY_DELAY_MS","RETRYABLE_HTTP_STATUS_CODES","DEFAULT_RETRYABLE_METHODS","defaultRetryableFor","method","AUTH_EXPIRED_DATA_KIND","isAuthExpiredError","error","JsonRpcClient","config","__publicField","headers","token","params","signal","response","jsonResponse","rpcResponse","err","callerSignal","requestId","maxRetries","body","lastError","attempt","timeoutController","timeoutId","merged","mergeAbortSignals","delay","ms","resolve","reject","onAbort","a","b","controller","onAbortA","onAbortB","cleanup","DaemonStatus","PRE_DEPOSITOR_SIGNATURES_STATES","POST_PAYOUT_SIGNATURE_STATUSES","VP_TRANSIENT_STATUSES","VP_TERMINAL_STATUSES","POST_WOTS_STATUSES","RpcErrorCode"],"mappings":";;;AAaO,MAAMA,IAAsB;AAAA,EACjC;AAAA,IACE,MAAM;AAAA,IACN,MAAM;AAAA,IACN,QAAQ;AAAA,MACN;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,MAEhB;AAAA,QACE,MAAM;AAAA,QACN,MAAM;AAAA,QACN,cAAc;AAAA,MAAA;AAAA,IAChB;AAAA,IAEF,SAAS;AAAA,MACP;AAAA,QACE,MAAM;AAAA,QACN,MAAM;A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EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AACF,GAGMC,IAA0D;AAAA,EAC9D;AAAA,EACA;AAAA,EACA;AAAA;AACF,GAMaC,wBAAuD,IAAI;AAAA,EACtE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAGD;AACL,CAAC,GAOYE,wBAAsD,IAAI;AAAA,EACrE;AAAA,EACA;AAAA,EACA;AAAA;AACF,CAAC,GAOYC,wBAAoD,IAAI;AAAA,EACnE,GAAGF;AAAA,EACH;AAAA;AACF,CAAC;AAuOM,IAAKG,sBAAAA,OACVA,EAAAA,EAAA,iBAAiB,MAAA,IAAjB,kBACAA,EAAAA,EAAA,gBAAgB,MAAA,IAAhB,iBACAA,EAAAA,EAAA,2BAA2B,MAAA,IAA3B,4BACAA,EAAAA,EAAA,iBAAiB,MAAA,IAAjB,kBACAA,EAAAA,EAAA,gBAAgB,MAAA,IAAhB,iBACAA,EAAAA,EAAA,mBAAmB,MAAA,IAAnB,oBACAA,EAAAA,EAAA,YAAY,MAAA,IAAZ,aACAA,EAAAA,EAAA,iBAAiB,MAAA,IAAjB,kBARUA,IAAAA,KAAA,CAAA,CAAA;"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"types-jmEyzzhY.cjs","sources":["../src/tbv/core/contracts/abis/BTCVaultRegistry.abi.ts","../src/tbv/core/clients/vault-provider/json-rpc-client.ts","../src/tbv/core/clients/vault-provider/types.ts"],"sourcesContent":["/**\n * BTCVaultRegistry Contract ABI\n *\n * Minimal ABI containing only the functions needed by the SDK.\n * Full ABI is available in the vault service package.\n *\n * @module contracts/abis/BTCVaultRegistry\n */\n\n/**\n * Minimal ABI for BTCVaultRegistry contract.\n * Contains submitPeginRequest, submitPeginRequestBatch, activateVaultWithSecret, getPegInFee, and getBtcVaultBasicInfo.\n */\nexport const BTCVaultRegistryABI = [\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"referralCode\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequestBatch\",\n inputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n {\n name: \"requests\",\n type: \"tuple[]\",\n internalType: \"struct IBTCVaultRegistry.BatchPeginRequest[]\",\n components: [\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"btcPopSignature\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"unsignedPrePeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorSignedPeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"hashlock\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"htlcVout\", type: \"uint8\", internalType: \"uint8\" },\n { name: \"referralCode\", type: \"uint32\", internalType: \"uint32\" },\n { name: \"depositorPayoutBtcAddress\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorWotsPkHash\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n },\n ],\n outputs: [\n { name: \"vaultIds\", type: \"bytes32[]\", internalType: \"bytes32[]\" },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"activateVaultWithSecret\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"s\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"activationMetadata\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getPegInFee\",\n inputs: [\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"totalFee\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getBtcVaultBasicInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"vBasic\",\n type: \"tuple\",\n internalType: \"struct BTCVaultTypes.BTCVaultBasicInfo\",\n components: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"status\",\n type: \"uint8\",\n internalType: \"enum IBTCVaultRegistry.BTCVaultStatus\",\n },\n {\n name: \"applicationEntryPoint\",\n type: \"address\",\n internalType: \"address\",\n },\n { name: \"createdAt\", type: \"uint256\", internalType: \"uint256\" },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"error\",\n name: \"InvalidPeginFee\",\n inputs: [\n {\n name: \"provided\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"required\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n },\n {\n type: \"error\",\n name: \"InvalidSecret\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"ActivationDeadlineExpired\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"DuplicateHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"CapExceeded\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidOutputIndex\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"PeginSignaturesIncomplete\",\n inputs: [],\n },\n {\n type: \"function\",\n name: \"getBtcVaultProtocolInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"vProtocol\",\n type: \"tuple\",\n internalType:\n \"struct BTCVaultRegistryTypes.BTCVaultProtocolInfo\",\n components: [\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"universalChallengersVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"appVaultKeepersVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"offchainParamsVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"verifiedAt\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"prePeginTxHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"vaultProviderCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"protocolParams\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"address\",\n internalType: \"contract IProtocolParams\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"applicationRegistry\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"address\",\n internalType: \"contract IApplicationRegistry\",\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n","/**\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 * Predicate to determine if a method is safe to retry.\n * Default: only retry `vaultProvider_getPeginStatus` and `vaultProvider_getPegoutStatus`.\n * Write/mutating methods are NOT retried by default.\n */\n retryableFor?: (method: string) => boolean;\n /**\n * Optional bearer-token provider. If set, the client injects\n * `Authorization: Bearer <token>` for every method the provider\n * returns a non-null token for (`call` and `callRaw` alike).\n *\n * `call` also performs a one-shot reactive refresh when a wire-origin\n * JSON-RPC error carries `error.data.kind === \"auth_expired\"` —\n * it calls `invalidate()`, fetches a fresh token, and retries the\n * request once. `callRaw` does NOT perform reactive refresh (its\n * body may be unbounded; we don't parse it).\n */\n tokenProvider?: BearerTokenProvider;\n}\n\n/**\n * Identifies whether an error was produced locally (timeout, network\n * failure, malformed response) or parsed from a wire-format JSON-RPC\n * error envelope returned by the server.\n *\n * This matters for anyone inspecting the shared `-32001` code: the SDK\n * uses it internally for network failures AND the server uses it for\n * auth-middleware rejections. The `source` field disambiguates.\n */\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} 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/** 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_getPegoutStatus\",\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 */\nconst 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 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.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 jsonResponse = await response.json();\n } catch {\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","/**\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 -> Activated\n *\n * Terminal / branching states:\n * - Expired: vault timed out before activation\n * - ClaimPosted: claim transaction posted on-chain\n * - PeggedOut: BTC has been returned to the depositor\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 = \"Activated\",\n EXPIRED = \"Expired\",\n CLAIM_POSTED = \"ClaimPosted\",\n PEGGED_OUT = \"PeggedOut\",\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,\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 where no further progress is possible.\n * If the VP reaches one of these states while polling, polling should\n * stop immediately with an error rather than waiting for timeout.\n */\nexport const VP_TERMINAL_STATUSES: ReadonlySet<DaemonStatus> = new Set([\n DaemonStatus.EXPIRED,\n DaemonStatus.CLAIM_POSTED,\n DaemonStatus.PEGGED_OUT,\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/** Params for querying pegout status from the VP daemon. */\nexport interface GetPegoutStatusParams {\n pegin_txid: string;\n}\n\n/** Claimer-side pegout progress. */\nexport interface ClaimerPegoutStatus {\n status: string;\n failed: boolean;\n claim_txid?: string;\n claimer_pubkey?: string;\n challenger_pubkey?: string;\n created_at?: string;\n updated_at?: string;\n}\n\n/** Challenger-side pegout progress. */\nexport interface ChallengerPegoutStatus {\n status: string;\n claim_txid?: string;\n claimer_pubkey?: string;\n assert_txid?: string;\n challenge_assert_txid?: string;\n nopayout_txid?: string;\n created_at?: string;\n updated_at?: string;\n}\n\n/** Response from `getPegoutStatus`. */\nexport interface GetPegoutStatusResponse {\n pegin_txid: string;\n found: boolean;\n claimer?: ClaimerPegoutStatus;\n challenger?: ChallengerPegoutStatus;\n}\n\n// ============================================================================\n// Error Codes\n// ============================================================================\n\n/** JSON-RPC error codes returned by the vault provider. */\nexport enum RpcErrorCode {\n DATABASE_ERROR = -32005,\n PRESIGN_ERROR = -32006,\n JSON_SERIALIZATION_ERROR = -32007,\n TX_GRAPH_ERROR = -32008,\n INVALID_GRAPH = -32009,\n VALIDATION_ERROR = -32010,\n NOT_FOUND = -32011,\n INTERNAL_ERROR = -32603,\n}\n"],"names":["BTCVaultRegistryABI","JsonRpcError","code","message","source","data","JSON_RPC_ERROR_CODES","JSON_RPC_VERSION","DEFAULT_RETRY_ATTEMPTS","DEFAULT_RETRY_DELAY_MS","RETRYABLE_HTTP_STATUS_CODES","DEFAULT_RETRYABLE_METHODS","defaultRetryableFor","method","AUTH_EXPIRED_DATA_KIND","isAuthExpiredError","error","JsonRpcClient","config","__publicField","headers","token","params","signal","response","jsonResponse","rpcResponse","err","callerSignal","requestId","maxRetries","body","lastError","attempt","timeoutController","timeoutId","merged","mergeAbortSignals","delay","ms","resolve","reject","onAbort","a","b","controller","onAbortA","onAbortB","cleanup","DaemonStatus","PRE_DEPOSITOR_SIGNATURES_STATES","POST_PAYOUT_SIGNATURE_STATUSES","VP_TRANSIENT_STATUSES","VP_TERMINAL_STATUSES","POST_WOTS_STATUSES","RpcErrorCode"],"mappings":"iLAaO,MAAMA,EAAsB,CACjC,CACE,KAAM,WACN,KAAM,qBACN,OAAQ,CACN,CACE,KAAM,YACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,qBACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,kBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,qBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,yBACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,gBACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,WACN,KAAM,UACN,aAAc,SAAA,EAEhB,CACE,KAAM,WACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,4BACN,KAAM,QACN,aAAc,OAAA,EAEhB,CACE,KAAM,sBACN,KAAM,UACN,aAAc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AAiB,MAAA,EAAjB,iBACAA,EAAAA,EAAA,cAAgB,MAAA,EAAhB,gBACAA,EAAAA,EAAA,iBAAmB,MAAA,EAAnB,mBACAA,EAAAA,EAAA,UAAY,MAAA,EAAZ,YACAA,EAAAA,EAAA,eAAiB,MAAA,EAAjB,iBARUA,IAAAA,GAAA,CAAA,CAAA"}
@@ -1,2 +0,0 @@
1
- "use strict";var ae=Object.defineProperty;var oe=(n,e,t)=>e in n?ae(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var l=(n,e,t)=>oe(n,typeof e!="symbol"?e+"":e,t);const h=require("./validation-u8W7Lp2x.cjs"),_=require("./types-jmEyzzhY.cjs"),p=require("./bitcoin-EYBKDtEW.cjs"),ce=require("@bitcoin-js/tiny-secp256k1-asmjs"),P=require("bitcoinjs-lib"),g=require("buffer"),O=require("./sha2-CsTynrfJ.cjs");function le(n){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const t in n)if(t!=="default"){const r=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>n[t]})}}return e.default=n,Object.freeze(e)}const B=le(ce),ue=21e6*1e8,F=3e4;async function $(n,e){const t=new AbortController,r=setTimeout(()=>t.abort(),F),s=[t.signal,e==null?void 0:e.signal].filter(Boolean);try{return await fetch(n,{...e,signal:AbortSignal.any(s)})}catch(i){throw clearTimeout(r),i!=null&&typeof i=="object"&&"name"in i&&i.name==="AbortError"?new Error(`Mempool API request timed out after ${F}ms: ${n}`):i}}const L=1e4;function q(n){return Number.isInteger(n)&&n>0&&n<=ue}function pe(n){return Number.isInteger(n)&&n>0&&n<=L}function Y(n,e){return!Number.isInteger(n)||n<0?!1:e===void 0||n<e}function I(n){if(!h.TXID_RE.test(n))throw new Error(`Invalid transaction ID format: ${n}`)}function G(n){if(!h.BITCOIN_ADDRESS_RE.test(n))throw new Error(`Invalid Bitcoin address format: ${n}`)}function W(n,e){if(!h.HEX_RE.test(n))throw new Error(`Invalid scriptPubKey: not valid hex for ${e}`);if(!h.KNOWN_SCRIPT_PREFIXES.some(r=>n.toLowerCase().startsWith(r)))throw new Error(`Unrecognized scriptPubKey type for ${e}: prefix ${n.slice(0,6)} does not match any known Bitcoin script type`)}const J={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function x(n,e){try{const t=await $(n,e);if(!t.ok){const s=await t.text();throw new Error(`Mempool API error (${t.status}): ${s||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 de(n,e){try{const t=await $(`${e}/tx`,{method:"POST",body:n,headers:{"Content-Type":"text/plain"}});if(!t.ok){const s=await t.text();let i;try{i=JSON.parse(s).message}catch{i=s}throw new Error(i||`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 z(n,e){return I(n),x(`${e}/tx/${n}`)}async function fe(n,e){I(n);try{const t=await $(`${e}/tx/${n}/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 ${n}: ${t.message}`):new Error(`Failed to get transaction hex for ${n}: Unknown error`)}}async function me(n,e,t){I(n);const r=await z(n,t);if(!Y(e,r.vout.length))throw new Error(`Invalid vout ${e} for transaction ${n} (has ${r.vout.length} outputs)`);const s=r.vout[e];if(!q(s.value))throw new Error(`Invalid UTXO value ${s.value} for ${n}:${e}`);return W(s.scriptpubkey,`${n}:${e}`),{txid:n,vout:e,value:s.value,scriptPubKey:s.scriptpubkey}}async function he(n,e){G(n);try{const t=await x(`${e}/address/${n}/utxo`),r=await x(`${e}/v1/validate-address/${n}`);if(!r.isvalid)throw new Error(`Invalid Bitcoin address: ${n}. Mempool API validation failed.`);W(r.scriptPubKey,n);for(const i of t){if(I(i.txid),!Y(i.vout))throw new Error(`Invalid vout ${i.vout} for ${i.txid}`);if(!q(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${i.txid}:${i.vout}`)}return t.sort((i,c)=>c.value-i.value).map(i=>({txid:i.txid,vout:i.vout,value:i.value,scriptPubKey:r.scriptPubKey,confirmed:i.status.confirmed}))}catch(t){throw t instanceof Error?new Error(`Failed to get UTXOs for address ${n}: ${t.message}`):new Error(`Failed to get UTXOs for address ${n}: Unknown error`)}}function ye(n){return J[n]}async function ge(n,e){return G(n),x(`${e}/address/${n}/txs`)}async function _e(n){const e=await $(`${n}/v1/fees/recommended`);if(!e.ok)throw new Error(`Failed to fetch network fees: ${e.status} ${e.statusText}`);const t=await e.json(),r=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const s of r)if(!pe(t[s]))throw new Error(`Invalid fee rate ${s}=${t[s]} from mempool API: expected a positive number ≤ ${L}`);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}const T=[{type:"function",name:"getVaultKeepersByVersion",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"},{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentVaultKeepers",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentVaultKeepersVersion",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"}],f=[{type:"function",name:"getTBVProtocolParams",inputs:[],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.TBVProtocolParams",components:[{name:"minimumPegInAmount",type:"uint64",internalType:"uint64"},{name:"maxPegInAmount",type:"uint64",internalType:"uint64"},{name:"pegInAckTimeout",type:"uint64",internalType:"uint64"},{name:"pegInActivationTimeout",type:"uint64",internalType:"uint64"},{name:"maxHtlcOutputCount",type:"uint8",internalType:"uint8"}]}],stateMutability:"view"},{type:"function",name:"getLatestOffchainParams",inputs:[],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.VersionedOffchainParams",components:[{name:"timelockAssert",type:"uint256",internalType:"uint256"},{name:"timelockChallengeAssert",type:"uint256",internalType:"uint256"},{name:"securityCouncilKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"councilQuorum",type:"uint8",internalType:"uint8"},{name:"feeRate",type:"uint64",internalType:"uint64"},{name:"babeTotalInstances",type:"uint16",internalType:"uint16"},{name:"babeInstancesToFinalize",type:"uint8",internalType:"uint8"},{name:"minVpCommissionBps",type:"uint16",internalType:"uint16"},{name:"tRefund",type:"uint32",internalType:"uint32"},{name:"tStale",type:"uint32",internalType:"uint32"},{name:"minPeginFeeRate",type:"uint64",internalType:"uint64"},{name:"proverProgramVersion",type:"uint16",internalType:"uint16"},{name:"minPrepeginDepth",type:"uint32",internalType:"uint32"}]}],stateMutability:"view"},{type:"function",name:"getOffchainParamsByVersion",inputs:[{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.VersionedOffchainParams",components:[{name:"timelockAssert",type:"uint256",internalType:"uint256"},{name:"timelockChallengeAssert",type:"uint256",internalType:"uint256"},{name:"securityCouncilKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"councilQuorum",type:"uint8",internalType:"uint8"},{name:"feeRate",type:"uint64",internalType:"uint64"},{name:"babeTotalInstances",type:"uint16",internalType:"uint16"},{name:"babeInstancesToFinalize",type:"uint8",internalType:"uint8"},{name:"minVpCommissionBps",type:"uint16",internalType:"uint16"},{name:"tRefund",type:"uint32",internalType:"uint32"},{name:"tStale",type:"uint32",internalType:"uint32"},{name:"minPeginFeeRate",type:"uint64",internalType:"uint64"},{name:"proverProgramVersion",type:"uint16",internalType:"uint16"},{name:"minPrepeginDepth",type:"uint32",internalType:"uint32"}]}],stateMutability:"view"},{type:"function",name:"latestOffchainParamsVersion",inputs:[],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"},{type:"function",name:"getUniversalChallengersByVersion",inputs:[{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentUniversalChallengers",inputs:[],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"latestUniversalChallengersVersion",inputs:[],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"}],U=new Set(Object.values(_.DaemonStatus)),be=200;function o(n){var e;return((e=JSON.stringify(n))==null?void 0:e.slice(0,be))??"undefined"}const we="The vault provider returned an unexpected response. Please try again or contact support.";class a extends Error{constructor(t){super(we);l(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const A=64;function b(n){return typeof n=="string"&&n.length>0&&h.HEX_RE.test(n)}function Q(n){return typeof n=="string"&&n.length>0}function Z(n,e){if(!b(n))throw new a(`VP response validation failed: "${e}" must be a non-empty hex string, got ${o(n)}`)}function w(n,e){if(!Q(n))throw new a(`VP response validation failed: "${e}" must be a non-empty string, got ${o(n)}`)}function ee(n,e){if(!b(n)||n.length!==p.X_ONLY_PUBKEY_HEX_LEN&&n.length!==p.COMPRESSED_PUBKEY_HEX_LEN)throw new a(`VP response validation failed: "${e}" must be a ${p.X_ONLY_PUBKEY_HEX_LEN} or ${p.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${o(n)}`)}function Pe(n){const e=n.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new a('VP response validation failed: "progress.presigning" must be an object if present');const t=e;if(t.depositor_graph_created!==void 0&&typeof t.depositor_graph_created!="boolean")throw new a(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${o(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${o(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${o(t.vk_challenger_presigning_total)}`)}function ve(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: getPeginStatus response is not an object");const e=n;if(!b(e.pegin_txid)||e.pegin_txid.length!==A)throw new a(`VP response validation failed: "pegin_txid" must be a ${A}-char hex string (txid), got ${o(e.pegin_txid)}`);if(typeof e.status!="string")throw new a('VP response validation failed: "status" must be a string');if(!U.has(e.status))throw new a(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...U].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new a('VP response validation failed: "progress" must be an object');if(Pe(e.progress),typeof e.health_info!="string")throw new a('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new a(`VP response validation failed: "last_error" must be a string if present, got ${o(e.last_error)}`)}function Te(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=n;if(!Array.isArray(e.txs))throw new a('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)xe(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new a('VP response validation failed: "depositor_graph" must be an object');$e(e.depositor_graph)}function y(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);Z(n.tx_hex,`${e}.tx_hex`)}function xe(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=n;ee(t.claimer_pubkey,`${e}.claimer_pubkey`),y(t.claim_tx,`${e}.claim_tx`),y(t.assert_tx,`${e}.assert_tx`),y(t.payout_tx,`${e}.payout_tx`),w(t.payout_psbt,`${e}.payout_psbt`)}function Ae(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=n;w(t.wots_pks_json,`${e}.wots_pks_json`),w(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function Ve(n,e){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=n;if(ee(t.challenger_pubkey,`${e}.challenger_pubkey`),y(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),y(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),y(t.nopayout_tx,`${e}.nopayout_tx`),w(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);for(let r=0;r<t.challenge_assert_connectors.length;r++)Ae(t.challenge_assert_connectors[r],`${e}.challenge_assert_connectors[${r}]`);if(!Array.isArray(t.output_label_hashes))throw new a(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let r=0;r<t.output_label_hashes.length;r++)Z(t.output_label_hashes[r],`${e}.output_label_hashes[${r}]`)}function te(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=n;if(!Q(e.tx_graph_json))throw new a(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${o(e.tx_graph_json)}`);if(!b(e.verifying_key_hex))throw new a(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${o(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object")throw new a('VP response validation failed: "babe_sessions" must be an object');for(const[t,r]of Object.entries(e.babe_sessions)){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "babe_sessions.${t}" must be an object`);const s=r;if(!b(s.decryptor_artifacts_hex))throw new a(`VP response validation failed: "babe_sessions.${t}.decryptor_artifacts_hex" must be a non-empty hex string, got ${o(s.decryptor_artifacts_hex)}`)}}function Ee(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: getPegoutStatus response is not an object");const e=n;if(!b(e.pegin_txid)||e.pegin_txid.length!==A)throw new a(`VP response validation failed: "pegin_txid" must be a ${A}-char hex string (txid), got ${o(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new a(`VP response validation failed: "found" must be a boolean, got ${o(e.found)}`);if(e.claimer!==void 0){if(e.claimer===null||typeof e.claimer!="object")throw new a('VP response validation failed: "claimer" must be an object if present');const t=e.claimer;if(typeof t.status!="string")throw new a(`VP response validation failed: "claimer.status" must be a string, got ${o(t.status)}`);if(typeof t.failed!="boolean")throw new a(`VP response validation failed: "claimer.failed" must be a boolean, got ${o(t.failed)}`)}if(e.challenger!==void 0){if(e.challenger===null||typeof e.challenger!="object")throw new a('VP response validation failed: "challenger" must be an object if present');const t=e.challenger;if(typeof t.status!="string")throw new a(`VP response validation failed: "challenger.status" must be a string, got ${o(t.status)}`)}}function $e(n){if(y(n.claim_tx,"depositor_graph.claim_tx"),y(n.assert_tx,"depositor_graph.assert_tx"),y(n.payout_tx,"depositor_graph.payout_tx"),w(n.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(n.challenger_presign_data))throw new a('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<n.challenger_presign_data.length;e++)Ve(n.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof n.offchain_params_version!="number")throw new a('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Ie=6e4;class Ce{constructor(e,t){l(this,"client");const r={baseUrl:e,timeout:(t==null?void 0:t.timeout)??Ie,retries:t==null?void 0:t.retries,retryDelay:t==null?void 0:t.retryDelay,retryableFor:t==null?void 0:t.retryableFor,headers:t==null?void 0:t.headers};this.client=new _.JsonRpcClient(r)}async requestDepositorPresignTransactions(e,t){const r=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return Te(r),r}async submitDepositorPresignatures(e,t){return this.client.call("vaultProvider_submitDepositorPresignatures",e,t)}async submitDepositorWotsKey(e,t){return this.client.call("vaultProvider_submitDepositorWotsKey",e,t)}async requestDepositorClaimerArtifacts(e,t){const r=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return te(r),r}async getPeginStatus(e,t){const r=await this.client.call("vaultProvider_getPeginStatus",e,t);return ve(r),r}async getPegoutStatus(e,t){const r=await this.client.call("vaultProvider_getPegoutStatus",e,t);return Ee(r),r}}const Se="BIP0322-signed-message",ke="TapTweak",ne=32,Be=64;function re(n,e){const t=new TextEncoder().encode(n),r=O.sha256(t),s=new Uint8Array(r.length*2+e.length);return s.set(r,0),s.set(r,r.length),s.set(e,r.length*2),O.sha256(s)}function Re(n){if(n.length!==ne)return null;const e=re(ke,n),t=B.xOnlyPointAddTweak(n,e);return t?t.xOnlyPubkey:null}function Ne(n,e,t){if(e.length!==ne||t.length!==Be)return!1;try{const r=re(Se,n),s=P.payments.p2tr({internalPubkey:g.Buffer.from(e)});if(!s.output)return!1;const i=s.output,c=0,m=new P.Transaction;m.version=0,m.locktime=0;const C=g.Buffer.concat([g.Buffer.from([0,32]),g.Buffer.from(r)]);m.addInput(g.Buffer.alloc(32,0),4294967295,0,C),m.addOutput(i,c);const d=new P.Transaction;d.version=0,d.locktime=0;const S=m.getHash();d.addInput(S,0,0),d.addOutput(g.Buffer.from([106]),c);const R=d.hashForWitnessV1(0,[i],[c],P.Transaction.SIGHASH_DEFAULT),N=Re(e);return N?B.verifySchnorr(R,N,t):!1}catch{return!1}}function V(n,e){const t=(n&7)<<5,r=typeof e=="bigint"?e:BigInt(e);if(r<0n)throw new Error("cborHead: negative argument");if(r<24n)return new Uint8Array([t|Number(r)]);if(r<0x100n)return new Uint8Array([t|24,Number(r)]);if(r<0x10000n){const i=Number(r);return new Uint8Array([t|25,i>>>8&255,i&255])}if(r<0x100000000n){const i=Number(r);return new Uint8Array([t|26,i>>>24&255,i>>>16&255,i>>>8&255,i&255])}const s=new Uint8Array(9);s[0]=t|27;for(let i=7;i>=0;i--)s[1+i]=Number(r>>BigInt((7-i)*8))&255;return s}function ie(...n){const e=n.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e);let r=0;for(const s of n)t.set(s,r),r+=s.length;return t}function H(n){const t=[V(4,n.length)];for(const r of n)t.push(V(0,r));return ie(...t)}function Oe(n,e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${t}`);const r=V(4,3),s=H(n),i=H(e),c=V(0,t);return ie(r,s,i,c)}const Fe=new TextEncoder().encode("btc-auth.server-identity.v1");class u extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function v(n){const e=new Uint8Array(n.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(n.slice(t*2,t*2+2),16);return e}function se(n){const{proof:e,pinnedServerPubkey:t,now:r}=n,s=p.stripHexPrefix(t).toLowerCase();if(s.length!==p.X_ONLY_PUBKEY_HEX_LEN||!h.HEX_RE.test(s))throw new u(`pinnedServerPubkey must be 32-byte hex; got ${s.length} chars`,"invalid_pubkey_encoding");const i=p.stripHexPrefix(e.server_pubkey).toLowerCase();if(i.length!==p.X_ONLY_PUBKEY_HEX_LEN||!h.HEX_RE.test(i))throw new u(`server_pubkey must be 32-byte hex; got ${i.length} chars`,"invalid_pubkey_encoding");if(i!==s)throw new u(`server_pubkey does not match pinned value: expected ${s}, got ${i}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new u(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(r))throw new u(`now must be a finite integer; got ${JSON.stringify(r)}`,"invalid_expires_at");if(e.expires_at<=r)throw new u(`server identity proof expired at ${e.expires_at}, now ${r}`,"expired");const c=p.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(c.length!==p.COMPRESSED_PUBKEY_HEX_LEN||!h.HEX_RE.test(c))throw new u(`ephemeral_pubkey must be 33-byte compressed hex; got ${c.length} chars`,"invalid_ephemeral_pubkey");const m=c.slice(0,2);if(m!=="02"&&m!=="03")throw new u(`ephemeral_pubkey must be compressed (prefix 02/03); got ${m}`,"invalid_ephemeral_pubkey");const C=v(c);if(!B.isPoint(C))throw new u("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const d=p.stripHexPrefix(e.signature).toLowerCase();if(d.length!==p.SCHNORR_SIG_HEX_LEN||!h.HEX_RE.test(d))throw new u(`signature must be 64-byte Schnorr hex; got ${d.length} chars`,"invalid_signature_encoding");const S=Oe(Fe,v(c),e.expires_at);if(!Ne(S,v(i),v(d)))throw new u("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const K="auth_createDepositorToken",j=4102444800,Ue=30;class He{constructor(e){l(this,"client");l(this,"peginTxid");l(this,"authAnchorHex");l(this,"pinnedServerPubkey");l(this,"authGatedMethods");l(this,"refreshSkewSecs");l(this,"now");l(this,"cached",null);l(this,"inFlight",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.authGatedMethods=e.authGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??Ue,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){if(e===K||!this.authGatedMethods.has(e))return null;const t=this.cached;return t&&this.now()+this.refreshSkewSecs<t.expiresAt?t.token:(await this.acquireSingleFlight()).token}invalidate(){this.cached=null}acquireSingleFlight(){const e=this.inFlight;if(e)return e;const t=(async()=>{try{const r=await this.client.call(K,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(se({proof:r.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof r.token!="string"||r.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof r.token})`);const s=this.now();if(!Number.isSafeInteger(r.expires_at)||r.expires_at<=s||r.expires_at>j)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(r.expires_at)}; must be a safe integer in (${s}, ${j}])`);const i={token:r.token,expiresAt:r.expires_at};return this.cached=i,i}finally{this.inFlight=null}})();return this.inFlight=t,t}}async function Ke(n,e){const[t,r]=await n.multicall({contracts:[{address:e,abi:_.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:_.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:r}}const D=65535;function k(n){return{timelockAssert:n.timelockAssert,timelockChallengeAssert:n.timelockChallengeAssert,securityCouncilKeys:[...n.securityCouncilKeys],councilQuorum:n.councilQuorum,feeRate:n.feeRate,babeTotalInstances:n.babeTotalInstances,babeInstancesToFinalize:n.babeInstancesToFinalize,minVpCommissionBps:n.minVpCommissionBps,tRefund:n.tRefund,tStale:n.tStale,minPeginFeeRate:n.minPeginFeeRate,proverProgramVersion:n.proverProgramVersion,minPrepeginDepth:n.minPrepeginDepth}}function M(n){return{minimumPegInAmount:n.minimumPegInAmount,maxPegInAmount:n.maxPegInAmount,pegInAckTimeout:n.pegInAckTimeout,pegInActivationTimeout:n.pegInActivationTimeout,maxHtlcOutputCount:n.maxHtlcOutputCount}}function X(n){if(n>BigInt(D))throw new Error(`timelockAssert value ${n} exceeds uint16 max (${D})`);return Number(n)}class je{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getTBVProtocolParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getTBVProtocolParams"});return M(e)}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getLatestOffchainParams"});return k(e)}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getOffchainParamsByVersion",args:[e]});return k(t)}async getLatestOffchainParamsVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"latestOffchainParamsVersion"})}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return X(t.timelockAssert)}async getPegInConfiguration(){const e=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:f,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:f,functionName:"getLatestOffchainParams"}],allowFailure:!1}),t=M(e[0]),r=k(e[1]);return{minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,timelockPegin:X(r.timelockAssert),timelockRefund:r.tRefund,minVpCommissionBps:r.minVpCommissionBps,offchainParams:r}}}function E(n){return n.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class De{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultKeepersByVersion(e,t){const r=await this.publicClient.readContract({address:this.contractAddress,abi:T,functionName:"getVaultKeepersByVersion",args:[e,t]});return E(r)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:T,functionName:"getCurrentVaultKeepers",args:[e]});return E(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:T,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class Me{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getUniversalChallengersByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getUniversalChallengersByVersion",args:[e]});return E(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getCurrentUniversalChallengers"});return E(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"latestUniversalChallengersVersion"})}}class Xe{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultBasicInfo(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:_.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[e]});return{depositor:t.depositor,depositorBtcPubKey:t.depositorBtcPubKey,amount:t.amount,vaultProvider:t.vaultProvider,status:t.status,applicationEntryPoint:t.applicationEntryPoint,createdAt:t.createdAt}}async getVaultProtocolInfo(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:_.BTCVaultRegistryABI,functionName:"getBtcVaultProtocolInfo",args:[e]});return{depositorSignedPeginTx:t.depositorSignedPeginTx,universalChallengersVersion:t.universalChallengersVersion,appVaultKeepersVersion:t.appVaultKeepersVersion,offchainParamsVersion:t.offchainParamsVersion,verifiedAt:t.verifiedAt,depositorWotsPkHash:t.depositorWotsPkHash,hashlock:t.hashlock,htlcVout:t.htlcVout,depositorPopSignature:t.depositorPopSignature,prePeginTxHash:t.prePeginTxHash,vaultProviderCommissionBps:t.vaultProviderCommissionBps}}async getVaultData(e){const[t,r]=await Promise.all([this.getVaultBasicInfo(e),this.getVaultProtocolInfo(e)]);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:t,protocol:r}}}exports.ApplicationRegistryABI=T;exports.MEMPOOL_API_URLS=J;exports.ProtocolParamsABI=f;exports.ServerIdentityError=u;exports.VaultProviderRpcClient=Ce;exports.ViemProtocolParamsReader=je;exports.ViemUniversalChallengerReader=Me;exports.ViemVaultKeeperReader=De;exports.ViemVaultRegistryReader=Xe;exports.VpResponseValidationError=a;exports.VpTokenProvider=He;exports.getAddressTxs=ge;exports.getAddressUtxos=he;exports.getMempoolApiUrl=ye;exports.getNetworkFees=_e;exports.getTxHex=fe;exports.getTxInfo=z;exports.getUtxoInfo=me;exports.pushTx=de;exports.resolveProtocolAddresses=Ke;exports.validateRequestDepositorClaimerArtifactsResponse=te;exports.verifyServerIdentity=se;
2
- //# sourceMappingURL=vault-registry-reader-BBS1_AON.cjs.map