@babylonlabs-io/ts-sdk 0.68.0 → 0.68.1

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 (55) hide show
  1. package/dist/{PeginManager--2R3T2S8.js → PeginManager-Bsv6caG3.js} +371 -363
  2. package/dist/PeginManager-Bsv6caG3.js.map +1 -0
  3. package/dist/PeginManager-C5NWzGT7.cjs +2 -0
  4. package/dist/PeginManager-C5NWzGT7.cjs.map +1 -0
  5. package/dist/{batchPoll-Cjj1du0i.js → batchPoll-Bc_UKaTz.js} +2 -2
  6. package/dist/{batchPoll-Cjj1du0i.js.map → batchPoll-Bc_UKaTz.js.map} +1 -1
  7. package/dist/{batchPoll-REVZiE-M.cjs → batchPoll-C9cZ5usJ.cjs} +2 -2
  8. package/dist/{batchPoll-REVZiE-M.cjs.map → batchPoll-C9cZ5usJ.cjs.map} +1 -1
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.js +5 -5
  11. package/dist/{mempoolApi-_D-jvtj_.js → mempoolApi-71R_CNZa.js} +71 -69
  12. package/dist/mempoolApi-71R_CNZa.js.map +1 -0
  13. package/dist/mempoolApi-BJN9fGEd.cjs +2 -0
  14. package/dist/mempoolApi-BJN9fGEd.cjs.map +1 -0
  15. package/dist/tbv/core/clients/index.cjs +1 -1
  16. package/dist/tbv/core/clients/index.js +2 -2
  17. package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts +9 -0
  18. package/dist/tbv/core/clients/vault-provider/auth/bip322Verify.d.ts.map +1 -1
  19. package/dist/tbv/core/index.cjs +1 -1
  20. package/dist/tbv/core/index.js +5 -5
  21. package/dist/tbv/core/managers/index.cjs +1 -1
  22. package/dist/tbv/core/managers/index.js +1 -1
  23. package/dist/tbv/core/managers/pegin/verifyPopWitness.d.ts.map +1 -1
  24. package/dist/tbv/core/primitives/index.cjs +1 -1
  25. package/dist/tbv/core/primitives/index.js +1 -1
  26. package/dist/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.d.ts +6 -5
  27. package/dist/tbv/core/primitives/psbt/verifyKeyPathSchnorrSignature.d.ts.map +1 -1
  28. package/dist/tbv/index.cjs +1 -1
  29. package/dist/tbv/index.js +5 -5
  30. package/dist/testing/MockBitcoinWallet.d.ts +1 -1
  31. package/dist/testing/MockBitcoinWallet.d.ts.map +1 -1
  32. package/dist/testing/index.cjs +1 -1
  33. package/dist/testing/index.cjs.map +1 -1
  34. package/dist/testing/index.js +66 -62
  35. package/dist/testing/index.js.map +1 -1
  36. package/dist/testing/signBip322P2wpkhWitness.d.ts +5 -0
  37. package/dist/testing/signBip322P2wpkhWitness.d.ts.map +1 -1
  38. package/dist/{toRefundInputs-9hv_6k0E.js → toRefundInputs-4UJfSVEz.js} +2 -2
  39. package/dist/{toRefundInputs-9hv_6k0E.js.map → toRefundInputs-4UJfSVEz.js.map} +1 -1
  40. package/dist/{toRefundInputs-D8sFs44p.cjs → toRefundInputs-DgDhx_Ut.cjs} +2 -2
  41. package/dist/{toRefundInputs-D8sFs44p.cjs.map → toRefundInputs-DgDhx_Ut.cjs.map} +1 -1
  42. package/dist/{verifyKeyPathSchnorrSignature-oGCUbjjZ.js → verifyKeyPathSchnorrSignature-C6Cmk0R1.js} +137 -128
  43. package/dist/verifyKeyPathSchnorrSignature-C6Cmk0R1.js.map +1 -0
  44. package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs +2 -0
  45. package/dist/verifyKeyPathSchnorrSignature-Cr5T4Aym.cjs.map +1 -0
  46. package/package.json +1 -1
  47. package/dist/PeginManager--2R3T2S8.js.map +0 -1
  48. package/dist/PeginManager-CKWq8ouZ.cjs +0 -2
  49. package/dist/PeginManager-CKWq8ouZ.cjs.map +0 -1
  50. package/dist/mempoolApi-EU1La9wk.cjs +0 -2
  51. package/dist/mempoolApi-EU1La9wk.cjs.map +0 -1
  52. package/dist/mempoolApi-_D-jvtj_.js.map +0 -1
  53. package/dist/verifyKeyPathSchnorrSignature-DCOzQkDf.cjs +0 -2
  54. package/dist/verifyKeyPathSchnorrSignature-DCOzQkDf.cjs.map +0 -1
  55. package/dist/verifyKeyPathSchnorrSignature-oGCUbjjZ.js.map +0 -1
