@babylonlabs-io/ts-sdk 0.57.0 → 0.57.2

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 (104) hide show
  1. package/dist/{PeginManager-iDbqXsKD.cjs → PeginManager-DOmyNYT-.cjs} +2 -2
  2. package/dist/{PeginManager-iDbqXsKD.cjs.map → PeginManager-DOmyNYT-.cjs.map} +1 -1
  3. package/dist/{PeginManager-CnX3uFb0.js → PeginManager-DbMFLh-1.js} +7 -7
  4. package/dist/{PeginManager-CnX3uFb0.js.map → PeginManager-DbMFLh-1.js.map} +1 -1
  5. package/dist/{primeVpAuth-BlxUcdBf.cjs → batchPoll-D2OuUee1.cjs} +2 -2
  6. package/dist/batchPoll-D2OuUee1.cjs.map +1 -0
  7. package/dist/{primeVpAuth-DkJbvywo.js → batchPoll-X7D7OIcu.js} +162 -162
  8. package/dist/batchPoll-X7D7OIcu.js.map +1 -0
  9. package/dist/{bitcoin-B5aNKtsk.js → bitcoin-CHzNE-rS.js} +39 -35
  10. package/dist/bitcoin-CHzNE-rS.js.map +1 -0
  11. package/dist/bitcoin-Dpcfff7b.cjs +2 -0
  12. package/dist/bitcoin-Dpcfff7b.cjs.map +1 -0
  13. package/dist/buildAndBroadcastRefund-COinY4dk.cjs +2 -0
  14. package/dist/buildAndBroadcastRefund-COinY4dk.cjs.map +1 -0
  15. package/dist/{buildAndBroadcastRefund-CCb1_z24.js → buildAndBroadcastRefund-D_l93Gln.js} +491 -448
  16. package/dist/buildAndBroadcastRefund-D_l93Gln.js.map +1 -0
  17. package/dist/{challengeAssert-Cu-PtJ1g.cjs → challengeAssert-CIHykYs3.cjs} +2 -2
  18. package/dist/{challengeAssert-Cu-PtJ1g.cjs.map → challengeAssert-CIHykYs3.cjs.map} +1 -1
  19. package/dist/{challengeAssert-BVQq50su.js → challengeAssert-XeAql2fF.js} +2 -2
  20. package/dist/{challengeAssert-BVQq50su.js.map → challengeAssert-XeAql2fF.js.map} +1 -1
  21. package/dist/{deriveVaultRoot-B_gEOTD6.js → deriveVaultRoot-B5G8y6HJ.js} +2 -2
  22. package/dist/{deriveVaultRoot-B_gEOTD6.js.map → deriveVaultRoot-B5G8y6HJ.js.map} +1 -1
  23. package/dist/{deriveVaultRoot-CebLadyJ.cjs → deriveVaultRoot-DH0kEyaS.cjs} +2 -2
  24. package/dist/{deriveVaultRoot-CebLadyJ.cjs.map → deriveVaultRoot-DH0kEyaS.cjs.map} +1 -1
  25. package/dist/index.cjs +1 -1
  26. package/dist/index.js +187 -181
  27. package/dist/json-rpc-client-BiAmg_ho.cjs +2 -0
  28. package/dist/json-rpc-client-BiAmg_ho.cjs.map +1 -0
  29. package/dist/json-rpc-client-DuUARJvV.js +334 -0
  30. package/dist/json-rpc-client-DuUARJvV.js.map +1 -0
  31. package/dist/{mempoolApi-C0olk43O.js → mempoolApi-4T6J5oxg.js} +2 -2
  32. package/dist/{mempoolApi-C0olk43O.js.map → mempoolApi-4T6J5oxg.js.map} +1 -1
  33. package/dist/{mempoolApi-Dsm2VPXp.cjs → mempoolApi-BtIABIAQ.cjs} +2 -2
  34. package/dist/{mempoolApi-Dsm2VPXp.cjs.map → mempoolApi-BtIABIAQ.cjs.map} +1 -1
  35. package/dist/{noPayout-Djrv31V5.cjs → noPayout-BkXzkhU1.cjs} +2 -2
  36. package/dist/{noPayout-Djrv31V5.cjs.map → noPayout-BkXzkhU1.cjs.map} +1 -1
  37. package/dist/{noPayout-CI4l1qu2.js → noPayout-DCf1xoJn.js} +5 -5
  38. package/dist/{noPayout-CI4l1qu2.js.map → noPayout-DCf1xoJn.js.map} +1 -1
  39. package/dist/{onChainBtcPubkey-Cd9kpz-S.cjs → onChainBtcPubkey-DqYufM7j.cjs} +2 -2
  40. package/dist/{onChainBtcPubkey-Cd9kpz-S.cjs.map → onChainBtcPubkey-DqYufM7j.cjs.map} +1 -1
  41. package/dist/{onChainBtcPubkey-aPY5ib3Q.js → onChainBtcPubkey-mP95j21Z.js} +2 -2
  42. package/dist/{onChainBtcPubkey-aPY5ib3Q.js.map → onChainBtcPubkey-mP95j21Z.js.map} +1 -1
  43. package/dist/{peginInput-CAiiDZeO.cjs → peginInput-CAYuE_5F.cjs} +2 -2
  44. package/dist/{peginInput-CAiiDZeO.cjs.map → peginInput-CAYuE_5F.cjs.map} +1 -1
  45. package/dist/{peginInput-BKD_b3gq.js → peginInput-DRUm164W.js} +2 -2
  46. package/dist/{peginInput-BKD_b3gq.js.map → peginInput-DRUm164W.js.map} +1 -1
  47. package/dist/{reservation-cHDRn4DA.js → reservation-4F9XCk0v.js} +2 -2
  48. package/dist/{reservation-cHDRn4DA.js.map → reservation-4F9XCk0v.js.map} +1 -1
  49. package/dist/{reservation-ClEs2X0H.cjs → reservation-B_7tzSwY.cjs} +2 -2
  50. package/dist/{reservation-ClEs2X0H.cjs.map → reservation-B_7tzSwY.cjs.map} +1 -1
  51. package/dist/{signPsbtsWithFallback-CzZFZf0I.js → signPsbtsWithFallback-DxG_APbS.js} +3 -3
  52. package/dist/{signPsbtsWithFallback-CzZFZf0I.js.map → signPsbtsWithFallback-DxG_APbS.js.map} +1 -1
  53. package/dist/{signPsbtsWithFallback-C01N6Kdo.cjs → signPsbtsWithFallback-r3bC-CfM.cjs} +2 -2
  54. package/dist/{signPsbtsWithFallback-C01N6Kdo.cjs.map → signPsbtsWithFallback-r3bC-CfM.cjs.map} +1 -1
  55. package/dist/tbv/core/clients/index.cjs +1 -1
  56. package/dist/tbv/core/clients/index.js +28 -27
  57. package/dist/tbv/core/clients/vault-provider/index.d.ts +4 -4
  58. package/dist/tbv/core/clients/vault-provider/index.d.ts.map +1 -1
  59. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts +36 -14
  60. package/dist/tbv/core/clients/vault-provider/json-rpc-client.d.ts.map +1 -1
  61. package/dist/tbv/core/index.cjs +1 -1
  62. package/dist/tbv/core/index.js +183 -177
  63. package/dist/tbv/core/managers/index.cjs +1 -1
  64. package/dist/tbv/core/managers/index.js +2 -2
  65. package/dist/tbv/core/primitives/index.cjs +1 -1
  66. package/dist/tbv/core/primitives/index.d.ts +1 -1
  67. package/dist/tbv/core/primitives/index.d.ts.map +1 -1
  68. package/dist/tbv/core/primitives/index.js +15 -14
  69. package/dist/tbv/core/primitives/utils/bitcoin.d.ts +14 -0
  70. package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
  71. package/dist/tbv/core/services/deposit/validateOnChainParticipantKeys.d.ts.map +1 -1
  72. package/dist/tbv/core/services/index.cjs +1 -1
  73. package/dist/tbv/core/services/index.js +35 -31
  74. package/dist/tbv/core/services/participants/__tests__/indexerKeyHint.test.d.ts +9 -0
  75. package/dist/tbv/core/services/participants/__tests__/indexerKeyHint.test.d.ts.map +1 -0
  76. package/dist/tbv/core/services/participants/index.d.ts +2 -0
  77. package/dist/tbv/core/services/participants/index.d.ts.map +1 -1
  78. package/dist/tbv/core/services/participants/indexerKeyHint.d.ts +61 -0
  79. package/dist/tbv/core/services/participants/indexerKeyHint.d.ts.map +1 -0
  80. package/dist/tbv/core/utils/index.cjs +1 -1
  81. package/dist/tbv/core/utils/index.js +3 -3
  82. package/dist/tbv/core/vault-secrets/index.cjs +1 -1
  83. package/dist/tbv/core/vault-secrets/index.js +1 -1
  84. package/dist/tbv/index.cjs +1 -1
  85. package/dist/tbv/index.js +183 -177
  86. package/dist/testing/index.cjs +1 -1
  87. package/dist/testing/index.js +1 -1
  88. package/dist/{verifyScriptPathSchnorrSignature-C-84KJ6U.cjs → verifyScriptPathSchnorrSignature-fhjfNoHK.cjs} +2 -2
  89. package/dist/{verifyScriptPathSchnorrSignature-C-84KJ6U.cjs.map → verifyScriptPathSchnorrSignature-fhjfNoHK.cjs.map} +1 -1
  90. package/dist/{verifyScriptPathSchnorrSignature-Xoo9DOHW.js → verifyScriptPathSchnorrSignature-wwa1JhiB.js} +2 -2
  91. package/dist/{verifyScriptPathSchnorrSignature-Xoo9DOHW.js.map → verifyScriptPathSchnorrSignature-wwa1JhiB.js.map} +1 -1
  92. package/package.json +1 -1
  93. package/dist/bitcoin-B5aNKtsk.js.map +0 -1
  94. package/dist/bitcoin-CHfKAhcI.cjs +0 -2
  95. package/dist/bitcoin-CHfKAhcI.cjs.map +0 -1
  96. package/dist/buildAndBroadcastRefund-CCb1_z24.js.map +0 -1
  97. package/dist/buildAndBroadcastRefund-CDzzTZ2U.cjs +0 -2
  98. package/dist/buildAndBroadcastRefund-CDzzTZ2U.cjs.map +0 -1
  99. package/dist/json-rpc-client-Ehjthcd7.js +0 -324
  100. package/dist/json-rpc-client-Ehjthcd7.js.map +0 -1
  101. package/dist/json-rpc-client-fUoK-TzT.cjs +0 -2
  102. package/dist/json-rpc-client-fUoK-TzT.cjs.map +0 -1
  103. package/dist/primeVpAuth-BlxUcdBf.cjs.map +0 -1
  104. package/dist/primeVpAuth-DkJbvywo.js.map +0 -1
@@ -1,2 +1,2 @@
1
- "use strict";var ke=Object.defineProperty;var Te=(r,e,t)=>e in r?ke(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var m=(r,e,t)=>Te(r,typeof e!="symbol"?e+"":e,t);const O=require("./BTCVaultRegistry.abi-AUAyCHal.cjs"),f=require("./ProtocolParams.abi-C8U7BHCS.cjs"),I=require("./mempoolApi-Dsm2VPXp.cjs"),X=require("./json-rpc-client-fUoK-TzT.cjs"),_=require("./bitcoin-CHfKAhcI.cjs"),Q=require("./constants-BqU1Uz15.cjs"),k=require("./validation-CDbOaDj7.cjs"),$e=require("@bitcoin-js/tiny-secp256k1-asmjs"),N=require("bitcoinjs-lib"),V=require("buffer"),J=require("./sha2-DsrLC4NM.cjs");function Re(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 j=Re($e);async function Ie(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 Ve(r,e){return{vaultProvider:r[0],vaultKeepers:r.slice(1,1+e),universalChallengers:r.slice(1+e)}}class Be{constructor(e,t){this.publicClient=e,this.contracts=t}async readAll(e,t){const n=await this.publicClient.multicall({contracts:e,allowFailure:!1});return Ve(n,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)}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)}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{vaultProvider:n[0],vaultKeepers:[...n.slice(1)]}}}const ee=65535;function H(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 te(r){return{minimumPegInAmount:r.minimumPegInAmount,maxPegInAmount:r.maxPegInAmount,pegInAckTimeout:r.pegInAckTimeout,pegInActivationTimeout:r.pegInActivationTimeout,maxHtlcOutputCount:r.maxHtlcOutputCount,expiredPegInGraceBlocks:r.expiredPegInGraceBlocks}}function re(r){if(r>BigInt(ee))throw new Error(`timelockAssert value ${r} exceeds uint16 max (${ee})`);return Number(r)}class Oe{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=te(e);return I.validateTBVProtocolParams(t),t}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getLatestOffchainParams"}),t=H(e);return I.validateOffchainParams(t),t}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]}),n=H(t);return I.validateOffchainParams(n),n}async getLatestOffchainParamsVersion(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}),t=Number(e);return I.assertValidOffchainParamsVersion(t),t}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return re(t.timelockAssert)}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=te(e[0]),n=H(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:re(n.timelockAssert),timelockRefund:n.tRefund,minVpCommissionBps:n.minVpCommissionBps,offchainParams:n,offchainParamsVersion:i,activeVaultCoreVersion:s};return I.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,d)=>d+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 d=H(s[c]);try{I.validateOffchainParams(d),a.set(n[c],d)}catch(l){e==null||e(n[c],l instanceof Error?l:new Error(String(l)))}}return{byVersion:a,latestVersion:t}}}function G(r){return r.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class Ne{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 G(n)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepers",args:[e]});return G(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class He{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 G(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getCurrentUniversalChallengers"});return G(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestUniversalChallengersVersion"})}}var he=(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))(he||{});const ne=new Set(Object.values(X.DaemonStatus)),Le=200;function h(r){var e;return((e=JSON.stringify(r))==null?void 0:e.slice(0,Le))??"undefined"}const De="The vault provider returned an unexpected response. Please try again or contact support.";class o extends Error{constructor(t){super(De);m(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const B=64;function $(r){return typeof r=="string"&&r.length>0&&k.HEX_RE.test(r)}function ge(r){return typeof r=="string"&&r.length>0}function fe(r,e){if(!$(r))throw new o(`VP response validation failed: "${e}" must be a non-empty hex string, got ${h(r)}`)}function P(r,e){if(!ge(r))throw new o(`VP response validation failed: "${e}" must be a non-empty string, got ${h(r)}`)}function z(r,e){if(!$(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 Ge(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 _e(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: getPeginStatus response is not an object");const e=r;if(!$(e.pegin_txid)||e.pegin_txid.length!==B)throw new o(`VP response validation failed: "pegin_txid" must be a ${B}-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(!ne.has(e.status))throw new o(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...ne].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(Ge(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 Me(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++)Xe(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');We(e.depositor_graph)}function E(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);fe(r.tx_hex,`${e}.tx_hex`)}function Xe(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);const t=r;z(t.claimer_pubkey,`${e}.claimer_pubkey`),E(t.claim_tx,`${e}.claim_tx`),E(t.assert_tx,`${e}.assert_tx`),E(t.payout_tx,`${e}.payout_tx`),P(t.payout_psbt,`${e}.payout_psbt`)}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;P(t.wots_pks_json,`${e}.wots_pks_json`),P(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function Ke(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);const t=r;if(z(t.challenger_pubkey,`${e}.challenger_pubkey`),E(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),E(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),E(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++)je(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++)fe(t.output_label_hashes[n],`${e}.output_label_hashes[${n}]`)}function me(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=r;if(!ge(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(!$(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(z(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(!$(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 Ue(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(!$(e.pegin_txid)||e.pegin_txid.length!==B)throw new o(`VP response validation failed: "pegin_txid" must be a ${B}-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)}`);Fe(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++)Je(e.challengers[t],t)}function Fe(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 Je(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`),L(t.assert_txid,`challengers[${e}].assert_txid`),L(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),L(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),L(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 L(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 Ye(r){ye(r,"batchGetPeginStatus",e=>{e.result!==null&&_e(e.result)})}function qe(r){ye(r,"batchGetPegoutStatus",e=>{e.result!==null&&Ue(e.result)})}function ye(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(!$(a.pegin_txid)||a.pegin_txid.length!==B)throw new o(`VP response validation failed: "${e}.results[${i}].pegin_txid" must be a ${B}-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 We(r){if(E(r.claim_tx,"depositor_graph.claim_tx"),E(r.assert_tx,"depositor_graph.assert_tx"),E(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++)Ke(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 ze=6e4;class be{constructor(e,t){m(this,"client");const n={baseUrl:e,timeout:(t==null?void 0:t.timeout)??ze,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 X.JsonRpcClient(n)}async requestDepositorPresignTransactions(e,t){const n=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return Me(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 me(n),n}async getPeginStatus(e,t){const n=await this.client.call("vaultProvider_getPeginStatus",e,t);return _e(n),n}async batchGetPeginStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return Ye(n),n}async batchGetPegoutStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return qe(n),n}}function Ze(r,e){const t=new Set;for(const d of r)t.add(d.toLowerCase());const n=new Map,i=new Set,s=[],a=[];for(const d of e){const l=d.pegin_txid.toLowerCase();if(!t.has(l)){a.push(l);continue}if(i.has(l)){s.push(l);continue}i.add(l),n.set(l,{result:d.result,error:d.error})}const c=[];for(const d of t)i.has(d)||c.push(d);return{byTxid:n,missing:c,unexpected:a,duplicate:s}}async function Qe(r){const{items:e,getTxid:t,batchCall:n,onItem:i,onMissing:s,onDuplicate:a,onDuplicateBatch:c,onWholeBatchError:d,onUnexpected:l,batchSize:g=X.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 b=0;b<e.length;b+=g){const x=e.slice(b,b+g),S=new Map,T=[];for(const y of x){const u=t(y).toLowerCase();S.set(u,y),T.push(u)}let A;try{const y=await n(T);A=Ze(T,y.results)}catch(y){d(x,y);continue}l&&A.unexpected.length>0&&l(A.unexpected);const R=new Set(A.duplicate);for(const y of R){const u=S.get(y);u&&a(u)}c&&R.size>0&&c(R.size);for(const y of A.missing){const u=S.get(y);u&&s(u)}for(const[y,u]of A.byTxid){if(R.has(y))continue;const C=S.get(y);C&&i(C,{pegin_txid:y,result:u.result,error:u.error})}}}const et="BIP0322-signed-message",tt="TapTweak",we=32,rt=64;function Pe(r,e){const t=new TextEncoder().encode(r),n=J.sha256(t),i=new Uint8Array(n.length*2+e.length);return i.set(n,0),i.set(n,n.length),i.set(e,n.length*2),J.sha256(i)}function nt(r){if(r.length!==we)return null;const e=Pe(tt,r),t=j.xOnlyPointAddTweak(r,e);return t?t.xOnlyPubkey:null}function st(r,e,t){if(e.length!==we||t.length!==rt)return!1;try{const n=Pe(et,r),i=N.payments.p2tr({internalPubkey:V.Buffer.from(e)});if(!i.output)return!1;const s=i.output,a=0,c=new N.Transaction;c.version=0,c.locktime=0;const d=V.Buffer.concat([V.Buffer.from([0,32]),V.Buffer.from(n)]);c.addInput(V.Buffer.alloc(32,0),4294967295,0,d),c.addOutput(s,a);const l=new N.Transaction;l.version=0,l.locktime=0;const g=c.getHash();l.addInput(g,0,0),l.addOutput(V.Buffer.from([106]),a);const b=l.hashForWitnessV1(0,[s],[a],N.Transaction.SIGHASH_DEFAULT),x=nt(e);return x?j.verifySchnorr(b,x,t):!1}catch{return!1}}function M(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 xe(...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 se(r){const t=[M(4,r.length)];for(const n of r)t.push(M(0,n));return xe(...t)}function it(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=M(4,3),i=se(r),s=se(e),a=M(0,t);return xe(n,i,s,a)}const at=new TextEncoder().encode("btc-auth.server-identity.v1"),ot=2*3600;class w extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function D(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 Ae(r){const{proof:e,pinnedServerPubkey:t,now:n}=r,i=r.maxLifetimeSecs??ot,s=_.stripHexPrefix(t).toLowerCase();if(s.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(s))throw new w(`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 w(`server_pubkey must be 32-byte hex; got ${a.length} chars`,"invalid_pubkey_encoding");if(a!==s)throw new w(`server_pubkey does not match pinned value: expected ${s}, got ${a}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new w(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(n))throw new w(`now must be a finite integer; got ${JSON.stringify(n)}`,"invalid_expires_at");if(e.expires_at<=n)throw new w(`server identity proof expired at ${e.expires_at}, now ${n}`,"expired");if(!Number.isSafeInteger(i)||i<=0)throw new w(`maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(i)}`,"invalid_max_lifetime");if(e.expires_at-n>i)throw new w(`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 w(`ephemeral_pubkey must be 33-byte compressed hex; got ${c.length} chars`,"invalid_ephemeral_pubkey");const d=c.slice(0,2);if(d!=="02"&&d!=="03")throw new w(`ephemeral_pubkey must be compressed (prefix 02/03); got ${d}`,"invalid_ephemeral_pubkey");const l=D(c);if(!j.isPoint(l))throw new w("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 w(`signature must be 64-byte Schnorr hex; got ${g.length} chars`,"invalid_signature_encoding");const b=it(at,D(c),e.expires_at);if(!st(b,D(a),D(g)))throw new w("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const ct=new Set(["vaultProvider_submitDepositorWotsKey","vaultProvider_submitDepositorPresignatures","vaultProvider_requestDepositorPresignTransactions"]),lt=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),ut=6e4,Y="auth_createDepositorToken",q="auth_createDepositorTokenGrpc";function ve(r,e){return new X.JsonRpcClient({baseUrl:r,timeout:ut,headers:e,retryableFor:t=>t===Y||t===q})}const dt=0,pt=1,K=2,ht=3,gt=4,ft=5,_t=6,mt=7,ie=24,yt=28,bt=20,wt=21,Pt=22,ae=256;class v extends Error{constructor(e){super(`CBOR decode: ${e}`),this.name="CborDecodeError"}}class Ee{constructor(e){m(this,"buf");m(this,"pos",0);this.buf=e}nextByte(){if(this.pos>=this.buf.length)throw new v("unexpected end of input");return this.buf[this.pos++]}readHead(){const e=this.nextByte(),t=e>>5,n=e&31;if(n<ie)return{major:t,arg:n};if(n>=yt)throw new v(`unsupported additional info ${n} (indefinite-length or reserved)`);const i=1<<n-ie;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 v(`argument ${s} exceeds safe integer range`);return{major:t,arg:Number(s)}}readBytes(e){if(this.pos+e>this.buf.length)throw new v("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!==K)throw new v(`expected byte string (major ${K}), got major ${e.major}`);return this.readBytes(e.arg)}readValue(e=0){if(e>ae)throw new v(`nesting exceeds maximum depth ${ae}`);const t=this.readHead();switch(t.major){case dt:return t.arg;case pt:return-1-t.arg;case K:return this.readBytes(t.arg);case ht:return new TextDecoder("utf-8",{fatal:!0}).decode(this.readBytes(t.arg));case gt:{const n=[];for(let i=0;i<t.arg;i++)n.push(this.readValue(e+1));return n}case ft:{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 _t:return{tag:t.arg,value:this.readValue(e+1)};case mt:if(t.arg===bt)return!1;if(t.arg===wt)return!0;if(t.arg===Pt)return null;throw new v(`unsupported simple/float value ${t.arg}`);default:throw new v(`unsupported major type ${t.major}`)}}}function Se(r){const e=new Ee(r),t=e.readValue();if(e.pos!==r.length)throw new v("trailing bytes after top-level item");return t}const xt="vaultd-jsonrpc",At="vaultd-grpc",oe=18,W=4,ce=-47,vt=1,le=64,Et=128,St=96,Ct=64,kt=1,Tt=2,$t=3,Rt=4,It=5,Vt=6,Bt=7,ue=new TextEncoder().encode("Signature1");class p extends Error{constructor(e,t){super(e),this.reason=t,this.name="CwtVerificationError"}}function Ot(r){const e=de(r.expectedIssuerXOnlyPubkey,"expectedIssuerXOnlyPubkey"),t=de(r.expectedAudienceXOnlyPubkey,"expectedAudienceXOnlyPubkey"),n=Gt(r.ephemeralPubkeyHex),i=Xt(r.token),s=new Ee(i),a=s.readHead();if(a.major!==6||a.arg!==oe)throw new p(`token is not a COSE Sign1 tagged value (tag ${oe})`,"invalid_token_structure");const c=s.readHead();if(c.major!==4||c.arg!==W)throw new p(`COSE Sign1 must be a ${W}-element array`,"invalid_token_structure");const d=s.pos,l=s.readByteString(),g=i.subarray(d,s.pos);s.readValue();const b=s.pos,x=s.readByteString(),S=i.subarray(b,s.pos),T=s.readByteString();if(T.length!==le)throw new p(`COSE signature must be ${le} 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 A=Nt(l);if(A!==ce)throw new p(`unexpected COSE algorithm ${A} (expected ES256K ${ce})`,"unexpected_algorithm");const R=Ht(g,S),y=J.sha256(R);if(!j.verify(y,n,T,!0))throw new p("COSE signature does not verify against the server's ephemeral key","signature_verification_failed");const u=Lt(x),C=u.audience.toLowerCase();if(C.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(C))throw new p("token `aud` is not a 32-byte x-only pubkey hex","invalid_claims");if(u.issuedAt>u.expiresAt)throw new p(`token iat (${u.issuedAt}) is after exp (${u.expiresAt})`,"invalid_claims");if(u.issuer.toLowerCase()!==e)throw new p(`token issuer does not match pinned server pubkey: expected ${e}, got ${u.issuer.toLowerCase()}`,"issuer_mismatch");if(u.subject!==r.expectedSubject)throw new p(`token subject mismatch: expected ${r.expectedSubject}, got ${u.subject}`,"subject_mismatch");if(C!==t)throw new p(`token audience does not match depositor pubkey: expected ${t}, got ${C}`,"audience_mismatch");if(u.expiresAt<=r.now)throw new p(`token expired: exp ${u.expiresAt} <= now ${r.now}`,"token_expired");if(r.responseExpiresAt!==u.expiresAt)throw new p(`response expires_at (${r.responseExpiresAt}) does not equal token exp (${u.expiresAt})`,"expiry_mismatch");if(r.serverIdentityExpiresAt<u.expiresAt)throw new p(`server identity expires (${r.serverIdentityExpiresAt}) before token exp (${u.expiresAt})`,"server_identity_expires_before_token");return{issuer:u.issuer,subject:u.subject,audience:C,expiresAt:u.expiresAt,notBefore:u.notBefore,issuedAt:u.issuedAt}}function Nt(r){if(r.length===0)throw new p("empty COSE protected header (no algorithm)","unexpected_algorithm");const e=Se(r);if(!(e instanceof Map))throw new p("COSE protected header is not a map","invalid_token_structure");const t=e.get(vt);if(typeof t!="number")throw new p("COSE protected header missing integer algorithm label","unexpected_algorithm");return t}function Ht(r,e){return jt(Uint8Array.of(Et|W),Uint8Array.of(St|ue.length),ue,r,Uint8Array.of(Ct),e)}function Lt(r){const e=Se(r);if(!(e instanceof Map))throw new p("CWT claims root is not a map","invalid_claims");if(Dt(e,Bt,"cti").length===0)throw new p("token cti is empty","invalid_claims");return{issuer:U(e,kt,"iss"),subject:U(e,Tt,"sub"),audience:U(e,$t,"aud"),expiresAt:F(e,Rt,"exp"),notBefore:F(e,It,"nbf"),issuedAt:F(e,Vt,"iat")}}function U(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 Dt(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 F(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 de(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 Gt(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 Mt=(()=>{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 Xt(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=l=>{const g=l<128?Mt[l]:-1;if(g<0)throw new p("invalid base64url character","invalid_token_structure");return g};let c=0,d=0;for(let l=0;l<t;l++){const g=a(r.charCodeAt(c++)),b=a(r.charCodeAt(c++)),x=a(r.charCodeAt(c++)),S=a(r.charCodeAt(c++));s[d++]=g<<2|b>>4,s[d++]=(b&15)<<4|x>>2,s[d++]=(x&3)<<6|S}if(n===2){const l=a(r.charCodeAt(c++)),g=a(r.charCodeAt(c++));s[d++]=l<<2|g>>4}else if(n===3){const l=a(r.charCodeAt(c++)),g=a(r.charCodeAt(c++)),b=a(r.charCodeAt(c++));s[d++]=l<<2|g>>4,s[d++]=(g&15)<<4|b>>2}return s}function jt(...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 pe=4102444800,Kt=30;class Ut{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??Kt,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){return e===Y||e===q?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"?q:Y,i=(async()=>{try{const s=await this.client.call(n,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(Ae({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>pe)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(s.expires_at)}; must be a safe integer in (${a}, ${pe}])`);Ot({token:s.token,ephemeralPubkeyHex:s.server_identity.ephemeral_pubkey,expectedIssuerXOnlyPubkey:this.pinnedServerPubkey,expectedSubject:e==="grpc"?At:xt,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 Ce{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 Ut({client:e.client,peginTxid:e.peginTxid,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey,authGatedMethods:ct,grpcGatedMethods:lt});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 Z=new Ce;function Ft(r){var n;const e=ve(r.baseUrl,(n=r.options)==null?void 0:n.headers),t=Z.getOrCreate({client:e,peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:_.processPublicKeyToXOnly(r.depositorBtcPubkey)});return new be(r.baseUrl,{...r.options,tokenProvider:t})}function Jt(r){Z.getOrCreate({client:ve(r.baseUrl,r.headers),peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:_.processPublicKeyToXOnly(r.depositorBtcPubkey)})}exports.OnChainBtcVaultStatus=he;exports.ServerIdentityError=w;exports.VaultProviderRpcClient=be;exports.ViemOperationKeyReader=Be;exports.ViemProtocolParamsReader=Oe;exports.ViemUniversalChallengerReader=He;exports.ViemVaultKeeperReader=Ne;exports.VpResponseValidationError=o;exports.VpTokenRegistry=Ce;exports.batchPollByProvider=Qe;exports.createAuthenticatedVpClient=Ft;exports.primeVpTokenRegistry=Jt;exports.resolveProtocolAddresses=Ie;exports.validateRequestDepositorClaimerArtifactsResponse=me;exports.verifyServerIdentity=Ae;exports.vpTokenRegistry=Z;
2
- //# sourceMappingURL=primeVpAuth-BlxUcdBf.cjs.map
1
+ "use strict";var ke=Object.defineProperty;var Te=(r,e,t)=>e in r?ke(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var m=(r,e,t)=>Te(r,typeof e!="symbol"?e+"":e,t);const O=require("./BTCVaultRegistry.abi-AUAyCHal.cjs"),f=require("./ProtocolParams.abi-C8U7BHCS.cjs"),I=require("./mempoolApi-BtIABIAQ.cjs"),_=require("./bitcoin-Dpcfff7b.cjs"),X=require("./json-rpc-client-BiAmg_ho.cjs"),Q=require("./constants-BqU1Uz15.cjs"),k=require("./validation-CDbOaDj7.cjs"),$e=require("@bitcoin-js/tiny-secp256k1-asmjs"),N=require("bitcoinjs-lib"),V=require("buffer"),J=require("./sha2-DsrLC4NM.cjs");function Re(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 j=Re($e);async function Ie(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 Ve(r,e){return{vaultProvider:r[0],vaultKeepers:r.slice(1,1+e),universalChallengers:r.slice(1+e)}}class Be{constructor(e,t){this.publicClient=e,this.contracts=t}async readAll(e,t){const n=await this.publicClient.multicall({contracts:e,allowFailure:!1});return Ve(n,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)}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)}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{vaultProvider:n[0],vaultKeepers:[...n.slice(1)]}}}const ee=65535;function H(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 te(r){return{minimumPegInAmount:r.minimumPegInAmount,maxPegInAmount:r.maxPegInAmount,pegInAckTimeout:r.pegInAckTimeout,pegInActivationTimeout:r.pegInActivationTimeout,maxHtlcOutputCount:r.maxHtlcOutputCount,expiredPegInGraceBlocks:r.expiredPegInGraceBlocks}}function re(r){if(r>BigInt(ee))throw new Error(`timelockAssert value ${r} exceeds uint16 max (${ee})`);return Number(r)}class Oe{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=te(e);return I.validateTBVProtocolParams(t),t}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getLatestOffchainParams"}),t=H(e);return I.validateOffchainParams(t),t}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]}),n=H(t);return I.validateOffchainParams(n),n}async getLatestOffchainParamsVersion(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}),t=Number(e);return I.assertValidOffchainParamsVersion(t),t}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return re(t.timelockAssert)}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=te(e[0]),n=H(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:re(n.timelockAssert),timelockRefund:n.tRefund,minVpCommissionBps:n.minVpCommissionBps,offchainParams:n,offchainParamsVersion:i,activeVaultCoreVersion:s};return I.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,d)=>d+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 d=H(s[c]);try{I.validateOffchainParams(d),a.set(n[c],d)}catch(l){e==null||e(n[c],l instanceof Error?l:new Error(String(l)))}}return{byVersion:a,latestVersion:t}}}function G(r){return r.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class Ne{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 G(n)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepers",args:[e]});return G(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class He{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 G(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getCurrentUniversalChallengers"});return G(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestUniversalChallengersVersion"})}}var he=(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))(he||{});const ne=new Set(Object.values(X.DaemonStatus)),Le=200;function h(r){var e;return((e=JSON.stringify(r))==null?void 0:e.slice(0,Le))??"undefined"}const De="The vault provider returned an unexpected response. Please try again or contact support.";class o extends Error{constructor(t){super(De);m(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const B=64;function $(r){return typeof r=="string"&&r.length>0&&k.HEX_RE.test(r)}function ge(r){return typeof r=="string"&&r.length>0}function fe(r,e){if(!$(r))throw new o(`VP response validation failed: "${e}" must be a non-empty hex string, got ${h(r)}`)}function P(r,e){if(!ge(r))throw new o(`VP response validation failed: "${e}" must be a non-empty string, got ${h(r)}`)}function z(r,e){if(!$(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 Ge(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 _e(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: getPeginStatus response is not an object");const e=r;if(!$(e.pegin_txid)||e.pegin_txid.length!==B)throw new o(`VP response validation failed: "pegin_txid" must be a ${B}-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(!ne.has(e.status))throw new o(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...ne].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(Ge(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 Me(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++)Xe(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');We(e.depositor_graph)}function E(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);fe(r.tx_hex,`${e}.tx_hex`)}function Xe(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);const t=r;z(t.claimer_pubkey,`${e}.claimer_pubkey`),E(t.claim_tx,`${e}.claim_tx`),E(t.assert_tx,`${e}.assert_tx`),E(t.payout_tx,`${e}.payout_tx`),P(t.payout_psbt,`${e}.payout_psbt`)}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;P(t.wots_pks_json,`${e}.wots_pks_json`),P(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function Ke(r,e){if(r===null||typeof r!="object")throw new o(`VP response validation failed: "${e}" must be an object`);const t=r;if(z(t.challenger_pubkey,`${e}.challenger_pubkey`),E(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),E(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),E(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++)je(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++)fe(t.output_label_hashes[n],`${e}.output_label_hashes[${n}]`)}function me(r){if(r===null||typeof r!="object")throw new o("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=r;if(!ge(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(!$(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(z(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(!$(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 Ue(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(!$(e.pegin_txid)||e.pegin_txid.length!==B)throw new o(`VP response validation failed: "pegin_txid" must be a ${B}-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)}`);Fe(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++)Je(e.challengers[t],t)}function Fe(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 Je(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`),L(t.assert_txid,`challengers[${e}].assert_txid`),L(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),L(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),L(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 L(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 Ye(r){ye(r,"batchGetPeginStatus",e=>{e.result!==null&&_e(e.result)})}function qe(r){ye(r,"batchGetPegoutStatus",e=>{e.result!==null&&Ue(e.result)})}function ye(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(!$(a.pegin_txid)||a.pegin_txid.length!==B)throw new o(`VP response validation failed: "${e}.results[${i}].pegin_txid" must be a ${B}-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 We(r){if(E(r.claim_tx,"depositor_graph.claim_tx"),E(r.assert_tx,"depositor_graph.assert_tx"),E(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++)Ke(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 ze=6e4;class be{constructor(e,t){m(this,"client");const n={baseUrl:e,timeout:(t==null?void 0:t.timeout)??ze,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 X.JsonRpcClient(n)}async requestDepositorPresignTransactions(e,t){const n=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return Me(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 me(n),n}async getPeginStatus(e,t){const n=await this.client.call("vaultProvider_getPeginStatus",e,t);return _e(n),n}async batchGetPeginStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return Ye(n),n}async batchGetPegoutStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return qe(n),n}}const Ze="BIP0322-signed-message",Qe="TapTweak",we=32,et=64;function Pe(r,e){const t=new TextEncoder().encode(r),n=J.sha256(t),i=new Uint8Array(n.length*2+e.length);return i.set(n,0),i.set(n,n.length),i.set(e,n.length*2),J.sha256(i)}function tt(r){if(r.length!==we)return null;const e=Pe(Qe,r),t=j.xOnlyPointAddTweak(r,e);return t?t.xOnlyPubkey:null}function rt(r,e,t){if(e.length!==we||t.length!==et)return!1;try{const n=Pe(Ze,r),i=N.payments.p2tr({internalPubkey:V.Buffer.from(e)});if(!i.output)return!1;const s=i.output,a=0,c=new N.Transaction;c.version=0,c.locktime=0;const d=V.Buffer.concat([V.Buffer.from([0,32]),V.Buffer.from(n)]);c.addInput(V.Buffer.alloc(32,0),4294967295,0,d),c.addOutput(s,a);const l=new N.Transaction;l.version=0,l.locktime=0;const g=c.getHash();l.addInput(g,0,0),l.addOutput(V.Buffer.from([106]),a);const b=l.hashForWitnessV1(0,[s],[a],N.Transaction.SIGHASH_DEFAULT),x=tt(e);return x?j.verifySchnorr(b,x,t):!1}catch{return!1}}function M(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 xe(...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 se(r){const t=[M(4,r.length)];for(const n of r)t.push(M(0,n));return xe(...t)}function nt(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=M(4,3),i=se(r),s=se(e),a=M(0,t);return xe(n,i,s,a)}const st=new TextEncoder().encode("btc-auth.server-identity.v1"),it=2*3600;class w extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function D(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 Ae(r){const{proof:e,pinnedServerPubkey:t,now:n}=r,i=r.maxLifetimeSecs??it,s=_.stripHexPrefix(t).toLowerCase();if(s.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(s))throw new w(`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 w(`server_pubkey must be 32-byte hex; got ${a.length} chars`,"invalid_pubkey_encoding");if(a!==s)throw new w(`server_pubkey does not match pinned value: expected ${s}, got ${a}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new w(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(n))throw new w(`now must be a finite integer; got ${JSON.stringify(n)}`,"invalid_expires_at");if(e.expires_at<=n)throw new w(`server identity proof expired at ${e.expires_at}, now ${n}`,"expired");if(!Number.isSafeInteger(i)||i<=0)throw new w(`maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(i)}`,"invalid_max_lifetime");if(e.expires_at-n>i)throw new w(`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 w(`ephemeral_pubkey must be 33-byte compressed hex; got ${c.length} chars`,"invalid_ephemeral_pubkey");const d=c.slice(0,2);if(d!=="02"&&d!=="03")throw new w(`ephemeral_pubkey must be compressed (prefix 02/03); got ${d}`,"invalid_ephemeral_pubkey");const l=D(c);if(!j.isPoint(l))throw new w("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 w(`signature must be 64-byte Schnorr hex; got ${g.length} chars`,"invalid_signature_encoding");const b=nt(st,D(c),e.expires_at);if(!rt(b,D(a),D(g)))throw new w("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const at=new Set(["vaultProvider_submitDepositorWotsKey","vaultProvider_submitDepositorPresignatures","vaultProvider_requestDepositorPresignTransactions"]),ot=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),ct=6e4,Y="auth_createDepositorToken",q="auth_createDepositorTokenGrpc";function ve(r,e){return new X.JsonRpcClient({baseUrl:r,timeout:ct,headers:e,retryableFor:t=>t===Y||t===q})}const lt=0,ut=1,K=2,dt=3,pt=4,ht=5,gt=6,ft=7,ie=24,_t=28,mt=20,yt=21,bt=22,ae=256;class v extends Error{constructor(e){super(`CBOR decode: ${e}`),this.name="CborDecodeError"}}class Ee{constructor(e){m(this,"buf");m(this,"pos",0);this.buf=e}nextByte(){if(this.pos>=this.buf.length)throw new v("unexpected end of input");return this.buf[this.pos++]}readHead(){const e=this.nextByte(),t=e>>5,n=e&31;if(n<ie)return{major:t,arg:n};if(n>=_t)throw new v(`unsupported additional info ${n} (indefinite-length or reserved)`);const i=1<<n-ie;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 v(`argument ${s} exceeds safe integer range`);return{major:t,arg:Number(s)}}readBytes(e){if(this.pos+e>this.buf.length)throw new v("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!==K)throw new v(`expected byte string (major ${K}), got major ${e.major}`);return this.readBytes(e.arg)}readValue(e=0){if(e>ae)throw new v(`nesting exceeds maximum depth ${ae}`);const t=this.readHead();switch(t.major){case lt:return t.arg;case ut:return-1-t.arg;case K:return this.readBytes(t.arg);case dt:return new TextDecoder("utf-8",{fatal:!0}).decode(this.readBytes(t.arg));case pt:{const n=[];for(let i=0;i<t.arg;i++)n.push(this.readValue(e+1));return n}case ht:{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 gt:return{tag:t.arg,value:this.readValue(e+1)};case ft:if(t.arg===mt)return!1;if(t.arg===yt)return!0;if(t.arg===bt)return null;throw new v(`unsupported simple/float value ${t.arg}`);default:throw new v(`unsupported major type ${t.major}`)}}}function Se(r){const e=new Ee(r),t=e.readValue();if(e.pos!==r.length)throw new v("trailing bytes after top-level item");return t}const wt="vaultd-jsonrpc",Pt="vaultd-grpc",oe=18,W=4,ce=-47,xt=1,le=64,At=128,vt=96,Et=64,St=1,Ct=2,kt=3,Tt=4,$t=5,Rt=6,It=7,ue=new TextEncoder().encode("Signature1");class p extends Error{constructor(e,t){super(e),this.reason=t,this.name="CwtVerificationError"}}function Vt(r){const e=de(r.expectedIssuerXOnlyPubkey,"expectedIssuerXOnlyPubkey"),t=de(r.expectedAudienceXOnlyPubkey,"expectedAudienceXOnlyPubkey"),n=Lt(r.ephemeralPubkeyHex),i=Gt(r.token),s=new Ee(i),a=s.readHead();if(a.major!==6||a.arg!==oe)throw new p(`token is not a COSE Sign1 tagged value (tag ${oe})`,"invalid_token_structure");const c=s.readHead();if(c.major!==4||c.arg!==W)throw new p(`COSE Sign1 must be a ${W}-element array`,"invalid_token_structure");const d=s.pos,l=s.readByteString(),g=i.subarray(d,s.pos);s.readValue();const b=s.pos,x=s.readByteString(),S=i.subarray(b,s.pos),T=s.readByteString();if(T.length!==le)throw new p(`COSE signature must be ${le} 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 A=Bt(l);if(A!==ce)throw new p(`unexpected COSE algorithm ${A} (expected ES256K ${ce})`,"unexpected_algorithm");const R=Ot(g,S),y=J.sha256(R);if(!j.verify(y,n,T,!0))throw new p("COSE signature does not verify against the server's ephemeral key","signature_verification_failed");const u=Nt(x),C=u.audience.toLowerCase();if(C.length!==_.X_ONLY_PUBKEY_HEX_LEN||!k.HEX_RE.test(C))throw new p("token `aud` is not a 32-byte x-only pubkey hex","invalid_claims");if(u.issuedAt>u.expiresAt)throw new p(`token iat (${u.issuedAt}) is after exp (${u.expiresAt})`,"invalid_claims");if(u.issuer.toLowerCase()!==e)throw new p(`token issuer does not match pinned server pubkey: expected ${e}, got ${u.issuer.toLowerCase()}`,"issuer_mismatch");if(u.subject!==r.expectedSubject)throw new p(`token subject mismatch: expected ${r.expectedSubject}, got ${u.subject}`,"subject_mismatch");if(C!==t)throw new p(`token audience does not match depositor pubkey: expected ${t}, got ${C}`,"audience_mismatch");if(u.expiresAt<=r.now)throw new p(`token expired: exp ${u.expiresAt} <= now ${r.now}`,"token_expired");if(r.responseExpiresAt!==u.expiresAt)throw new p(`response expires_at (${r.responseExpiresAt}) does not equal token exp (${u.expiresAt})`,"expiry_mismatch");if(r.serverIdentityExpiresAt<u.expiresAt)throw new p(`server identity expires (${r.serverIdentityExpiresAt}) before token exp (${u.expiresAt})`,"server_identity_expires_before_token");return{issuer:u.issuer,subject:u.subject,audience:C,expiresAt:u.expiresAt,notBefore:u.notBefore,issuedAt:u.issuedAt}}function Bt(r){if(r.length===0)throw new p("empty COSE protected header (no algorithm)","unexpected_algorithm");const e=Se(r);if(!(e instanceof Map))throw new p("COSE protected header is not a map","invalid_token_structure");const t=e.get(xt);if(typeof t!="number")throw new p("COSE protected header missing integer algorithm label","unexpected_algorithm");return t}function Ot(r,e){return Mt(Uint8Array.of(At|W),Uint8Array.of(vt|ue.length),ue,r,Uint8Array.of(Et),e)}function Nt(r){const e=Se(r);if(!(e instanceof Map))throw new p("CWT claims root is not a map","invalid_claims");if(Ht(e,It,"cti").length===0)throw new p("token cti is empty","invalid_claims");return{issuer:U(e,St,"iss"),subject:U(e,Ct,"sub"),audience:U(e,kt,"aud"),expiresAt:F(e,Tt,"exp"),notBefore:F(e,$t,"nbf"),issuedAt:F(e,Rt,"iat")}}function U(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 Ht(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 F(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 de(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 Lt(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 Dt=(()=>{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 Gt(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=l=>{const g=l<128?Dt[l]:-1;if(g<0)throw new p("invalid base64url character","invalid_token_structure");return g};let c=0,d=0;for(let l=0;l<t;l++){const g=a(r.charCodeAt(c++)),b=a(r.charCodeAt(c++)),x=a(r.charCodeAt(c++)),S=a(r.charCodeAt(c++));s[d++]=g<<2|b>>4,s[d++]=(b&15)<<4|x>>2,s[d++]=(x&3)<<6|S}if(n===2){const l=a(r.charCodeAt(c++)),g=a(r.charCodeAt(c++));s[d++]=l<<2|g>>4}else if(n===3){const l=a(r.charCodeAt(c++)),g=a(r.charCodeAt(c++)),b=a(r.charCodeAt(c++));s[d++]=l<<2|g>>4,s[d++]=(g&15)<<4|b>>2}return s}function Mt(...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 pe=4102444800,Xt=30;class jt{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??Xt,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){return e===Y||e===q?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"?q:Y,i=(async()=>{try{const s=await this.client.call(n,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(Ae({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>pe)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(s.expires_at)}; must be a safe integer in (${a}, ${pe}])`);Vt({token:s.token,ephemeralPubkeyHex:s.server_identity.ephemeral_pubkey,expectedIssuerXOnlyPubkey:this.pinnedServerPubkey,expectedSubject:e==="grpc"?Pt:wt,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 Ce{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 jt({client:e.client,peginTxid:e.peginTxid,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,expectedAudienceXOnlyPubkey:e.expectedAudienceXOnlyPubkey,authGatedMethods:at,grpcGatedMethods:ot});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 Z=new Ce;function Kt(r){var n;const e=ve(r.baseUrl,(n=r.options)==null?void 0:n.headers),t=Z.getOrCreate({client:e,peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:_.processPublicKeyToXOnly(r.depositorBtcPubkey)});return new be(r.baseUrl,{...r.options,tokenProvider:t})}function Ut(r){Z.getOrCreate({client:ve(r.baseUrl,r.headers),peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,expectedAudienceXOnlyPubkey:_.processPublicKeyToXOnly(r.depositorBtcPubkey)})}function Ft(r,e){const t=new Set;for(const d of r)t.add(d.toLowerCase());const n=new Map,i=new Set,s=[],a=[];for(const d of e){const l=d.pegin_txid.toLowerCase();if(!t.has(l)){a.push(l);continue}if(i.has(l)){s.push(l);continue}i.add(l),n.set(l,{result:d.result,error:d.error})}const c=[];for(const d of t)i.has(d)||c.push(d);return{byTxid:n,missing:c,unexpected:a,duplicate:s}}async function Jt(r){const{items:e,getTxid:t,batchCall:n,onItem:i,onMissing:s,onDuplicate:a,onDuplicateBatch:c,onWholeBatchError:d,onUnexpected:l,batchSize:g=X.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 b=0;b<e.length;b+=g){const x=e.slice(b,b+g),S=new Map,T=[];for(const y of x){const u=t(y).toLowerCase();S.set(u,y),T.push(u)}let A;try{const y=await n(T);A=Ft(T,y.results)}catch(y){d(x,y);continue}l&&A.unexpected.length>0&&l(A.unexpected);const R=new Set(A.duplicate);for(const y of R){const u=S.get(y);u&&a(u)}c&&R.size>0&&c(R.size);for(const y of A.missing){const u=S.get(y);u&&s(u)}for(const[y,u]of A.byTxid){if(R.has(y))continue;const C=S.get(y);C&&i(C,{pegin_txid:y,result:u.result,error:u.error})}}}exports.OnChainBtcVaultStatus=he;exports.ServerIdentityError=w;exports.VaultProviderRpcClient=be;exports.ViemOperationKeyReader=Be;exports.ViemProtocolParamsReader=Oe;exports.ViemUniversalChallengerReader=He;exports.ViemVaultKeeperReader=Ne;exports.VpResponseValidationError=o;exports.VpTokenRegistry=Ce;exports.batchPollByProvider=Jt;exports.createAuthenticatedVpClient=Kt;exports.primeVpTokenRegistry=Ut;exports.resolveProtocolAddresses=Ie;exports.validateRequestDepositorClaimerArtifactsResponse=me;exports.verifyServerIdentity=Ae;exports.vpTokenRegistry=Z;
2
+ //# sourceMappingURL=batchPoll-D2OuUee1.cjs.map