@@ -1,2 +1,2 @@
1
- "use strict";var ve=Object.defineProperty;var Ee=(r,e,t)=>e in r?ve(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var m=(r,e,t)=>Ee(r,typeof e!="symbol"?e+"":e,t);const O=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),f=require("./ProtocolParams.abi-CYZoV2EI.cjs"),$=require("./mempoolApi-EU1La9wk.cjs"),_=require("./bitcoin-m84N5a8o.cjs"),M=require("./json-rpc-client-BiAmg_ho.cjs"),q=require("./constants-DU5CGcqO.cjs"),k=require("./validation-CDbOaDj7.cjs"),Ce=require("@bitcoin-js/tiny-secp256k1-asmjs"),Se=require("./sha2-DsrLC4NM.cjs");function ke(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const ue=ke(Ce);async function Te(r,e){const[t,n]=await r.multicall({contracts:[{address:e,abi:O.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:O.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:n}}function W(r,e,t){if(r!==e)throw new Error(`${t}: multicall returned ${r} results for ${e} calls, so the results are not roster-aligned; refusing to use them`)}function $e(r,e){return{vaultProvider:r[0],vaultKeepers:r.slice(1,1+e),universalChallengers:r.slice(1+e)}}class Re{constructor(e,t){this.publicClient=e,this.contracts=t}async readAll(e,t,n,i){const s=await this.publicClient.multicall({contracts:e,allowFailure:!1});return W(s.length,1+t+n,i),$e(s,t)}async getCurrentOperationKeys(e){const t=[{address:this.contracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e.vaultProviderEthAddress]},...e.vaultKeepers.map(n=>({address:this.contracts.applicationRegistry,abi:f.ApplicationRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e.applicationEntryPoint,n.ethAddress]})),...e.universalChallengers.map(n=>({address:this.contracts.protocolParams,abi:f.ProtocolParamsABI,functionName:"getCurrentOperationBtcKey",args:[n.ethAddress]}))];return this.readAll(t,e.vaultKeepers.length,e.universalChallengers.length,"getCurrentOperationKeys")}async getOperationKeysAtEpochs(e,t){const n=[{address:this.contracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[e.vaultProviderEthAddress,t.vpKeyEpoch]},...e.vaultKeepers.map(i=>({address:this.contracts.applicationRegistry,abi:f.ApplicationRegistryABI,functionName:"getOperationBtcKeyAtEpochOrGenesis",args:[e.applicationEntryPoint,i.ethAddress,t.appKeeperKeyEpoch,i.btcPubKey]})),...e.universalChallengers.map(i=>({address:this.contracts.protocolParams,abi:f.ProtocolParamsABI,functionName:"getOperationBtcKeyAtEpochOrGenesis",args:[i.ethAddress,t.ucKeyEpoch,i.btcPubKey]}))];return this.readAll(n,e.vaultKeepers.length,e.universalChallengers.length,"getOperationKeysAtEpochs")}async getPayoutScriptsAtEpochs(e,t){const n=await this.publicClient.multicall({contracts:[{address:this.contracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getPayoutScriptAtEpoch",args:[e.vaultProviderEthAddress,t.vpKeyEpoch]},...e.vaultKeepers.map(i=>({address:this.contracts.applicationRegistry,abi:f.ApplicationRegistryABI,functionName:"getPayoutScriptAtEpoch",args:[e.applicationEntryPoint,i.ethAddress,t.appKeeperKeyEpoch]}))],allowFailure:!1});return W(n.length,1+e.vaultKeepers.length,"getPayoutScriptsAtEpochs"),{vaultProvider:n[0],vaultKeepers:[...n.slice(1)]}}}const z=65535;function B(r){return{timelockAssert:r.timelockAssert,timelockChallengeAssert:r.timelockChallengeAssert,securityCouncilKeys:[...r.securityCouncilKeys],councilQuorum:r.councilQuorum,feeRate:r.feeRate,babeTotalInstances:r.babeTotalInstances,babeInstancesToFinalize:r.babeInstancesToFinalize,minVpCommissionBps:r.minVpCommissionBps,tRefund:r.tRefund,tStale:r.tStale,minPeginFeeRate:r.minPeginFeeRate,proverCircuitVersion:r.proverCircuitVersion,minPrepeginDepth:r.minPrepeginDepth}}function Q(r){return{minimumPegInAmount:r.minimumPegInAmount,maxPegInAmount:r.maxPegInAmount,pegInAckTimeout:r.pegInAckTimeout,pegInActivationTimeout:r.pegInActivationTimeout,maxHtlcOutputCount:r.maxHtlcOutputCount,expiredPegInGraceBlocks:r.expiredPegInGraceBlocks}}function Z(r){if(r>BigInt(z))throw new Error(`timelockAssert value ${r} exceeds uint16 max (${z})`);return Number(r)}class Ve{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getTBVProtocolParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getTBVProtocolParams"}),t=Q(e);return $.validateTBVProtocolParams(t),t}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getLatestOffchainParams"}),t=B(e);return $.validateOffchainParams(t),t}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]}),n=B(t);return $.validateOffchainParams(n),n}async getLatestOffchainParamsVersion(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}),t=Number(e);return $.assertValidOffchainParamsVersion(t),t}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return Z(t.timelockAssert)}async getPeginActivationDelay(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"peginActivationDelay"});if(typeof e!="bigint")throw new Error(`Invalid peginActivationDelay from contract: must be a bigint, got ${typeof e}`);return e}async getPegInConfiguration(){const e=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getLatestOffchainParams"},{address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"},{address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"activeVaultCoreVersion"}],allowFailure:!1}),t=Q(e[0]),n=B(e[1]),i=Number(e[2]),s=Number(e[3]),a={minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,expiredPegInGraceBlocks:t.expiredPegInGraceBlocks,timelockPegin:Z(n.timelockAssert),timelockRefund:n.tRefund,minVpCommissionBps:n.minVpCommissionBps,offchainParams:n,offchainParamsVersion:i,activeVaultCoreVersion:s};return $.validatePegInConfiguration(a),a}async fetchAllOffchainParams(e){const t=await this.getLatestOffchainParamsVersion();if(t===0)return{byVersion:new Map,latestVersion:0};const n=Array.from({length:t},(c,u)=>u+1),i=n.map(c=>({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[c]})),s=await this.publicClient.multicall({contracts:i,allowFailure:!1}),a=new Map;for(let c=0;c<n.length;c++){const u=B(s[c]);try{$.validateOffchainParams(u),a.set(n[c],u)}catch(d){e==null||e(n[c],d instanceof Error?d:new Error(String(d)))}}return{byVersion:a,latestVersion:t}}}function H(r){return r.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class Ie{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultKeepersByVersion(e,t){const n=await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getVaultKeepersByVersion",args:[e,t]});return H(n)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepers",args:[e]});return H(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class Oe{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getUniversalChallengersByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getUniversalChallengersByVersion",args:[e]});return H(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getCurrentUniversalChallengers"});return H(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestUniversalChallengersVersion"})}}var de=(r=>(r[r.PENDING=0]="PENDING",r[r.VERIFIED=1]="VERIFIED",r[r.ACTIVE=2]="ACTIVE",r[r.REDEEMED=3]="REDEEMED",r[r.EXPIRED=4]="EXPIRED",r))(de||{});const ee=new Set(Object.values(M.DaemonStatus)),Be=200;function h(r){var e;return((e=JSON.stringify(r))==null?void 0:e.slice(0,Be))??"undefined"}const Ne="The vault provider returned an unexpected response. Please try again or contact support.";class o extends Error{constructor(t){super(Ne);m(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const I=64;function R(r){return typeof r=="string"&&r.length>0&&k.HEX_RE.test(r)}function pe(r){return typeof r=="string"&&r.length>0}function he(r,e){if(!R(r))throw new o(`VP response validation failed: "${e}" must be a non-empty hex string, got ${h(r)}`)}function P(r,e){if(!pe(r))throw new o(`VP response validation failed: "${e}" must be a non-empty string, got ${h(r)}`)}function J(r,e){if(!R(r)||r.length!==_.X_ONLY_PUBKEY_HEX_LEN&&r.length!==_.COMPRESSED_PUBKEY_HEX_LEN)throw new o(`VP response validation failed: "${e}" must be a ${_.X_ONLY_PUBKEY_HEX_LEN} or ${_.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${h(r)}`)}function Le(r){const e=r.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new o('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 o(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${h(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new o(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${h(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new o(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${h(t.vk_challenger_presigning_total)}`)}function ge(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: getPeginStatus response is not an object");const e=r;if(!R(e.pegin_txid)||e.pegin_txid.length!==I)throw new o(`VP response validation failed: "pegin_txid" must be a ${I}-char hex string (txid), got ${h(e.pegin_txid)}`);if(typeof e.status!="string")throw new o('VP response validation failed: "status" must be a string');if(!ee.has(e.status))throw new o(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...ee].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new o('VP response validation failed: "progress" must be an object');if(Le(e.progress),typeof e.health_info!="string")throw new o('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new o(`VP response validation failed: "last_error" must be a string if present, got ${h(e.last_error)}`)}function He(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=r;if(!Array.isArray(e.txs))throw new o('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)De(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new o('VP response validation failed: "depositor_graph" must be an object');Je(e.depositor_graph)}function v(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);he(r.tx_hex,`${e}.tx_hex`)}function De(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);const t=r;J(t.claimer_pubkey,`${e}.claimer_pubkey`),v(t.claim_tx,`${e}.claim_tx`),v(t.assert_tx,`${e}.assert_tx`),v(t.payout_tx,`${e}.payout_tx`),P(t.payout_psbt,`${e}.payout_psbt`)}function Me(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);const t=r;P(t.wots_pks_json,`${e}.wots_pks_json`),P(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function je(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);const t=r;if(J(t.challenger_pubkey,`${e}.challenger_pubkey`),v(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),v(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),v(t.nopayout_tx,`${e}.nopayout_tx`),P(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new o(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);if(t.challenge_assert_connectors.length!==q.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER)throw new o(`VP response validation failed: "${e}.challenge_assert_connectors" must have exactly ${q.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER} entries, got ${t.challenge_assert_connectors.length}`);for(let n=0;n<t.challenge_assert_connectors.length;n++)Me(t.challenge_assert_connectors[n],`${e}.challenge_assert_connectors[${n}]`);if(!Array.isArray(t.output_label_hashes))throw new o(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let n=0;n<t.output_label_hashes.length;n++)he(t.output_label_hashes[n],`${e}.output_label_hashes[${n}]`)}function fe(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=r;if(!pe(e.tx_graph_json))throw new o(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${h(e.tx_graph_json)}`);if(!R(e.verifying_key_hex))throw new o(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${h(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object"||Array.isArray(e.babe_sessions))throw new o('VP response validation failed: "babe_sessions" must be an object');const t=Object.entries(e.babe_sessions);if(t.length===0)throw new o('VP response validation failed: "babe_sessions" must contain at least one challenger entry');for(const[n,i]of t){if(J(n,`babe_sessions["${n}"]`),i===null||typeof i!="object")throw new o(`VP response validation failed: "babe_sessions.${n}" must be an object`);const s=i;if(!R(s.decryptor_artifacts_hex))throw new o(`VP response validation failed: "babe_sessions.${n}.decryptor_artifacts_hex" must be a non-empty hex string, got ${h(s.decryptor_artifacts_hex)}`)}}function Ge(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: pegout status payload is not an object");const e=r;if(!R(e.pegin_txid)||e.pegin_txid.length!==I)throw new o(`VP response validation failed: "pegin_txid" must be a ${I}-char hex string (txid), got ${h(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new o(`VP response validation failed: "found" must be a boolean, got ${h(e.found)}`);if(e.claimer!==null){if(typeof e.claimer!="object")throw new o(`VP response validation failed: "claimer" must be an object or null, got ${h(e.claimer)}`);Xe(e.claimer)}if(!Array.isArray(e.challengers))throw new o(`VP response validation failed: "challengers" must be an array, got ${h(e.challengers)}`);for(let t=0;t<e.challengers.length;t++)Ke(e.challengers[t],t)}function Xe(r){if(P(r.status,"claimer.status"),typeof r.failed!="boolean")throw new o(`VP response validation failed: "claimer.failed" must be a boolean, got ${h(r.failed)}`);if(P(r.claim_txid,"claimer.claim_txid"),P(r.claimer_pubkey,"claimer.claimer_pubkey"),P(r.assert_txid,"claimer.assert_txid"),typeof r.created_at!="number")throw new o(`VP response validation failed: "claimer.created_at" must be a number, got ${h(r.created_at)}`);if(typeof r.updated_at!="number")throw new o(`VP response validation failed: "claimer.updated_at" must be a number, got ${h(r.updated_at)}`)}function Ke(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "challengers[${e}]" must be an object, got ${h(r)}`);const t=r;if(P(t.status,`challengers[${e}].status`),P(t.claim_txid,`challengers[${e}].claim_txid`),P(t.claimer_pubkey,`challengers[${e}].claimer_pubkey`),N(t.assert_txid,`challengers[${e}].assert_txid`),N(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),N(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),N(t.nopayout_txid,`challengers[${e}].nopayout_txid`),typeof t.created_at!="number")throw new o(`VP response validation failed: "challengers[${e}].created_at" must be a number, got ${h(t.created_at)}`);if(typeof t.updated_at!="number")throw new o(`VP response validation failed: "challengers[${e}].updated_at" must be a number, got ${h(t.updated_at)}`)}function N(r,e){if(r!==null&&typeof r!="string")throw new o(`VP response validation failed: "${e}" must be a string or null, got ${h(r)}`)}function Ue(r){_e(r,"batchGetPeginStatus",e=>{e.result!==null&&ge(e.result)})}function Fe(r){_e(r,"batchGetPegoutStatus",e=>{e.result!==null&&Ge(e.result)})}function _e(r,e,t){if(r===null||typeof r!="object")throw new o(`VP response validation failed: ${e} response is not an object`);const n=r;if(!Array.isArray(n.results))throw new o(`VP response validation failed: "${e}.results" must be an array, got ${h(n.results)}`);for(let i=0;i<n.results.length;i++){const s=n.results[i];if(s===null||typeof s!="object")throw new o(`VP response validation failed: "${e}.results[${i}]" must be an object, got ${h(s)}`);const a=s;if(!R(a.pegin_txid)||a.pegin_txid.length!==I)throw new o(`VP response validation failed: "${e}.results[${i}].pegin_txid" must be a ${I}-char hex string, got ${h(a.pegin_txid)}`);if(a.error!==null&&typeof a.error!="string")throw new o(`VP response validation failed: "${e}.results[${i}].error" must be a string or null, got ${h(a.error)}`);if(a.result===null&&a.error===null)throw new o(`VP response validation failed: "${e}.results[${i}]" has neither "result" nor "error" populated`);if(a.result!==null&&a.error!==null)throw new o(`VP response validation failed: "${e}.results[${i}]" has both "result" and "error" populated`);t(a,i)}}function Je(r){if(v(r.claim_tx,"depositor_graph.claim_tx"),v(r.assert_tx,"depositor_graph.assert_tx"),v(r.payout_tx,"depositor_graph.payout_tx"),P(r.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(r.challenger_presign_data))throw new o('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<r.challenger_presign_data.length;e++)je(r.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof r.offchain_params_version!="number")throw new o('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Ye=6e4;class me{constructor(e,t){m(this,"client");const n={baseUrl:e,timeout:(t==null?void 0:t.timeout)??Ye,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,tokenProvider:t==null?void 0:t.tokenProvider,maxResponseBytes:t==null?void 0:t.maxResponseBytes};this.client=new M.JsonRpcClient(n)}async requestDepositorPresignTransactions(e,t){const n=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return He(n),n}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 n=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return fe(n),n}async getPeginStatus(e,t){const n=await this.client.call("vaultProvider_getPeginStatus",e,t);return ge(n),n}async batchGetPeginStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return Ue(n),n}async batchGetPegoutStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return Fe(n),n}}function D(r,e){const t=(r&7)<<5,n=typeof e=="bigint"?e:BigInt(e);if(n<0n)throw new Error("cborHead: negative argument");if(n<24n)return new Uint8Array([t|Number(n)]);if(n<0x100n)return new Uint8Array([t|24,Number(n)]);if(n<0x10000n){const s=Number(n);return new Uint8Array([t|25,s>>>8&255,s&255])}if(n<0x100000000n){const s=Number(n);return new Uint8Array([t|26,s>>>24&255,s>>>16&255,s>>>8&255,s&255])}const i=new Uint8Array(9);i[0]=t|27;for(let s=7;s>=0;s--)i[1+s]=Number(n>>BigInt((7-s)*8))&255;return i}function ye(...r){const e=r.reduce((i,s)=>i+s.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}function te(r){const t=[D(4,r.length)];for(const n of r)t.push(D(0,n));return ye(...t)}function qe(r,e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${t}`);const n=D(4,3),i=te(r),s=te(e),a=D(0,t);return ye(n,i,s,a)}const We=new TextEncoder().encode("btc-auth.server-identity.v1"),ze=2*3600;class b extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function L(r){const e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(r.slice(t*2,t*2+2),16);return e}function be(r){const{proof:e,pinnedServerPubkey:t,now:n}=r,i=r.maxLifetimeSecs??ze,s=_.stripHexPrefix(t).toLowerCase();if(s.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(s))throw new b(`pinnedServerPubkey must be 32-byte hex; got ${s.length} chars`,"invalid_pubkey_encoding");const a=_.stripHexPrefix(e.server_pubkey).toLowerCase();if(a.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(a))throw new b(`server_pubkey must be 32-byte hex; got ${a.length} chars`,"invalid_pubkey_encoding");if(a!==s)throw new b(`server_pubkey does not match pinned value: expected ${s}, got ${a}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new b(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(n))throw new b(`now must be a finite integer; got ${JSON.stringify(n)}`,"invalid_expires_at");if(e.expires_at<=n)throw new b(`server identity proof expired at ${e.expires_at}, now ${n}`,"expired");if(!Number.isSafeInteger(i)||i<=0)throw new b(`maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(i)}`,"invalid_max_lifetime");if(e.expires_at-n>i)throw new b(`server identity proof expires too far in the future: expires_at=${e.expires_at}, now=${n}, max lifetime=${i}s`,"expires_too_far");const c=_.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(c.length!==_.COMPRESSED_PUBKEY_HEX_LEN||!k.HEX_RE.test(c))throw new b(`ephemeral_pubkey must be 33-byte compressed hex; got ${c.length} chars`,"invalid_ephemeral_pubkey");const u=c.slice(0,2);if(u!=="02"&&u!=="03")throw new b(`ephemeral_pubkey must be compressed (prefix 02/03); got ${u}`,"invalid_ephemeral_pubkey");const d=L(c);if(!ue.isPoint(d))throw new b("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const g=_.stripHexPrefix(e.signature).toLowerCase();if(g.length!==_.SCHNORR_SIG_HEX_LEN||!k.HEX_RE.test(g))throw new b(`signature must be 64-byte Schnorr hex; got ${g.length} chars`,"invalid_signature_encoding");const w=qe(We,L(c),e.expires_at);if(!$.verifyBip322Simple(w,L(a),L(g)))throw new b("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const Qe=new Set(["vaultProvider_submitDepositorWotsKey","vaultProvider_submitDepositorPresignatures","vaultProvider_requestDepositorPresignTransactions"]),Ze=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),et=6e4,K="auth_createDepositorToken",U="auth_createDepositorTokenGrpc";function we(r,e){return new M.JsonRpcClient({baseUrl:r,timeout:et,headers:e,retryableFor:t=>t===K||t===U})}const tt=0,rt=1,j=2,nt=3,st=4,it=5,at=6,ot=7,re=24,ct=28,lt=20,ut=21,dt=22,ne=256;class A extends Error{constructor(e){super(`CBOR decode: ${e}`),this.name="CborDecodeError"}}class Pe{constructor(e){m(this,"buf");m(this,"pos",0);this.buf=e}nextByte(){if(this.pos>=this.buf.length)throw new A("unexpected end of input");return this.buf[this.pos++]}readHead(){const e=this.nextByte(),t=e>>5,n=e&31;if(n<re)return{major:t,arg:n};if(n>=ct)throw new A(`unsupported additional info ${n} (indefinite-length or reserved)`);const i=1<<n-re;let s=0n;for(let a=0;a<i;a++)s=s<<8n|BigInt(this.nextByte());if(s>BigInt(Number.MAX_SAFE_INTEGER))throw new A(`argument ${s} exceeds safe integer range`);return{major:t,arg:Number(s)}}readBytes(e){if(this.pos+e>this.buf.length)throw new A("length overruns end of input");const t=this.buf.subarray(this.pos,this.pos+e);return this.pos+=e,t}readByteString(){const e=this.readHead();if(e.major!==j)throw new A(`expected byte string (major ${j}), got major ${e.major}`);return this.readBytes(e.arg)}readValue(e=0){if(e>ne)throw new A(`nesting exceeds maximum depth ${ne}`);const t=this.readHead();switch(t.major){case tt:return t.arg;case rt:return-1-t.arg;case j:return this.readBytes(t.arg);case nt:return new TextDecoder("utf-8",{fatal:!0}).decode(this.readBytes(t.arg));case st:{const n=[];for(let i=0;i<t.arg;i++)n.push(this.readValue(e+1));return n}case it:{const n=new Map;for(let i=0;i<t.arg;i++){const s=this.readValue(e+1),a=this.readValue(e+1);n.set(s,a)}return n}case at:return{tag:t.arg,value:this.readValue(e+1)};case ot:if(t.arg===lt)return!1;if(t.arg===ut)return!0;if(t.arg===dt)return null;throw new A(`unsupported simple/float value ${t.arg}`);default:throw new A(`unsupported major type ${t.major}`)}}}function xe(r){const e=new Pe(r),t=e.readValue();if(e.pos!==r.length)throw new A("trailing bytes after top-level item");return t}const pt="vaultd-jsonrpc",ht="vaultd-grpc",se=18,F=4,ie=-47,gt=1,ae=64,ft=128,_t=96,mt=64,yt=1,bt=2,wt=3,Pt=4,xt=5,At=6,vt=7,oe=new TextEncoder().encode("Signature1");class p extends Error{constructor(e,t){super(e),this.reason=t,this.name="CwtVerificationError"}}function Et(r){const e=ce(r.expectedIssuerXOnlyPubkey,"expectedIssuerXOnlyPubkey"),t=ce(r.expectedAudienceXOnlyPubkey,"expectedAudienceXOnlyPubkey"),n=$t(r.ephemeralPubkeyHex),i=Vt(r.token),s=new Pe(i),a=s.readHead();if(a.major!==6||a.arg!==se)throw new p(`token is not a COSE Sign1 tagged value (tag ${se})`,"invalid_token_structure");const c=s.readHead();if(c.major!==4||c.arg!==F)throw new p(`COSE Sign1 must be a ${F}-element array`,"invalid_token_structure");const u=s.pos,d=s.readByteString(),g=i.subarray(u,s.pos);s.readValue();const w=s.pos,E=s.readByteString(),C=i.subarray(w,s.pos),T=s.readByteString();if(T.length!==ae)throw new p(`COSE signature must be ${ae} bytes, got ${T.length}`,"invalid_token_structure");if(s.pos!==i.length)throw new p("COSE Sign1 token has trailing bytes after the signature","invalid_token_structure");const x=Ct(d);if(x!==ie)throw new p(`unexpected COSE algorithm ${x} (expected ES256K ${ie})`,"unexpected_algorithm");const V=St(g,C),y=Se.sha256(V);if(!ue.verify(y,n,T,!0))throw new p("COSE signature does not verify against the server's ephemeral key","signature_verification_failed");const l=kt(E),S=l.audience.toLowerCase();if(S.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(S))throw new p("token `aud` is not a 32-byte x-only pubkey hex","invalid_claims");if(l.issuedAt>l.expiresAt)throw new p(`token iat (${l.issuedAt}) is after exp (${l.expiresAt})`,"invalid_claims");if(l.issuer.toLowerCase()!==e)throw new p(`token issuer does not match pinned server pubkey: expected ${e}, got ${l.issuer.toLowerCase()}`,"issuer_mismatch");if(l.subject!==r.expectedSubject)throw new p(`token subject mismatch: expected ${r.expectedSubject}, got ${l.subject}`,"subject_mismatch");if(S!==t)throw new p(`token audience does not match depositor pubkey: expected ${t}, got ${S}`,"audience_mismatch");if(l.expiresAt<=r.now)throw new p(`token expired: exp ${l.expiresAt} <= now ${r.now}`,"token_expired");if(r.responseExpiresAt!==l.expiresAt)throw new p(`response expires_at (${r.responseExpiresAt}) does not equal token exp (${l.expiresAt})`,"expiry_mismatch");if(r.serverIdentityExpiresAt<l.expiresAt)throw new p(`server identity expires (${r.serverIdentityExpiresAt}) before token exp (${l.expiresAt})`,"server_identity_expires_before_token");return{issuer:l.issuer,subject:l.subject,audience:S,expiresAt:l.expiresAt,notBefore:l.notBefore,issuedAt:l.issuedAt}}function Ct(r){if(r.length===0)throw new p("empty COSE protected header (no algorithm)","unexpected_algorithm");const e=xe(r);if(!(e instanceof Map))throw new p("COSE protected header is not a map","invalid_token_structure");const t=e.get(gt);if(typeof t!="number")throw new p("COSE protected header missing integer algorithm label","unexpected_algorithm");return t}function St(r,e){return It(Uint8Array.of(ft|F),Uint8Array.of(_t|oe.length),oe,r,Uint8Array.of(mt),e)}function kt(r){const e=xe(r);if(!(e instanceof Map))throw new p("CWT claims root is not a map","invalid_claims");if(Tt(e,vt,"cti").length===0)throw new p("token cti is empty","invalid_claims");return{issuer:G(e,yt,"iss"),subject:G(e,bt,"sub"),audience:G(e,wt,"aud"),expiresAt:X(e,Pt,"exp"),notBefore:X(e,xt,"nbf"),issuedAt:X(e,At,"iat")}}function G(r,e,t){const n=r.get(e);if(typeof n!="string")throw new p(`token claim ${t} is missing or not a text string`,"invalid_claims");return n}function Tt(r,e,t){const n=r.get(e);if(!(n instanceof Uint8Array))throw new p(`token claim ${t} is missing or not a byte string`,"invalid_claims");return n}function X(r,e,t){const n=r.get(e);if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new p(`token claim ${t} is missing or not a non-negative integer timestamp`,"invalid_claims");return n}function ce(r,e){const t=_.stripHexPrefix(r).toLowerCase();if(t.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(t))throw new p(`${e} must be 32-byte x-only hex; got ${t.length} chars`,"invalid_input");return t}function $t(r){const e=_.stripHexPrefix(r).toLowerCase(),t=e.slice(0,2);if(e.length!==_.COMPRESSED_PUBKEY_HEX_LEN||!k.HEX_RE.test(e)||t!=="02"&&t!=="03")throw new p("ephemeralPubkeyHex must be 33-byte compressed pubkey hex (prefix 02/03)","invalid_input");return _.hexToUint8Array(e)}const Rt=(()=>{const r=new Int16Array(128).fill(-1),e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";for(let t=0;t<e.length;t++)r[e.charCodeAt(t)]=t;return r})();function Vt(r){const e=r.length,t=Math.floor(e/4),n=e%4;if(n===1)throw new p("invalid base64url length","invalid_token_structure");const i=t*3+(n===0?0:n-1),s=new Uint8Array(i),a=d=>{const g=d<128?Rt[d]:-1;if(g<0)throw new p("invalid base64url character","invalid_token_structure");return g};let c=0,u=0;for(let d=0;d<t;d++){const g=a(r.charCodeAt(c++)),w=a(r.charCodeAt(c++)),E=a(r.charCodeAt(c++)),C=a(r.charCodeAt(c++));s[u++]=g<<2|w>>4,s[u++]=(w&15)<<4|E>>2,s[u++]=(E&3)<<6|C}if(n===2){const d=a(r.charCodeAt(c++)),g=a(r.charCodeAt(c++));s[u++]=d<<2|g>>4}else if(n===3){const d=a(r.charCodeAt(c++)),g=a(r.charCodeAt(c++)),w=a(r.charCodeAt(c++));s[u++]=d<<2|g>>4,s[u++]=(g&15)<<4|w>>2}return s}function It(...r){const e=r.reduce((i,s)=>i+s.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}const le=4102444800,Ot=30;class Bt{constructor(e){m(this,"client");m(this,"peginTxid");m(this,"authAnchorHex");m(this,"pinnedServerPubkey");m(this,"expectedAudienceXOnlyPubkey");m(this,"authGatedMethods");m(this,"grpcGatedMethods");m(this,"refreshSkewSecs");m(this,"now");m(this,"cachedJsonRpc",null);m(this,"inFlightJsonRpc",null);m(this,"cachedGrpc",null);m(this,"inFlightGrpc",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.expectedAudienceXOnlyPubkey=e.expectedAudienceXOnlyPubkey,this.authGatedMethods=e.authGatedMethods,this.grpcGatedMethods=e.grpcGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??Ot,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){return e===K||e===U?null:this.grpcGatedMethods.has(e)?this.getTokenForSubject("grpc"):this.authGatedMethods.has(e)?this.getTokenForSubject("jsonrpc"):null}invalidate(){this.cachedJsonRpc=null,this.cachedGrpc=null}async getTokenForSubject(e){const t=e==="grpc"?this.cachedGrpc:this.cachedJsonRpc;return t&&this.now()+this.refreshSkewSecs<t.expiresAt?t.token:(await this.acquireSingleFlight(e)).token}setClient(e){this.client=e}acquireSingleFlight(e){const t=e==="grpc"?this.inFlightGrpc:this.inFlightJsonRpc;if(t)return t;const n=e==="grpc"?U:K,i=(async()=>{try{const s=await this.client.call(n,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(be({proof:s.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof s.token!="string"||s.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof s.token})`);const a=this.now();if(!Number.isSafeInteger(s.expires_at)||s.expires_at<=a||s.expires_at>le)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(s.expires_at)}; must be a safe integer in (${a}, ${le}])`);Et({token:s.token,ephemeralPubkeyHex:s.server_identity.ephemeral_pubkey,expectedIssuerXOnlyPubkey:this.pinnedServerPubkey,expectedSubject:e==="grpc"?ht:pt,expectedAudienceXOnlyPubkey:this.expectedAudienceXOnlyPubkey,responseExpiresAt:s.expires_at,serverIdentityExpiresAt:s.server_identity.expires_at,now:a});const c={token:s.token,expiresAt:s.expires_at};return e==="grpc"?this.cachedGrpc=c:this.cachedJsonRpc=c,c}finally{e==="grpc"?this.inFlightGrpc=null:this.inFlightJsonRpc=null}})();return e==="grpc"?this.inFlightGrpc=i:this.inFlightJsonRpc=i,i}}class Ae{constructor(){m(this,"entries",new Map)}getOrCreate(e){const t=this.entries.get(e.peginTxid);if(t){if(t.authAnchorHex!==e.authAnchorHex)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to authAnchorHex ${t.authAnchorHex.slice(0,8)}…; got ${e.authAnchorHex.slice(0,8)}…`);if(t.pinnedServerPubkey!==e.pinnedServerPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to pinnedServerPubkey ${t.pinnedServerPubkey.slice(0,8)}…; got ${e.pinnedServerPubkey.slice(0,8)}…`);if(t.expectedAudienceXOnlyPubkey!==e.expectedAudienceXOnlyPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to expectedAudienceXOnlyPubkey ${t.expectedAudienceXOnlyPubkey.slice(0,8)}…; got ${e.expectedAudienceXOnlyPubkey.slice(0,8)}…`);return t.provider.setClient(e.client),t.provider}const n=new Bt({client:e.client,peginTxid:e.peginTxid,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey,authGatedMethods:Qe,grpcGatedMethods:Ze});return this.entries.set(e.peginTxid,{provider:n,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey}),n}peek(e){var t;return(t=this.entries.get(e))==null?void 0:t.provider}release(e){this.entries.delete(e)}clear(){this.entries.clear()}get size(){return this.entries.size}}const Y=new Ae;function Nt(r){var n;const e=we(r.baseUrl,(n=r.options)==null?void 0:n.headers),t=Y.getOrCreate({client:e,peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:_.processPublicKeyToXOnly(r.depositorBtcPubkey)});return new me(r.baseUrl,{...r.options,tokenProvider:t})}function Lt(r){Y.getOrCreate({client:we(r.baseUrl,r.headers),peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:_.processPublicKeyToXOnly(r.depositorBtcPubkey)})}function Ht(r,e){const t=new Set;for(const u of r)t.add(u.toLowerCase());const n=new Map,i=new Set,s=[],a=[];for(const u of e){const d=u.pegin_txid.toLowerCase();if(!t.has(d)){a.push(d);continue}if(i.has(d)){s.push(d);continue}i.add(d),n.set(d,{result:u.result,error:u.error})}const c=[];for(const u of t)i.has(u)||c.push(u);return{byTxid:n,missing:c,unexpected:a,duplicate:s}}async function Dt(r){const{items:e,getTxid:t,batchCall:n,onItem:i,onMissing:s,onDuplicate:a,onDuplicateBatch:c,onWholeBatchError:u,onUnexpected:d,batchSize:g=M.VP_BATCH_MAX_SIZE}=r;if(!Number.isInteger(g)||g<=0)throw new Error(`batchPollByProvider: batchSize must be a positive integer, got ${g}`);for(let w=0;w<e.length;w+=g){const E=e.slice(w,w+g),C=new Map,T=[];for(const y of E){const l=t(y).toLowerCase();C.set(l,y),T.push(l)}let x;try{const y=await n(T);x=Ht(T,y.results)}catch(y){u(E,y);continue}d&&x.unexpected.length>0&&d(x.unexpected);const V=new Set(x.duplicate);for(const y of V){const l=C.get(y);l&&a(l)}c&&V.size>0&&c(V.size);for(const y of x.missing){const l=C.get(y);l&&s(l)}for(const[y,l]of x.byTxid){if(V.has(y))continue;const S=C.get(y);S&&i(S,{pegin_txid:y,result:l.result,error:l.error})}}}exports.OnChainBtcVaultStatus=de;exports.ServerIdentityError=b;exports.VaultProviderRpcClient=me;exports.ViemOperationKeyReader=Re;exports.ViemProtocolParamsReader=Ve;exports.ViemUniversalChallengerReader=Oe;exports.ViemVaultKeeperReader=Ie;exports.VpResponseValidationError=o;exports.VpTokenRegistry=Ae;exports.batchPollByProvider=Dt;exports.createAuthenticatedVpClient=Nt;exports.primeVpTokenRegistry=Lt;exports.resolveProtocolAddresses=Te;exports.validateRequestDepositorClaimerArtifactsResponse=fe;exports.verifyServerIdentity=be;exports.vpTokenRegistry=Y;
2
- //# sourceMappingURL=batchPoll-REVZiE-M.cjs.map
1
+ "use strict";var ve=Object.defineProperty;var Ee=(r,e,t)=>e in r?ve(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var m=(r,e,t)=>Ee(r,typeof e!="symbol"?e+"":e,t);const O=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),f=require("./ProtocolParams.abi-CYZoV2EI.cjs"),$=require("./mempoolApi-BJN9fGEd.cjs"),_=require("./bitcoin-m84N5a8o.cjs"),M=require("./json-rpc-client-BiAmg_ho.cjs"),q=require("./constants-DU5CGcqO.cjs"),k=require("./validation-CDbOaDj7.cjs"),Ce=require("@bitcoin-js/tiny-secp256k1-asmjs"),Se=require("./sha2-DsrLC4NM.cjs");function ke(r){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const t in r)if(t!=="default"){const n=Object.getOwnPropertyDescriptor(r,t);Object.defineProperty(e,t,n.get?n:{enumerable:!0,get:()=>r[t]})}}return e.default=r,Object.freeze(e)}const ue=ke(Ce);async function Te(r,e){const[t,n]=await r.multicall({contracts:[{address:e,abi:O.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:O.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:n}}function W(r,e,t){if(r!==e)throw new Error(`${t}: multicall returned ${r} results for ${e} calls, so the results are not roster-aligned; refusing to use them`)}function $e(r,e){return{vaultProvider:r[0],vaultKeepers:r.slice(1,1+e),universalChallengers:r.slice(1+e)}}class Re{constructor(e,t){this.publicClient=e,this.contracts=t}async readAll(e,t,n,i){const s=await this.publicClient.multicall({contracts:e,allowFailure:!1});return W(s.length,1+t+n,i),$e(s,t)}async getCurrentOperationKeys(e){const t=[{address:this.contracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e.vaultProviderEthAddress]},...e.vaultKeepers.map(n=>({address:this.contracts.applicationRegistry,abi:f.ApplicationRegistryABI,functionName:"getCurrentOperationBtcKey",args:[e.applicationEntryPoint,n.ethAddress]})),...e.universalChallengers.map(n=>({address:this.contracts.protocolParams,abi:f.ProtocolParamsABI,functionName:"getCurrentOperationBtcKey",args:[n.ethAddress]}))];return this.readAll(t,e.vaultKeepers.length,e.universalChallengers.length,"getCurrentOperationKeys")}async getOperationKeysAtEpochs(e,t){const n=[{address:this.contracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getOperationBtcKeyAtEpoch",args:[e.vaultProviderEthAddress,t.vpKeyEpoch]},...e.vaultKeepers.map(i=>({address:this.contracts.applicationRegistry,abi:f.ApplicationRegistryABI,functionName:"getOperationBtcKeyAtEpochOrGenesis",args:[e.applicationEntryPoint,i.ethAddress,t.appKeeperKeyEpoch,i.btcPubKey]})),...e.universalChallengers.map(i=>({address:this.contracts.protocolParams,abi:f.ProtocolParamsABI,functionName:"getOperationBtcKeyAtEpochOrGenesis",args:[i.ethAddress,t.ucKeyEpoch,i.btcPubKey]}))];return this.readAll(n,e.vaultKeepers.length,e.universalChallengers.length,"getOperationKeysAtEpochs")}async getPayoutScriptsAtEpochs(e,t){const n=await this.publicClient.multicall({contracts:[{address:this.contracts.btcVaultRegistry,abi:O.BTCVaultRegistryABI,functionName:"getPayoutScriptAtEpoch",args:[e.vaultProviderEthAddress,t.vpKeyEpoch]},...e.vaultKeepers.map(i=>({address:this.contracts.applicationRegistry,abi:f.ApplicationRegistryABI,functionName:"getPayoutScriptAtEpoch",args:[e.applicationEntryPoint,i.ethAddress,t.appKeeperKeyEpoch]}))],allowFailure:!1});return W(n.length,1+e.vaultKeepers.length,"getPayoutScriptsAtEpochs"),{vaultProvider:n[0],vaultKeepers:[...n.slice(1)]}}}const z=65535;function B(r){return{timelockAssert:r.timelockAssert,timelockChallengeAssert:r.timelockChallengeAssert,securityCouncilKeys:[...r.securityCouncilKeys],councilQuorum:r.councilQuorum,feeRate:r.feeRate,babeTotalInstances:r.babeTotalInstances,babeInstancesToFinalize:r.babeInstancesToFinalize,minVpCommissionBps:r.minVpCommissionBps,tRefund:r.tRefund,tStale:r.tStale,minPeginFeeRate:r.minPeginFeeRate,proverCircuitVersion:r.proverCircuitVersion,minPrepeginDepth:r.minPrepeginDepth}}function Q(r){return{minimumPegInAmount:r.minimumPegInAmount,maxPegInAmount:r.maxPegInAmount,pegInAckTimeout:r.pegInAckTimeout,pegInActivationTimeout:r.pegInActivationTimeout,maxHtlcOutputCount:r.maxHtlcOutputCount,expiredPegInGraceBlocks:r.expiredPegInGraceBlocks}}function Z(r){if(r>BigInt(z))throw new Error(`timelockAssert value ${r} exceeds uint16 max (${z})`);return Number(r)}class Ve{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getTBVProtocolParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getTBVProtocolParams"}),t=Q(e);return $.validateTBVProtocolParams(t),t}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getLatestOffchainParams"}),t=B(e);return $.validateOffchainParams(t),t}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]}),n=B(t);return $.validateOffchainParams(n),n}async getLatestOffchainParamsVersion(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}),t=Number(e);return $.assertValidOffchainParamsVersion(t),t}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return Z(t.timelockAssert)}async getPeginActivationDelay(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"peginActivationDelay"});if(typeof e!="bigint")throw new Error(`Invalid peginActivationDelay from contract: must be a bigint, got ${typeof e}`);return e}async getPegInConfiguration(){const e=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getLatestOffchainParams"},{address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"},{address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"activeVaultCoreVersion"}],allowFailure:!1}),t=Q(e[0]),n=B(e[1]),i=Number(e[2]),s=Number(e[3]),a={minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,expiredPegInGraceBlocks:t.expiredPegInGraceBlocks,timelockPegin:Z(n.timelockAssert),timelockRefund:n.tRefund,minVpCommissionBps:n.minVpCommissionBps,offchainParams:n,offchainParamsVersion:i,activeVaultCoreVersion:s};return $.validatePegInConfiguration(a),a}async fetchAllOffchainParams(e){const t=await this.getLatestOffchainParamsVersion();if(t===0)return{byVersion:new Map,latestVersion:0};const n=Array.from({length:t},(c,u)=>u+1),i=n.map(c=>({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[c]})),s=await this.publicClient.multicall({contracts:i,allowFailure:!1}),a=new Map;for(let c=0;c<n.length;c++){const u=B(s[c]);try{$.validateOffchainParams(u),a.set(n[c],u)}catch(d){e==null||e(n[c],d instanceof Error?d:new Error(String(d)))}}return{byVersion:a,latestVersion:t}}}function H(r){return r.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class Ie{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultKeepersByVersion(e,t){const n=await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getVaultKeepersByVersion",args:[e,t]});return H(n)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepers",args:[e]});return H(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class Oe{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getUniversalChallengersByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getUniversalChallengersByVersion",args:[e]});return H(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getCurrentUniversalChallengers"});return H(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestUniversalChallengersVersion"})}}var de=(r=>(r[r.PENDING=0]="PENDING",r[r.VERIFIED=1]="VERIFIED",r[r.ACTIVE=2]="ACTIVE",r[r.REDEEMED=3]="REDEEMED",r[r.EXPIRED=4]="EXPIRED",r))(de||{});const ee=new Set(Object.values(M.DaemonStatus)),Be=200;function h(r){var e;return((e=JSON.stringify(r))==null?void 0:e.slice(0,Be))??"undefined"}const Ne="The vault provider returned an unexpected response. Please try again or contact support.";class o extends Error{constructor(t){super(Ne);m(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const I=64;function R(r){return typeof r=="string"&&r.length>0&&k.HEX_RE.test(r)}function pe(r){return typeof r=="string"&&r.length>0}function he(r,e){if(!R(r))throw new o(`VP response validation failed: "${e}" must be a non-empty hex string, got ${h(r)}`)}function P(r,e){if(!pe(r))throw new o(`VP response validation failed: "${e}" must be a non-empty string, got ${h(r)}`)}function J(r,e){if(!R(r)||r.length!==_.X_ONLY_PUBKEY_HEX_LEN&&r.length!==_.COMPRESSED_PUBKEY_HEX_LEN)throw new o(`VP response validation failed: "${e}" must be a ${_.X_ONLY_PUBKEY_HEX_LEN} or ${_.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${h(r)}`)}function Le(r){const e=r.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new o('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 o(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${h(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new o(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${h(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new o(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${h(t.vk_challenger_presigning_total)}`)}function ge(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: getPeginStatus response is not an object");const e=r;if(!R(e.pegin_txid)||e.pegin_txid.length!==I)throw new o(`VP response validation failed: "pegin_txid" must be a ${I}-char hex string (txid), got ${h(e.pegin_txid)}`);if(typeof e.status!="string")throw new o('VP response validation failed: "status" must be a string');if(!ee.has(e.status))throw new o(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...ee].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new o('VP response validation failed: "progress" must be an object');if(Le(e.progress),typeof e.health_info!="string")throw new o('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new o(`VP response validation failed: "last_error" must be a string if present, got ${h(e.last_error)}`)}function He(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=r;if(!Array.isArray(e.txs))throw new o('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)De(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new o('VP response validation failed: "depositor_graph" must be an object');Je(e.depositor_graph)}function v(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);he(r.tx_hex,`${e}.tx_hex`)}function De(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);const t=r;J(t.claimer_pubkey,`${e}.claimer_pubkey`),v(t.claim_tx,`${e}.claim_tx`),v(t.assert_tx,`${e}.assert_tx`),v(t.payout_tx,`${e}.payout_tx`),P(t.payout_psbt,`${e}.payout_psbt`)}function Me(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);const t=r;P(t.wots_pks_json,`${e}.wots_pks_json`),P(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function je(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);const t=r;if(J(t.challenger_pubkey,`${e}.challenger_pubkey`),v(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),v(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),v(t.nopayout_tx,`${e}.nopayout_tx`),P(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new o(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);if(t.challenge_assert_connectors.length!==q.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER)throw new o(`VP response validation failed: "${e}.challenge_assert_connectors" must have exactly ${q.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER} entries, got ${t.challenge_assert_connectors.length}`);for(let n=0;n<t.challenge_assert_connectors.length;n++)Me(t.challenge_assert_connectors[n],`${e}.challenge_assert_connectors[${n}]`);if(!Array.isArray(t.output_label_hashes))throw new o(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let n=0;n<t.output_label_hashes.length;n++)he(t.output_label_hashes[n],`${e}.output_label_hashes[${n}]`)}function fe(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=r;if(!pe(e.tx_graph_json))throw new o(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${h(e.tx_graph_json)}`);if(!R(e.verifying_key_hex))throw new o(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${h(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object"||Array.isArray(e.babe_sessions))throw new o('VP response validation failed: "babe_sessions" must be an object');const t=Object.entries(e.babe_sessions);if(t.length===0)throw new o('VP response validation failed: "babe_sessions" must contain at least one challenger entry');for(const[n,i]of t){if(J(n,`babe_sessions["${n}"]`),i===null||typeof i!="object")throw new o(`VP response validation failed: "babe_sessions.${n}" must be an object`);const s=i;if(!R(s.decryptor_artifacts_hex))throw new o(`VP response validation failed: "babe_sessions.${n}.decryptor_artifacts_hex" must be a non-empty hex string, got ${h(s.decryptor_artifacts_hex)}`)}}function Ge(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: pegout status payload is not an object");const e=r;if(!R(e.pegin_txid)||e.pegin_txid.length!==I)throw new o(`VP response validation failed: "pegin_txid" must be a ${I}-char hex string (txid), got ${h(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new o(`VP response validation failed: "found" must be a boolean, got ${h(e.found)}`);if(e.claimer!==null){if(typeof e.claimer!="object")throw new o(`VP response validation failed: "claimer" must be an object or null, got ${h(e.claimer)}`);Xe(e.claimer)}if(!Array.isArray(e.challengers))throw new o(`VP response validation failed: "challengers" must be an array, got ${h(e.challengers)}`);for(let t=0;t<e.challengers.length;t++)Ke(e.challengers[t],t)}function Xe(r){if(P(r.status,"claimer.status"),typeof r.failed!="boolean")throw new o(`VP response validation failed: "claimer.failed" must be a boolean, got ${h(r.failed)}`);if(P(r.claim_txid,"claimer.claim_txid"),P(r.claimer_pubkey,"claimer.claimer_pubkey"),P(r.assert_txid,"claimer.assert_txid"),typeof r.created_at!="number")throw new o(`VP response validation failed: "claimer.created_at" must be a number, got ${h(r.created_at)}`);if(typeof r.updated_at!="number")throw new o(`VP response validation failed: "claimer.updated_at" must be a number, got ${h(r.updated_at)}`)}function Ke(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "challengers[${e}]" must be an object, got ${h(r)}`);const t=r;if(P(t.status,`challengers[${e}].status`),P(t.claim_txid,`challengers[${e}].claim_txid`),P(t.claimer_pubkey,`challengers[${e}].claimer_pubkey`),N(t.assert_txid,`challengers[${e}].assert_txid`),N(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),N(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),N(t.nopayout_txid,`challengers[${e}].nopayout_txid`),typeof t.created_at!="number")throw new o(`VP response validation failed: "challengers[${e}].created_at" must be a number, got ${h(t.created_at)}`);if(typeof t.updated_at!="number")throw new o(`VP response validation failed: "challengers[${e}].updated_at" must be a number, got ${h(t.updated_at)}`)}function N(r,e){if(r!==null&&typeof r!="string")throw new o(`VP response validation failed: "${e}" must be a string or null, got ${h(r)}`)}function Ue(r){_e(r,"batchGetPeginStatus",e=>{e.result!==null&&ge(e.result)})}function Fe(r){_e(r,"batchGetPegoutStatus",e=>{e.result!==null&&Ge(e.result)})}function _e(r,e,t){if(r===null||typeof r!="object")throw new o(`VP response validation failed: ${e} response is not an object`);const n=r;if(!Array.isArray(n.results))throw new o(`VP response validation failed: "${e}.results" must be an array, got ${h(n.results)}`);for(let i=0;i<n.results.length;i++){const s=n.results[i];if(s===null||typeof s!="object")throw new o(`VP response validation failed: "${e}.results[${i}]" must be an object, got ${h(s)}`);const a=s;if(!R(a.pegin_txid)||a.pegin_txid.length!==I)throw new o(`VP response validation failed: "${e}.results[${i}].pegin_txid" must be a ${I}-char hex string, got ${h(a.pegin_txid)}`);if(a.error!==null&&typeof a.error!="string")throw new o(`VP response validation failed: "${e}.results[${i}].error" must be a string or null, got ${h(a.error)}`);if(a.result===null&&a.error===null)throw new o(`VP response validation failed: "${e}.results[${i}]" has neither "result" nor "error" populated`);if(a.result!==null&&a.error!==null)throw new o(`VP response validation failed: "${e}.results[${i}]" has both "result" and "error" populated`);t(a,i)}}function Je(r){if(v(r.claim_tx,"depositor_graph.claim_tx"),v(r.assert_tx,"depositor_graph.assert_tx"),v(r.payout_tx,"depositor_graph.payout_tx"),P(r.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(r.challenger_presign_data))throw new o('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<r.challenger_presign_data.length;e++)je(r.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof r.offchain_params_version!="number")throw new o('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Ye=6e4;class me{constructor(e,t){m(this,"client");const n={baseUrl:e,timeout:(t==null?void 0:t.timeout)??Ye,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,tokenProvider:t==null?void 0:t.tokenProvider,maxResponseBytes:t==null?void 0:t.maxResponseBytes};this.client=new M.JsonRpcClient(n)}async requestDepositorPresignTransactions(e,t){const n=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return He(n),n}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 n=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return fe(n),n}async getPeginStatus(e,t){const n=await this.client.call("vaultProvider_getPeginStatus",e,t);return ge(n),n}async batchGetPeginStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return Ue(n),n}async batchGetPegoutStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return Fe(n),n}}function D(r,e){const t=(r&7)<<5,n=typeof e=="bigint"?e:BigInt(e);if(n<0n)throw new Error("cborHead: negative argument");if(n<24n)return new Uint8Array([t|Number(n)]);if(n<0x100n)return new Uint8Array([t|24,Number(n)]);if(n<0x10000n){const s=Number(n);return new Uint8Array([t|25,s>>>8&255,s&255])}if(n<0x100000000n){const s=Number(n);return new Uint8Array([t|26,s>>>24&255,s>>>16&255,s>>>8&255,s&255])}const i=new Uint8Array(9);i[0]=t|27;for(let s=7;s>=0;s--)i[1+s]=Number(n>>BigInt((7-s)*8))&255;return i}function ye(...r){const e=r.reduce((i,s)=>i+s.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}function te(r){const t=[D(4,r.length)];for(const n of r)t.push(D(0,n));return ye(...t)}function qe(r,e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`encodeServerIdentityPayload: expires_at must be a non-negative safe integer, got ${t}`);const n=D(4,3),i=te(r),s=te(e),a=D(0,t);return ye(n,i,s,a)}const We=new TextEncoder().encode("btc-auth.server-identity.v1"),ze=2*3600;class b extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function L(r){const e=new Uint8Array(r.length/2);for(let t=0;t<e.length;t++)e[t]=parseInt(r.slice(t*2,t*2+2),16);return e}function be(r){const{proof:e,pinnedServerPubkey:t,now:n}=r,i=r.maxLifetimeSecs??ze,s=_.stripHexPrefix(t).toLowerCase();if(s.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(s))throw new b(`pinnedServerPubkey must be 32-byte hex; got ${s.length} chars`,"invalid_pubkey_encoding");const a=_.stripHexPrefix(e.server_pubkey).toLowerCase();if(a.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(a))throw new b(`server_pubkey must be 32-byte hex; got ${a.length} chars`,"invalid_pubkey_encoding");if(a!==s)throw new b(`server_pubkey does not match pinned value: expected ${s}, got ${a}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new b(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(n))throw new b(`now must be a finite integer; got ${JSON.stringify(n)}`,"invalid_expires_at");if(e.expires_at<=n)throw new b(`server identity proof expired at ${e.expires_at}, now ${n}`,"expired");if(!Number.isSafeInteger(i)||i<=0)throw new b(`maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(i)}`,"invalid_max_lifetime");if(e.expires_at-n>i)throw new b(`server identity proof expires too far in the future: expires_at=${e.expires_at}, now=${n}, max lifetime=${i}s`,"expires_too_far");const c=_.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(c.length!==_.COMPRESSED_PUBKEY_HEX_LEN||!k.HEX_RE.test(c))throw new b(`ephemeral_pubkey must be 33-byte compressed hex; got ${c.length} chars`,"invalid_ephemeral_pubkey");const u=c.slice(0,2);if(u!=="02"&&u!=="03")throw new b(`ephemeral_pubkey must be compressed (prefix 02/03); got ${u}`,"invalid_ephemeral_pubkey");const d=L(c);if(!ue.isPoint(d))throw new b("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const g=_.stripHexPrefix(e.signature).toLowerCase();if(g.length!==_.SCHNORR_SIG_HEX_LEN||!k.HEX_RE.test(g))throw new b(`signature must be 64-byte Schnorr hex; got ${g.length} chars`,"invalid_signature_encoding");const w=qe(We,L(c),e.expires_at);if(!$.verifyBip322Simple(w,L(a),L(g)))throw new b("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const Qe=new Set(["vaultProvider_submitDepositorWotsKey","vaultProvider_submitDepositorPresignatures","vaultProvider_requestDepositorPresignTransactions"]),Ze=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),et=6e4,K="auth_createDepositorToken",U="auth_createDepositorTokenGrpc";function we(r,e){return new M.JsonRpcClient({baseUrl:r,timeout:et,headers:e,retryableFor:t=>t===K||t===U})}const tt=0,rt=1,j=2,nt=3,st=4,it=5,at=6,ot=7,re=24,ct=28,lt=20,ut=21,dt=22,ne=256;class A extends Error{constructor(e){super(`CBOR decode: ${e}`),this.name="CborDecodeError"}}class Pe{constructor(e){m(this,"buf");m(this,"pos",0);this.buf=e}nextByte(){if(this.pos>=this.buf.length)throw new A("unexpected end of input");return this.buf[this.pos++]}readHead(){const e=this.nextByte(),t=e>>5,n=e&31;if(n<re)return{major:t,arg:n};if(n>=ct)throw new A(`unsupported additional info ${n} (indefinite-length or reserved)`);const i=1<<n-re;let s=0n;for(let a=0;a<i;a++)s=s<<8n|BigInt(this.nextByte());if(s>BigInt(Number.MAX_SAFE_INTEGER))throw new A(`argument ${s} exceeds safe integer range`);return{major:t,arg:Number(s)}}readBytes(e){if(this.pos+e>this.buf.length)throw new A("length overruns end of input");const t=this.buf.subarray(this.pos,this.pos+e);return this.pos+=e,t}readByteString(){const e=this.readHead();if(e.major!==j)throw new A(`expected byte string (major ${j}), got major ${e.major}`);return this.readBytes(e.arg)}readValue(e=0){if(e>ne)throw new A(`nesting exceeds maximum depth ${ne}`);const t=this.readHead();switch(t.major){case tt:return t.arg;case rt:return-1-t.arg;case j:return this.readBytes(t.arg);case nt:return new TextDecoder("utf-8",{fatal:!0}).decode(this.readBytes(t.arg));case st:{const n=[];for(let i=0;i<t.arg;i++)n.push(this.readValue(e+1));return n}case it:{const n=new Map;for(let i=0;i<t.arg;i++){const s=this.readValue(e+1),a=this.readValue(e+1);n.set(s,a)}return n}case at:return{tag:t.arg,value:this.readValue(e+1)};case ot:if(t.arg===lt)return!1;if(t.arg===ut)return!0;if(t.arg===dt)return null;throw new A(`unsupported simple/float value ${t.arg}`);default:throw new A(`unsupported major type ${t.major}`)}}}function xe(r){const e=new Pe(r),t=e.readValue();if(e.pos!==r.length)throw new A("trailing bytes after top-level item");return t}const pt="vaultd-jsonrpc",ht="vaultd-grpc",se=18,F=4,ie=-47,gt=1,ae=64,ft=128,_t=96,mt=64,yt=1,bt=2,wt=3,Pt=4,xt=5,At=6,vt=7,oe=new TextEncoder().encode("Signature1");class p extends Error{constructor(e,t){super(e),this.reason=t,this.name="CwtVerificationError"}}function Et(r){const e=ce(r.expectedIssuerXOnlyPubkey,"expectedIssuerXOnlyPubkey"),t=ce(r.expectedAudienceXOnlyPubkey,"expectedAudienceXOnlyPubkey"),n=$t(r.ephemeralPubkeyHex),i=Vt(r.token),s=new Pe(i),a=s.readHead();if(a.major!==6||a.arg!==se)throw new p(`token is not a COSE Sign1 tagged value (tag ${se})`,"invalid_token_structure");const c=s.readHead();if(c.major!==4||c.arg!==F)throw new p(`COSE Sign1 must be a ${F}-element array`,"invalid_token_structure");const u=s.pos,d=s.readByteString(),g=i.subarray(u,s.pos);s.readValue();const w=s.pos,E=s.readByteString(),C=i.subarray(w,s.pos),T=s.readByteString();if(T.length!==ae)throw new p(`COSE signature must be ${ae} bytes, got ${T.length}`,"invalid_token_structure");if(s.pos!==i.length)throw new p("COSE Sign1 token has trailing bytes after the signature","invalid_token_structure");const x=Ct(d);if(x!==ie)throw new p(`unexpected COSE algorithm ${x} (expected ES256K ${ie})`,"unexpected_algorithm");const V=St(g,C),y=Se.sha256(V);if(!ue.verify(y,n,T,!0))throw new p("COSE signature does not verify against the server's ephemeral key","signature_verification_failed");const l=kt(E),S=l.audience.toLowerCase();if(S.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(S))throw new p("token `aud` is not a 32-byte x-only pubkey hex","invalid_claims");if(l.issuedAt>l.expiresAt)throw new p(`token iat (${l.issuedAt}) is after exp (${l.expiresAt})`,"invalid_claims");if(l.issuer.toLowerCase()!==e)throw new p(`token issuer does not match pinned server pubkey: expected ${e}, got ${l.issuer.toLowerCase()}`,"issuer_mismatch");if(l.subject!==r.expectedSubject)throw new p(`token subject mismatch: expected ${r.expectedSubject}, got ${l.subject}`,"subject_mismatch");if(S!==t)throw new p(`token audience does not match depositor pubkey: expected ${t}, got ${S}`,"audience_mismatch");if(l.expiresAt<=r.now)throw new p(`token expired: exp ${l.expiresAt} <= now ${r.now}`,"token_expired");if(r.responseExpiresAt!==l.expiresAt)throw new p(`response expires_at (${r.responseExpiresAt}) does not equal token exp (${l.expiresAt})`,"expiry_mismatch");if(r.serverIdentityExpiresAt<l.expiresAt)throw new p(`server identity expires (${r.serverIdentityExpiresAt}) before token exp (${l.expiresAt})`,"server_identity_expires_before_token");return{issuer:l.issuer,subject:l.subject,audience:S,expiresAt:l.expiresAt,notBefore:l.notBefore,issuedAt:l.issuedAt}}function Ct(r){if(r.length===0)throw new p("empty COSE protected header (no algorithm)","unexpected_algorithm");const e=xe(r);if(!(e instanceof Map))throw new p("COSE protected header is not a map","invalid_token_structure");const t=e.get(gt);if(typeof t!="number")throw new p("COSE protected header missing integer algorithm label","unexpected_algorithm");return t}function St(r,e){return It(Uint8Array.of(ft|F),Uint8Array.of(_t|oe.length),oe,r,Uint8Array.of(mt),e)}function kt(r){const e=xe(r);if(!(e instanceof Map))throw new p("CWT claims root is not a map","invalid_claims");if(Tt(e,vt,"cti").length===0)throw new p("token cti is empty","invalid_claims");return{issuer:G(e,yt,"iss"),subject:G(e,bt,"sub"),audience:G(e,wt,"aud"),expiresAt:X(e,Pt,"exp"),notBefore:X(e,xt,"nbf"),issuedAt:X(e,At,"iat")}}function G(r,e,t){const n=r.get(e);if(typeof n!="string")throw new p(`token claim ${t} is missing or not a text string`,"invalid_claims");return n}function Tt(r,e,t){const n=r.get(e);if(!(n instanceof Uint8Array))throw new p(`token claim ${t} is missing or not a byte string`,"invalid_claims");return n}function X(r,e,t){const n=r.get(e);if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new p(`token claim ${t} is missing or not a non-negative integer timestamp`,"invalid_claims");return n}function ce(r,e){const t=_.stripHexPrefix(r).toLowerCase();if(t.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(t))throw new p(`${e} must be 32-byte x-only hex; got ${t.length} chars`,"invalid_input");return t}function $t(r){const e=_.stripHexPrefix(r).toLowerCase(),t=e.slice(0,2);if(e.length!==_.COMPRESSED_PUBKEY_HEX_LEN||!k.HEX_RE.test(e)||t!=="02"&&t!=="03")throw new p("ephemeralPubkeyHex must be 33-byte compressed pubkey hex (prefix 02/03)","invalid_input");return _.hexToUint8Array(e)}const Rt=(()=>{const r=new Int16Array(128).fill(-1),e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";for(let t=0;t<e.length;t++)r[e.charCodeAt(t)]=t;return r})();function Vt(r){const e=r.length,t=Math.floor(e/4),n=e%4;if(n===1)throw new p("invalid base64url length","invalid_token_structure");const i=t*3+(n===0?0:n-1),s=new Uint8Array(i),a=d=>{const g=d<128?Rt[d]:-1;if(g<0)throw new p("invalid base64url character","invalid_token_structure");return g};let c=0,u=0;for(let d=0;d<t;d++){const g=a(r.charCodeAt(c++)),w=a(r.charCodeAt(c++)),E=a(r.charCodeAt(c++)),C=a(r.charCodeAt(c++));s[u++]=g<<2|w>>4,s[u++]=(w&15)<<4|E>>2,s[u++]=(E&3)<<6|C}if(n===2){const d=a(r.charCodeAt(c++)),g=a(r.charCodeAt(c++));s[u++]=d<<2|g>>4}else if(n===3){const d=a(r.charCodeAt(c++)),g=a(r.charCodeAt(c++)),w=a(r.charCodeAt(c++));s[u++]=d<<2|g>>4,s[u++]=(g&15)<<4|w>>2}return s}function It(...r){const e=r.reduce((i,s)=>i+s.length,0),t=new Uint8Array(e);let n=0;for(const i of r)t.set(i,n),n+=i.length;return t}const le=4102444800,Ot=30;class Bt{constructor(e){m(this,"client");m(this,"peginTxid");m(this,"authAnchorHex");m(this,"pinnedServerPubkey");m(this,"expectedAudienceXOnlyPubkey");m(this,"authGatedMethods");m(this,"grpcGatedMethods");m(this,"refreshSkewSecs");m(this,"now");m(this,"cachedJsonRpc",null);m(this,"inFlightJsonRpc",null);m(this,"cachedGrpc",null);m(this,"inFlightGrpc",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.expectedAudienceXOnlyPubkey=e.expectedAudienceXOnlyPubkey,this.authGatedMethods=e.authGatedMethods,this.grpcGatedMethods=e.grpcGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??Ot,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){return e===K||e===U?null:this.grpcGatedMethods.has(e)?this.getTokenForSubject("grpc"):this.authGatedMethods.has(e)?this.getTokenForSubject("jsonrpc"):null}invalidate(){this.cachedJsonRpc=null,this.cachedGrpc=null}async getTokenForSubject(e){const t=e==="grpc"?this.cachedGrpc:this.cachedJsonRpc;return t&&this.now()+this.refreshSkewSecs<t.expiresAt?t.token:(await this.acquireSingleFlight(e)).token}setClient(e){this.client=e}acquireSingleFlight(e){const t=e==="grpc"?this.inFlightGrpc:this.inFlightJsonRpc;if(t)return t;const n=e==="grpc"?U:K,i=(async()=>{try{const s=await this.client.call(n,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(be({proof:s.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof s.token!="string"||s.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof s.token})`);const a=this.now();if(!Number.isSafeInteger(s.expires_at)||s.expires_at<=a||s.expires_at>le)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(s.expires_at)}; must be a safe integer in (${a}, ${le}])`);Et({token:s.token,ephemeralPubkeyHex:s.server_identity.ephemeral_pubkey,expectedIssuerXOnlyPubkey:this.pinnedServerPubkey,expectedSubject:e==="grpc"?ht:pt,expectedAudienceXOnlyPubkey:this.expectedAudienceXOnlyPubkey,responseExpiresAt:s.expires_at,serverIdentityExpiresAt:s.server_identity.expires_at,now:a});const c={token:s.token,expiresAt:s.expires_at};return e==="grpc"?this.cachedGrpc=c:this.cachedJsonRpc=c,c}finally{e==="grpc"?this.inFlightGrpc=null:this.inFlightJsonRpc=null}})();return e==="grpc"?this.inFlightGrpc=i:this.inFlightJsonRpc=i,i}}class Ae{constructor(){m(this,"entries",new Map)}getOrCreate(e){const t=this.entries.get(e.peginTxid);if(t){if(t.authAnchorHex!==e.authAnchorHex)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to authAnchorHex ${t.authAnchorHex.slice(0,8)}…; got ${e.authAnchorHex.slice(0,8)}…`);if(t.pinnedServerPubkey!==e.pinnedServerPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to pinnedServerPubkey ${t.pinnedServerPubkey.slice(0,8)}…; got ${e.pinnedServerPubkey.slice(0,8)}…`);if(t.expectedAudienceXOnlyPubkey!==e.expectedAudienceXOnlyPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to expectedAudienceXOnlyPubkey ${t.expectedAudienceXOnlyPubkey.slice(0,8)}…; got ${e.expectedAudienceXOnlyPubkey.slice(0,8)}…`);return t.provider.setClient(e.client),t.provider}const n=new Bt({client:e.client,peginTxid:e.peginTxid,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey,authGatedMethods:Qe,grpcGatedMethods:Ze});return this.entries.set(e.peginTxid,{provider:n,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey}),n}peek(e){var t;return(t=this.entries.get(e))==null?void 0:t.provider}release(e){this.entries.delete(e)}clear(){this.entries.clear()}get size(){return this.entries.size}}const Y=new Ae;function Nt(r){var n;const e=we(r.baseUrl,(n=r.options)==null?void 0:n.headers),t=Y.getOrCreate({client:e,peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:_.processPublicKeyToXOnly(r.depositorBtcPubkey)});return new me(r.baseUrl,{...r.options,tokenProvider:t})}function Lt(r){Y.getOrCreate({client:we(r.baseUrl,r.headers),peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:_.processPublicKeyToXOnly(r.depositorBtcPubkey)})}function Ht(r,e){const t=new Set;for(const u of r)t.add(u.toLowerCase());const n=new Map,i=new Set,s=[],a=[];for(const u of e){const d=u.pegin_txid.toLowerCase();if(!t.has(d)){a.push(d);continue}if(i.has(d)){s.push(d);continue}i.add(d),n.set(d,{result:u.result,error:u.error})}const c=[];for(const u of t)i.has(u)||c.push(u);return{byTxid:n,missing:c,unexpected:a,duplicate:s}}async function Dt(r){const{items:e,getTxid:t,batchCall:n,onItem:i,onMissing:s,onDuplicate:a,onDuplicateBatch:c,onWholeBatchError:u,onUnexpected:d,batchSize:g=M.VP_BATCH_MAX_SIZE}=r;if(!Number.isInteger(g)||g<=0)throw new Error(`batchPollByProvider: batchSize must be a positive integer, got ${g}`);for(let w=0;w<e.length;w+=g){const E=e.slice(w,w+g),C=new Map,T=[];for(const y of E){const l=t(y).toLowerCase();C.set(l,y),T.push(l)}let x;try{const y=await n(T);x=Ht(T,y.results)}catch(y){u(E,y);continue}d&&x.unexpected.length>0&&d(x.unexpected);const V=new Set(x.duplicate);for(const y of V){const l=C.get(y);l&&a(l)}c&&V.size>0&&c(V.size);for(const y of x.missing){const l=C.get(y);l&&s(l)}for(const[y,l]of x.byTxid){if(V.has(y))continue;const S=C.get(y);S&&i(S,{pegin_txid:y,result:l.result,error:l.error})}}}exports.OnChainBtcVaultStatus=de;exports.ServerIdentityError=b;exports.VaultProviderRpcClient=me;exports.ViemOperationKeyReader=Re;exports.ViemProtocolParamsReader=Ve;exports.ViemUniversalChallengerReader=Oe;exports.ViemVaultKeeperReader=Ie;exports.VpResponseValidationError=o;exports.VpTokenRegistry=Ae;exports.batchPollByProvider=Dt;exports.createAuthenticatedVpClient=Nt;exports.primeVpTokenRegistry=Lt;exports.resolveProtocolAddresses=Te;exports.validateRequestDepositorClaimerArtifactsResponse=fe;exports.verifyServerIdentity=be;exports.vpTokenRegistry=Y;
2
+ //# sourceMappingURL=batchPoll-C9cZ5usJ.cjs.map