@babylonlabs-io/ts-sdk 0.48.4 → 0.48.5

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 (31) hide show
  1. package/dist/{PeginManager-NfDjKQGV.cjs → PeginManager-BvxfSwsr.cjs} +2 -2
  2. package/dist/{PeginManager-NfDjKQGV.cjs.map → PeginManager-BvxfSwsr.cjs.map} +1 -1
  3. package/dist/{PeginManager-CNhDl1eC.js → PeginManager-COxRVrxa.js} +2 -2
  4. package/dist/{PeginManager-CNhDl1eC.js.map → PeginManager-COxRVrxa.js.map} +1 -1
  5. package/dist/index.cjs +1 -1
  6. package/dist/index.js +79 -78
  7. package/dist/{mempoolApi-BxT89SAq.js → mempoolApi-Dc1KSVNI.js} +61 -54
  8. package/dist/mempoolApi-Dc1KSVNI.js.map +1 -0
  9. package/dist/{mempoolApi-C_9JhjCI.cjs → mempoolApi-NMiYQAXI.cjs} +2 -2
  10. package/dist/mempoolApi-NMiYQAXI.cjs.map +1 -0
  11. package/dist/{primeVpAuth-Dzxxy0-F.js → primeVpAuth-CZsFLrHX.js} +2 -2
  12. package/dist/{primeVpAuth-Dzxxy0-F.js.map → primeVpAuth-CZsFLrHX.js.map} +1 -1
  13. package/dist/{primeVpAuth-wKbRw0m4.cjs → primeVpAuth-DhbTaCKm.cjs} +2 -2
  14. package/dist/{primeVpAuth-wKbRw0m4.cjs.map → primeVpAuth-DhbTaCKm.cjs.map} +1 -1
  15. package/dist/tbv/core/clients/index.cjs +1 -1
  16. package/dist/tbv/core/clients/index.js +33 -32
  17. package/dist/tbv/core/clients/mempool/index.d.ts +2 -2
  18. package/dist/tbv/core/clients/mempool/index.d.ts.map +1 -1
  19. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts +15 -1
  20. package/dist/tbv/core/clients/mempool/mempoolApi.d.ts.map +1 -1
  21. package/dist/tbv/core/clients/mempool/types.d.ts +20 -0
  22. package/dist/tbv/core/clients/mempool/types.d.ts.map +1 -1
  23. package/dist/tbv/core/index.cjs +1 -1
  24. package/dist/tbv/core/index.js +76 -75
  25. package/dist/tbv/core/managers/index.cjs +1 -1
  26. package/dist/tbv/core/managers/index.js +1 -1
  27. package/dist/tbv/index.cjs +1 -1
  28. package/dist/tbv/index.js +76 -75
  29. package/package.json +1 -1
  30. package/dist/mempoolApi-BxT89SAq.js.map +0 -1
  31. package/dist/mempoolApi-C_9JhjCI.cjs.map +0 -1
@@ -1,2 +1,2 @@
1
- "use strict";var fe=Object.defineProperty;var _e=(r,e,t)=>e in r?fe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e,t)=>_e(r,typeof e!="symbol"?e+"":e,t);const K=require("./BTCVaultRegistry.abi-JdeqLz4x.cjs"),f=require("./ApplicationRegistry.abi-BAPhJch3.cjs"),E=require("./mempoolApi-C_9JhjCI.cjs"),D=require("./types-WA0LrDk1.cjs"),X=require("./constants-CSG2XeD8.cjs"),m=require("./bitcoin-CHfKAhcI.cjs"),V=require("./validation-u8W7Lp2x.cjs"),me=require("@bitcoin-js/tiny-secp256k1-asmjs"),C=require("bitcoinjs-lib"),S=require("buffer"),q=require("./sha2-DsrLC4NM.cjs");function be(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 L=be(me);async function ye(r,e){const[t,n]=await r.multicall({contracts:[{address:e,abi:K.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:K.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:n}}const J=65535;function R(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 Y(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(J))throw new Error(`timelockAssert value ${r} exceeds uint16 max (${J})`);return Number(r)}class Pe{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=Y(e);return E.validateTBVProtocolParams(t),t}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getLatestOffchainParams"}),t=R(e);return E.validateOffchainParams(t),t}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]}),n=R(t);return E.validateOffchainParams(n),n}async getLatestOffchainParamsVersion(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}),t=Number(e);return E.assertValidOffchainParamsVersion(t),t}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return z(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"}],allowFailure:!1}),t=Y(e[0]),n=R(e[1]),s=Number(e[2]),i={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:s};return E.validatePegInConfiguration(i),i}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),s=n.map(c=>({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[c]})),i=await this.publicClient.multicall({contracts:s,allowFailure:!1}),o=new Map;for(let c=0;c<n.length;c++){const u=R(i[c]);try{E.validateOffchainParams(u),o.set(n[c],u)}catch(d){e==null||e(n[c],d instanceof Error?d:new Error(String(d)))}}return{byVersion:o,latestVersion:t}}}function N(r){return r.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class we{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 N(n)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepers",args:[e]});return N(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class ve{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 N(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getCurrentUniversalChallengers"});return N(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestUniversalChallengersVersion"})}}var re=(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))(re||{});const W=new Set(Object.values(D.DaemonStatus)),xe=200;function l(r){var e;return((e=JSON.stringify(r))==null?void 0:e.slice(0,xe))??"undefined"}const Ae="The vault provider returned an unexpected response. Please try again or contact support.";class a extends Error{constructor(t){super(Ae);p(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const T=64;function v(r){return typeof r=="string"&&r.length>0&&V.HEX_RE.test(r)}function ne(r){return typeof r=="string"&&r.length>0}function se(r,e){if(!v(r))throw new a(`VP response validation failed: "${e}" must be a non-empty hex string, got ${l(r)}`)}function b(r,e){if(!ne(r))throw new a(`VP response validation failed: "${e}" must be a non-empty string, got ${l(r)}`)}function U(r,e){if(!v(r)||r.length!==m.X_ONLY_PUBKEY_HEX_LEN&&r.length!==m.COMPRESSED_PUBKEY_HEX_LEN)throw new a(`VP response validation failed: "${e}" must be a ${m.X_ONLY_PUBKEY_HEX_LEN} or ${m.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${l(r)}`)}function Ee(r){const e=r.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new a('VP response validation failed: "progress.presigning" must be an object if present');const t=e;if(t.depositor_graph_created!==void 0&&typeof t.depositor_graph_created!="boolean")throw new a(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${l(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${l(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${l(t.vk_challenger_presigning_total)}`)}function ie(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: getPeginStatus response is not an object");const e=r;if(!v(e.pegin_txid)||e.pegin_txid.length!==T)throw new a(`VP response validation failed: "pegin_txid" must be a ${T}-char hex string (txid), got ${l(e.pegin_txid)}`);if(typeof e.status!="string")throw new a('VP response validation failed: "status" must be a string');if(!W.has(e.status))throw new a(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...W].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new a('VP response validation failed: "progress" must be an object');if(Ee(e.progress),typeof e.health_info!="string")throw new a('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new a(`VP response validation failed: "last_error" must be a string if present, got ${l(e.last_error)}`)}function Se(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=r;if(!Array.isArray(e.txs))throw new a('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)Te(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new a('VP response validation failed: "depositor_graph" must be an object');Ne(e.depositor_graph)}function P(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);se(r.tx_hex,`${e}.tx_hex`)}function Te(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;U(t.claimer_pubkey,`${e}.claimer_pubkey`),P(t.claim_tx,`${e}.claim_tx`),P(t.assert_tx,`${e}.assert_tx`),P(t.payout_tx,`${e}.payout_tx`),b(t.payout_psbt,`${e}.payout_psbt`)}function Ve(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;b(t.wots_pks_json,`${e}.wots_pks_json`),b(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function $e(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;if(U(t.challenger_pubkey,`${e}.challenger_pubkey`),P(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),P(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),P(t.nopayout_tx,`${e}.nopayout_tx`),b(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);if(t.challenge_assert_connectors.length!==X.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER)throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must have exactly ${X.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER} entries, got ${t.challenge_assert_connectors.length}`);for(let n=0;n<t.challenge_assert_connectors.length;n++)Ve(t.challenge_assert_connectors[n],`${e}.challenge_assert_connectors[${n}]`);if(!Array.isArray(t.output_label_hashes))throw new a(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let n=0;n<t.output_label_hashes.length;n++)se(t.output_label_hashes[n],`${e}.output_label_hashes[${n}]`)}function ae(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=r;if(!ne(e.tx_graph_json))throw new a(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${l(e.tx_graph_json)}`);if(!v(e.verifying_key_hex))throw new a(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${l(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object"||Array.isArray(e.babe_sessions))throw new a('VP response validation failed: "babe_sessions" must be an object');const t=Object.entries(e.babe_sessions);if(t.length===0)throw new a('VP response validation failed: "babe_sessions" must contain at least one challenger entry');for(const[n,s]of t){if(U(n,`babe_sessions["${n}"]`),s===null||typeof s!="object")throw new a(`VP response validation failed: "babe_sessions.${n}" must be an object`);const i=s;if(!v(i.decryptor_artifacts_hex))throw new a(`VP response validation failed: "babe_sessions.${n}.decryptor_artifacts_hex" must be a non-empty hex string, got ${l(i.decryptor_artifacts_hex)}`)}}function ke(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: pegout status payload is not an object");const e=r;if(!v(e.pegin_txid)||e.pegin_txid.length!==T)throw new a(`VP response validation failed: "pegin_txid" must be a ${T}-char hex string (txid), got ${l(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new a(`VP response validation failed: "found" must be a boolean, got ${l(e.found)}`);if(e.claimer!==null){if(typeof e.claimer!="object")throw new a(`VP response validation failed: "claimer" must be an object or null, got ${l(e.claimer)}`);Ce(e.claimer)}if(!Array.isArray(e.challengers))throw new a(`VP response validation failed: "challengers" must be an array, got ${l(e.challengers)}`);for(let t=0;t<e.challengers.length;t++)Re(e.challengers[t],t)}function Ce(r){if(b(r.status,"claimer.status"),typeof r.failed!="boolean")throw new a(`VP response validation failed: "claimer.failed" must be a boolean, got ${l(r.failed)}`);if(b(r.claim_txid,"claimer.claim_txid"),b(r.claimer_pubkey,"claimer.claimer_pubkey"),b(r.assert_txid,"claimer.assert_txid"),typeof r.created_at!="number")throw new a(`VP response validation failed: "claimer.created_at" must be a number, got ${l(r.created_at)}`);if(typeof r.updated_at!="number")throw new a(`VP response validation failed: "claimer.updated_at" must be a number, got ${l(r.updated_at)}`)}function Re(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "challengers[${e}]" must be an object, got ${l(r)}`);const t=r;if(b(t.status,`challengers[${e}].status`),b(t.claim_txid,`challengers[${e}].claim_txid`),b(t.claimer_pubkey,`challengers[${e}].claimer_pubkey`),I(t.assert_txid,`challengers[${e}].assert_txid`),I(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),I(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),I(t.nopayout_txid,`challengers[${e}].nopayout_txid`),typeof t.created_at!="number")throw new a(`VP response validation failed: "challengers[${e}].created_at" must be a number, got ${l(t.created_at)}`);if(typeof t.updated_at!="number")throw new a(`VP response validation failed: "challengers[${e}].updated_at" must be a number, got ${l(t.updated_at)}`)}function I(r,e){if(r!==null&&typeof r!="string")throw new a(`VP response validation failed: "${e}" must be a string or null, got ${l(r)}`)}function Ie(r){oe(r,"batchGetPeginStatus",e=>{e.result!==null&&ie(e.result)})}function Be(r){oe(r,"batchGetPegoutStatus",e=>{e.result!==null&&ke(e.result)})}function oe(r,e,t){if(r===null||typeof r!="object")throw new a(`VP response validation failed: ${e} response is not an object`);const n=r;if(!Array.isArray(n.results))throw new a(`VP response validation failed: "${e}.results" must be an array, got ${l(n.results)}`);for(let s=0;s<n.results.length;s++){const i=n.results[s];if(i===null||typeof i!="object")throw new a(`VP response validation failed: "${e}.results[${s}]" must be an object, got ${l(i)}`);const o=i;if(!v(o.pegin_txid)||o.pegin_txid.length!==T)throw new a(`VP response validation failed: "${e}.results[${s}].pegin_txid" must be a ${T}-char hex string, got ${l(o.pegin_txid)}`);if(o.error!==null&&typeof o.error!="string")throw new a(`VP response validation failed: "${e}.results[${s}].error" must be a string or null, got ${l(o.error)}`);if(o.result===null&&o.error===null)throw new a(`VP response validation failed: "${e}.results[${s}]" has neither "result" nor "error" populated`);if(o.result!==null&&o.error!==null)throw new a(`VP response validation failed: "${e}.results[${s}]" has both "result" and "error" populated`);t(o,s)}}function Ne(r){if(P(r.claim_tx,"depositor_graph.claim_tx"),P(r.assert_tx,"depositor_graph.assert_tx"),P(r.payout_tx,"depositor_graph.payout_tx"),b(r.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(r.challenger_presign_data))throw new a('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<r.challenger_presign_data.length;e++)$e(r.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof r.offchain_params_version!="number")throw new a('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const He=6e4;class ce{constructor(e,t){p(this,"client");const n={baseUrl:e,timeout:(t==null?void 0:t.timeout)??He,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 D.JsonRpcClient(n)}async requestDepositorPresignTransactions(e,t){const n=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return Se(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 ae(n),n}async getPeginStatus(e,t){const n=await this.client.call("vaultProvider_getPeginStatus",e,t);return ie(n),n}async batchGetPeginStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return Ie(n),n}async batchGetPegoutStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return Be(n),n}}function De(r,e){const t=new Set;for(const u of r)t.add(u.toLowerCase());const n=new Map,s=new Set,i=[],o=[];for(const u of e){const d=u.pegin_txid.toLowerCase();if(!t.has(d)){o.push(d);continue}if(s.has(d)){i.push(d);continue}s.add(d),n.set(d,{result:u.result,error:u.error})}const c=[];for(const u of t)s.has(u)||c.push(u);return{byTxid:n,missing:c,unexpected:o,duplicate:i}}async function Oe(r){const{items:e,getTxid:t,batchCall:n,onItem:s,onMissing:i,onDuplicate:o,onDuplicateBatch:c,onWholeBatchError:u,onUnexpected:d,batchSize:_=D.VP_BATCH_MAX_SIZE}=r;if(!Number.isInteger(_)||_<=0)throw new Error(`batchPollByProvider: batchSize must be a positive integer, got ${_}`);for(let w=0;w<e.length;w+=_){const x=e.slice(w,w+_),$=new Map,O=[];for(const h of x){const y=t(h).toLowerCase();$.set(y,h),O.push(y)}let A;try{const h=await n(O);A=De(O,h.results)}catch(h){u(x,h);continue}d&&A.unexpected.length>0&&d(A.unexpected);const k=new Set(A.duplicate);for(const h of k){const y=$.get(h);y&&o(y)}c&&k.size>0&&c(k.size);for(const h of A.missing){const y=$.get(h);y&&i(y)}for(const[h,y]of A.byTxid){if(k.has(h))continue;const F=$.get(h);F&&s(F,{pegin_txid:h,result:y.result,error:y.error})}}}const Ge="BIP0322-signed-message",je="TapTweak",le=32,Le=64;function ue(r,e){const t=new TextEncoder().encode(r),n=q.sha256(t),s=new Uint8Array(n.length*2+e.length);return s.set(n,0),s.set(n,n.length),s.set(e,n.length*2),q.sha256(s)}function Ue(r){if(r.length!==le)return null;const e=ue(je,r),t=L.xOnlyPointAddTweak(r,e);return t?t.xOnlyPubkey:null}function Me(r,e,t){if(e.length!==le||t.length!==Le)return!1;try{const n=ue(Ge,r),s=C.payments.p2tr({internalPubkey:S.Buffer.from(e)});if(!s.output)return!1;const i=s.output,o=0,c=new C.Transaction;c.version=0,c.locktime=0;const u=S.Buffer.concat([S.Buffer.from([0,32]),S.Buffer.from(n)]);c.addInput(S.Buffer.alloc(32,0),4294967295,0,u),c.addOutput(i,o);const d=new C.Transaction;d.version=0,d.locktime=0;const _=c.getHash();d.addInput(_,0,0),d.addOutput(S.Buffer.from([106]),o);const w=d.hashForWitnessV1(0,[i],[o],C.Transaction.SIGHASH_DEFAULT),x=Ue(e);return x?L.verifySchnorr(w,x,t):!1}catch{return!1}}function H(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 i=Number(n);return new Uint8Array([t|25,i>>>8&255,i&255])}if(n<0x100000000n){const i=Number(n);return new Uint8Array([t|26,i>>>24&255,i>>>16&255,i>>>8&255,i&255])}const s=new Uint8Array(9);s[0]=t|27;for(let i=7;i>=0;i--)s[1+i]=Number(n>>BigInt((7-i)*8))&255;return s}function de(...r){const e=r.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e);let n=0;for(const s of r)t.set(s,n),n+=s.length;return t}function Z(r){const t=[H(4,r.length)];for(const n of r)t.push(H(0,n));return de(...t)}function Fe(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=H(4,3),s=Z(r),i=Z(e),o=H(0,t);return de(n,s,i,o)}const Ke=new TextEncoder().encode("btc-auth.server-identity.v1"),Xe=2*3600;class g extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function B(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 pe(r){const{proof:e,pinnedServerPubkey:t,now:n}=r,s=r.maxLifetimeSecs??Xe,i=m.stripHexPrefix(t).toLowerCase();if(i.length!==m.X_ONLY_PUBKEY_HEX_LEN||!V.HEX_RE.test(i))throw new g(`pinnedServerPubkey must be 32-byte hex; got ${i.length} chars`,"invalid_pubkey_encoding");const o=m.stripHexPrefix(e.server_pubkey).toLowerCase();if(o.length!==m.X_ONLY_PUBKEY_HEX_LEN||!V.HEX_RE.test(o))throw new g(`server_pubkey must be 32-byte hex; got ${o.length} chars`,"invalid_pubkey_encoding");if(o!==i)throw new g(`server_pubkey does not match pinned value: expected ${i}, got ${o}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new g(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(n))throw new g(`now must be a finite integer; got ${JSON.stringify(n)}`,"invalid_expires_at");if(e.expires_at<=n)throw new g(`server identity proof expired at ${e.expires_at}, now ${n}`,"expired");if(!Number.isSafeInteger(s)||s<=0)throw new g(`maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(s)}`,"invalid_max_lifetime");if(e.expires_at-n>s)throw new g(`server identity proof expires too far in the future: expires_at=${e.expires_at}, now=${n}, max lifetime=${s}s`,"expires_too_far");const c=m.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(c.length!==m.COMPRESSED_PUBKEY_HEX_LEN||!V.HEX_RE.test(c))throw new g(`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 g(`ephemeral_pubkey must be compressed (prefix 02/03); got ${u}`,"invalid_ephemeral_pubkey");const d=B(c);if(!L.isPoint(d))throw new g("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const _=m.stripHexPrefix(e.signature).toLowerCase();if(_.length!==m.SCHNORR_SIG_HEX_LEN||!V.HEX_RE.test(_))throw new g(`signature must be 64-byte Schnorr hex; got ${_.length} chars`,"invalid_signature_encoding");const w=Fe(Ke,B(c),e.expires_at);if(!Me(w,B(o),B(_)))throw new g("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const Q=new Set(["vaultProvider_submitDepositorWotsKey","vaultProvider_submitDepositorPresignatures","vaultProvider_requestDepositorPresignTransactions"]),ee=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),qe=6e4,G="auth_createDepositorToken",j="auth_createDepositorTokenGrpc";function he(r,e){return new D.JsonRpcClient({baseUrl:r,timeout:qe,headers:e,retryableFor:t=>t===G||t===j})}const te=4102444800,Je=30;class Ye{constructor(e){p(this,"client");p(this,"peginTxid");p(this,"authAnchorHex");p(this,"pinnedServerPubkey");p(this,"authGatedMethods");p(this,"grpcGatedMethods");p(this,"refreshSkewSecs");p(this,"now");p(this,"cachedJsonRpc",null);p(this,"inFlightJsonRpc",null);p(this,"cachedGrpc",null);p(this,"inFlightGrpc",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.authGatedMethods=e.authGatedMethods,this.grpcGatedMethods=e.grpcGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??Je,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){return e===G||e===j?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"?j:G,s=(async()=>{try{const i=await this.client.call(n,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(pe({proof:i.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof i.token!="string"||i.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof i.token})`);const o=this.now();if(!Number.isSafeInteger(i.expires_at)||i.expires_at<=o||i.expires_at>te)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(i.expires_at)}; must be a safe integer in (${o}, ${te}])`);const c={token:i.token,expiresAt:i.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=s:this.inFlightJsonRpc=s,s}}class ge{constructor(){p(this,"entries",new Map)}getOrCreate(e){const t=e.enableGrpcArtifactAuth??!1,n=this.entries.get(e.peginTxid);if(n){if(n.authAnchorHex!==e.authAnchorHex)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to authAnchorHex ${n.authAnchorHex.slice(0,8)}…; got ${e.authAnchorHex.slice(0,8)}…`);if(n.pinnedServerPubkey!==e.pinnedServerPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to pinnedServerPubkey ${n.pinnedServerPubkey.slice(0,8)}…; got ${e.pinnedServerPubkey.slice(0,8)}…`);if(n.enableGrpcArtifactAuth!==t)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to enableGrpcArtifactAuth=${n.enableGrpcArtifactAuth}; got ${t}`);return n.provider.setClient(e.client),n.provider}const s=new Ye({client:e.client,peginTxid:e.peginTxid,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,authGatedMethods:t?Q:new Set([...Q,...ee]),grpcGatedMethods:t?ee:new Set});return this.entries.set(e.peginTxid,{provider:s,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,enableGrpcArtifactAuth:t}),s}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 M=new ge;function ze(r){var n;const e=he(r.baseUrl,(n=r.options)==null?void 0:n.headers),t=M.getOrCreate({client:e,peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,enableGrpcArtifactAuth:r.enableGrpcArtifactAuth});return new ce(r.baseUrl,{...r.options,tokenProvider:t})}function We(r){M.getOrCreate({client:he(r.baseUrl,r.headers),peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,enableGrpcArtifactAuth:r.enableGrpcArtifactAuth})}exports.OnChainBtcVaultStatus=re;exports.ServerIdentityError=g;exports.VaultProviderRpcClient=ce;exports.ViemProtocolParamsReader=Pe;exports.ViemUniversalChallengerReader=ve;exports.ViemVaultKeeperReader=we;exports.VpResponseValidationError=a;exports.VpTokenRegistry=ge;exports.batchPollByProvider=Oe;exports.createAuthenticatedVpClient=ze;exports.primeVpTokenRegistry=We;exports.resolveProtocolAddresses=ye;exports.validateRequestDepositorClaimerArtifactsResponse=ae;exports.verifyServerIdentity=pe;exports.vpTokenRegistry=M;
2
- //# sourceMappingURL=primeVpAuth-wKbRw0m4.cjs.map
1
+ "use strict";var fe=Object.defineProperty;var _e=(r,e,t)=>e in r?fe(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e,t)=>_e(r,typeof e!="symbol"?e+"":e,t);const K=require("./BTCVaultRegistry.abi-JdeqLz4x.cjs"),f=require("./ApplicationRegistry.abi-BAPhJch3.cjs"),E=require("./mempoolApi-NMiYQAXI.cjs"),D=require("./types-WA0LrDk1.cjs"),X=require("./constants-CSG2XeD8.cjs"),m=require("./bitcoin-CHfKAhcI.cjs"),V=require("./validation-u8W7Lp2x.cjs"),me=require("@bitcoin-js/tiny-secp256k1-asmjs"),C=require("bitcoinjs-lib"),S=require("buffer"),q=require("./sha2-DsrLC4NM.cjs");function be(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 L=be(me);async function ye(r,e){const[t,n]=await r.multicall({contracts:[{address:e,abi:K.BTCVaultRegistryABI,functionName:"protocolParams"},{address:e,abi:K.BTCVaultRegistryABI,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:n}}const J=65535;function R(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 Y(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(J))throw new Error(`timelockAssert value ${r} exceeds uint16 max (${J})`);return Number(r)}class Pe{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=Y(e);return E.validateTBVProtocolParams(t),t}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getLatestOffchainParams"}),t=R(e);return E.validateOffchainParams(t),t}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[e]}),n=R(t);return E.validateOffchainParams(n),n}async getLatestOffchainParamsVersion(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestOffchainParamsVersion"}),t=Number(e);return E.assertValidOffchainParamsVersion(t),t}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return z(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"}],allowFailure:!1}),t=Y(e[0]),n=R(e[1]),s=Number(e[2]),i={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:s};return E.validatePegInConfiguration(i),i}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),s=n.map(c=>({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getOffchainParamsByVersion",args:[c]})),i=await this.publicClient.multicall({contracts:s,allowFailure:!1}),o=new Map;for(let c=0;c<n.length;c++){const u=R(i[c]);try{E.validateOffchainParams(u),o.set(n[c],u)}catch(d){e==null||e(n[c],d instanceof Error?d:new Error(String(d)))}}return{byVersion:o,latestVersion:t}}}function N(r){return r.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class we{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 N(n)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepers",args:[e]});return N(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ApplicationRegistryABI,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class ve{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 N(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"getCurrentUniversalChallengers"});return N(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:f.ProtocolParamsABI,functionName:"latestUniversalChallengersVersion"})}}var re=(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))(re||{});const W=new Set(Object.values(D.DaemonStatus)),xe=200;function l(r){var e;return((e=JSON.stringify(r))==null?void 0:e.slice(0,xe))??"undefined"}const Ae="The vault provider returned an unexpected response. Please try again or contact support.";class a extends Error{constructor(t){super(Ae);p(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const T=64;function v(r){return typeof r=="string"&&r.length>0&&V.HEX_RE.test(r)}function ne(r){return typeof r=="string"&&r.length>0}function se(r,e){if(!v(r))throw new a(`VP response validation failed: "${e}" must be a non-empty hex string, got ${l(r)}`)}function b(r,e){if(!ne(r))throw new a(`VP response validation failed: "${e}" must be a non-empty string, got ${l(r)}`)}function U(r,e){if(!v(r)||r.length!==m.X_ONLY_PUBKEY_HEX_LEN&&r.length!==m.COMPRESSED_PUBKEY_HEX_LEN)throw new a(`VP response validation failed: "${e}" must be a ${m.X_ONLY_PUBKEY_HEX_LEN} or ${m.COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${l(r)}`)}function Ee(r){const e=r.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new a('VP response validation failed: "progress.presigning" must be an object if present');const t=e;if(t.depositor_graph_created!==void 0&&typeof t.depositor_graph_created!="boolean")throw new a(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${l(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${l(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${l(t.vk_challenger_presigning_total)}`)}function ie(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: getPeginStatus response is not an object");const e=r;if(!v(e.pegin_txid)||e.pegin_txid.length!==T)throw new a(`VP response validation failed: "pegin_txid" must be a ${T}-char hex string (txid), got ${l(e.pegin_txid)}`);if(typeof e.status!="string")throw new a('VP response validation failed: "status" must be a string');if(!W.has(e.status))throw new a(`VP response validation failed: unrecognized status "${e.status}". Expected one of: ${[...W].join(", ")}`);if(e.progress===null||typeof e.progress!="object"||Array.isArray(e.progress))throw new a('VP response validation failed: "progress" must be an object');if(Ee(e.progress),typeof e.health_info!="string")throw new a('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new a(`VP response validation failed: "last_error" must be a string if present, got ${l(e.last_error)}`)}function Se(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=r;if(!Array.isArray(e.txs))throw new a('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)Te(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new a('VP response validation failed: "depositor_graph" must be an object');Ne(e.depositor_graph)}function P(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);se(r.tx_hex,`${e}.tx_hex`)}function Te(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;U(t.claimer_pubkey,`${e}.claimer_pubkey`),P(t.claim_tx,`${e}.claim_tx`),P(t.assert_tx,`${e}.assert_tx`),P(t.payout_tx,`${e}.payout_tx`),b(t.payout_psbt,`${e}.payout_psbt`)}function Ve(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;b(t.wots_pks_json,`${e}.wots_pks_json`),b(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function $e(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "${e}" must be an object`);const t=r;if(U(t.challenger_pubkey,`${e}.challenger_pubkey`),P(t.challenge_assert_x_tx,`${e}.challenge_assert_x_tx`),P(t.challenge_assert_y_tx,`${e}.challenge_assert_y_tx`),P(t.nopayout_tx,`${e}.nopayout_tx`),b(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);if(t.challenge_assert_connectors.length!==X.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER)throw new a(`VP response validation failed: "${e}.challenge_assert_connectors" must have exactly ${X.CHALLENGE_ASSERT_CONNECTORS_PER_CHALLENGER} entries, got ${t.challenge_assert_connectors.length}`);for(let n=0;n<t.challenge_assert_connectors.length;n++)Ve(t.challenge_assert_connectors[n],`${e}.challenge_assert_connectors[${n}]`);if(!Array.isArray(t.output_label_hashes))throw new a(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let n=0;n<t.output_label_hashes.length;n++)se(t.output_label_hashes[n],`${e}.output_label_hashes[${n}]`)}function ae(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=r;if(!ne(e.tx_graph_json))throw new a(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${l(e.tx_graph_json)}`);if(!v(e.verifying_key_hex))throw new a(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${l(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object"||Array.isArray(e.babe_sessions))throw new a('VP response validation failed: "babe_sessions" must be an object');const t=Object.entries(e.babe_sessions);if(t.length===0)throw new a('VP response validation failed: "babe_sessions" must contain at least one challenger entry');for(const[n,s]of t){if(U(n,`babe_sessions["${n}"]`),s===null||typeof s!="object")throw new a(`VP response validation failed: "babe_sessions.${n}" must be an object`);const i=s;if(!v(i.decryptor_artifacts_hex))throw new a(`VP response validation failed: "babe_sessions.${n}.decryptor_artifacts_hex" must be a non-empty hex string, got ${l(i.decryptor_artifacts_hex)}`)}}function ke(r){if(r===null||typeof r!="object")throw new a("VP response validation failed: pegout status payload is not an object");const e=r;if(!v(e.pegin_txid)||e.pegin_txid.length!==T)throw new a(`VP response validation failed: "pegin_txid" must be a ${T}-char hex string (txid), got ${l(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new a(`VP response validation failed: "found" must be a boolean, got ${l(e.found)}`);if(e.claimer!==null){if(typeof e.claimer!="object")throw new a(`VP response validation failed: "claimer" must be an object or null, got ${l(e.claimer)}`);Ce(e.claimer)}if(!Array.isArray(e.challengers))throw new a(`VP response validation failed: "challengers" must be an array, got ${l(e.challengers)}`);for(let t=0;t<e.challengers.length;t++)Re(e.challengers[t],t)}function Ce(r){if(b(r.status,"claimer.status"),typeof r.failed!="boolean")throw new a(`VP response validation failed: "claimer.failed" must be a boolean, got ${l(r.failed)}`);if(b(r.claim_txid,"claimer.claim_txid"),b(r.claimer_pubkey,"claimer.claimer_pubkey"),b(r.assert_txid,"claimer.assert_txid"),typeof r.created_at!="number")throw new a(`VP response validation failed: "claimer.created_at" must be a number, got ${l(r.created_at)}`);if(typeof r.updated_at!="number")throw new a(`VP response validation failed: "claimer.updated_at" must be a number, got ${l(r.updated_at)}`)}function Re(r,e){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "challengers[${e}]" must be an object, got ${l(r)}`);const t=r;if(b(t.status,`challengers[${e}].status`),b(t.claim_txid,`challengers[${e}].claim_txid`),b(t.claimer_pubkey,`challengers[${e}].claimer_pubkey`),I(t.assert_txid,`challengers[${e}].assert_txid`),I(t.challenge_assert_x_txid,`challengers[${e}].challenge_assert_x_txid`),I(t.challenge_assert_y_txid,`challengers[${e}].challenge_assert_y_txid`),I(t.nopayout_txid,`challengers[${e}].nopayout_txid`),typeof t.created_at!="number")throw new a(`VP response validation failed: "challengers[${e}].created_at" must be a number, got ${l(t.created_at)}`);if(typeof t.updated_at!="number")throw new a(`VP response validation failed: "challengers[${e}].updated_at" must be a number, got ${l(t.updated_at)}`)}function I(r,e){if(r!==null&&typeof r!="string")throw new a(`VP response validation failed: "${e}" must be a string or null, got ${l(r)}`)}function Ie(r){oe(r,"batchGetPeginStatus",e=>{e.result!==null&&ie(e.result)})}function Be(r){oe(r,"batchGetPegoutStatus",e=>{e.result!==null&&ke(e.result)})}function oe(r,e,t){if(r===null||typeof r!="object")throw new a(`VP response validation failed: ${e} response is not an object`);const n=r;if(!Array.isArray(n.results))throw new a(`VP response validation failed: "${e}.results" must be an array, got ${l(n.results)}`);for(let s=0;s<n.results.length;s++){const i=n.results[s];if(i===null||typeof i!="object")throw new a(`VP response validation failed: "${e}.results[${s}]" must be an object, got ${l(i)}`);const o=i;if(!v(o.pegin_txid)||o.pegin_txid.length!==T)throw new a(`VP response validation failed: "${e}.results[${s}].pegin_txid" must be a ${T}-char hex string, got ${l(o.pegin_txid)}`);if(o.error!==null&&typeof o.error!="string")throw new a(`VP response validation failed: "${e}.results[${s}].error" must be a string or null, got ${l(o.error)}`);if(o.result===null&&o.error===null)throw new a(`VP response validation failed: "${e}.results[${s}]" has neither "result" nor "error" populated`);if(o.result!==null&&o.error!==null)throw new a(`VP response validation failed: "${e}.results[${s}]" has both "result" and "error" populated`);t(o,s)}}function Ne(r){if(P(r.claim_tx,"depositor_graph.claim_tx"),P(r.assert_tx,"depositor_graph.assert_tx"),P(r.payout_tx,"depositor_graph.payout_tx"),b(r.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(r.challenger_presign_data))throw new a('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<r.challenger_presign_data.length;e++)$e(r.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof r.offchain_params_version!="number")throw new a('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const He=6e4;class ce{constructor(e,t){p(this,"client");const n={baseUrl:e,timeout:(t==null?void 0:t.timeout)??He,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 D.JsonRpcClient(n)}async requestDepositorPresignTransactions(e,t){const n=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return Se(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 ae(n),n}async getPeginStatus(e,t){const n=await this.client.call("vaultProvider_getPeginStatus",e,t);return ie(n),n}async batchGetPeginStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPeginStatus",e,t);return Ie(n),n}async batchGetPegoutStatus(e,t){const n=await this.client.call("vaultProvider_batchGetPegoutStatus",e,t);return Be(n),n}}function De(r,e){const t=new Set;for(const u of r)t.add(u.toLowerCase());const n=new Map,s=new Set,i=[],o=[];for(const u of e){const d=u.pegin_txid.toLowerCase();if(!t.has(d)){o.push(d);continue}if(s.has(d)){i.push(d);continue}s.add(d),n.set(d,{result:u.result,error:u.error})}const c=[];for(const u of t)s.has(u)||c.push(u);return{byTxid:n,missing:c,unexpected:o,duplicate:i}}async function Oe(r){const{items:e,getTxid:t,batchCall:n,onItem:s,onMissing:i,onDuplicate:o,onDuplicateBatch:c,onWholeBatchError:u,onUnexpected:d,batchSize:_=D.VP_BATCH_MAX_SIZE}=r;if(!Number.isInteger(_)||_<=0)throw new Error(`batchPollByProvider: batchSize must be a positive integer, got ${_}`);for(let w=0;w<e.length;w+=_){const x=e.slice(w,w+_),$=new Map,O=[];for(const h of x){const y=t(h).toLowerCase();$.set(y,h),O.push(y)}let A;try{const h=await n(O);A=De(O,h.results)}catch(h){u(x,h);continue}d&&A.unexpected.length>0&&d(A.unexpected);const k=new Set(A.duplicate);for(const h of k){const y=$.get(h);y&&o(y)}c&&k.size>0&&c(k.size);for(const h of A.missing){const y=$.get(h);y&&i(y)}for(const[h,y]of A.byTxid){if(k.has(h))continue;const F=$.get(h);F&&s(F,{pegin_txid:h,result:y.result,error:y.error})}}}const Ge="BIP0322-signed-message",je="TapTweak",le=32,Le=64;function ue(r,e){const t=new TextEncoder().encode(r),n=q.sha256(t),s=new Uint8Array(n.length*2+e.length);return s.set(n,0),s.set(n,n.length),s.set(e,n.length*2),q.sha256(s)}function Ue(r){if(r.length!==le)return null;const e=ue(je,r),t=L.xOnlyPointAddTweak(r,e);return t?t.xOnlyPubkey:null}function Me(r,e,t){if(e.length!==le||t.length!==Le)return!1;try{const n=ue(Ge,r),s=C.payments.p2tr({internalPubkey:S.Buffer.from(e)});if(!s.output)return!1;const i=s.output,o=0,c=new C.Transaction;c.version=0,c.locktime=0;const u=S.Buffer.concat([S.Buffer.from([0,32]),S.Buffer.from(n)]);c.addInput(S.Buffer.alloc(32,0),4294967295,0,u),c.addOutput(i,o);const d=new C.Transaction;d.version=0,d.locktime=0;const _=c.getHash();d.addInput(_,0,0),d.addOutput(S.Buffer.from([106]),o);const w=d.hashForWitnessV1(0,[i],[o],C.Transaction.SIGHASH_DEFAULT),x=Ue(e);return x?L.verifySchnorr(w,x,t):!1}catch{return!1}}function H(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 i=Number(n);return new Uint8Array([t|25,i>>>8&255,i&255])}if(n<0x100000000n){const i=Number(n);return new Uint8Array([t|26,i>>>24&255,i>>>16&255,i>>>8&255,i&255])}const s=new Uint8Array(9);s[0]=t|27;for(let i=7;i>=0;i--)s[1+i]=Number(n>>BigInt((7-i)*8))&255;return s}function de(...r){const e=r.reduce((s,i)=>s+i.length,0),t=new Uint8Array(e);let n=0;for(const s of r)t.set(s,n),n+=s.length;return t}function Z(r){const t=[H(4,r.length)];for(const n of r)t.push(H(0,n));return de(...t)}function Fe(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=H(4,3),s=Z(r),i=Z(e),o=H(0,t);return de(n,s,i,o)}const Ke=new TextEncoder().encode("btc-auth.server-identity.v1"),Xe=2*3600;class g extends Error{constructor(e,t){super(e),this.reason=t,this.name="ServerIdentityError"}}function B(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 pe(r){const{proof:e,pinnedServerPubkey:t,now:n}=r,s=r.maxLifetimeSecs??Xe,i=m.stripHexPrefix(t).toLowerCase();if(i.length!==m.X_ONLY_PUBKEY_HEX_LEN||!V.HEX_RE.test(i))throw new g(`pinnedServerPubkey must be 32-byte hex; got ${i.length} chars`,"invalid_pubkey_encoding");const o=m.stripHexPrefix(e.server_pubkey).toLowerCase();if(o.length!==m.X_ONLY_PUBKEY_HEX_LEN||!V.HEX_RE.test(o))throw new g(`server_pubkey must be 32-byte hex; got ${o.length} chars`,"invalid_pubkey_encoding");if(o!==i)throw new g(`server_pubkey does not match pinned value: expected ${i}, got ${o}`,"pinned_pubkey_mismatch");if(!Number.isSafeInteger(e.expires_at))throw new g(`expires_at must be a finite integer; got ${JSON.stringify(e.expires_at)}`,"invalid_expires_at");if(!Number.isSafeInteger(n))throw new g(`now must be a finite integer; got ${JSON.stringify(n)}`,"invalid_expires_at");if(e.expires_at<=n)throw new g(`server identity proof expired at ${e.expires_at}, now ${n}`,"expired");if(!Number.isSafeInteger(s)||s<=0)throw new g(`maxLifetimeSecs must be a positive safe integer; got ${JSON.stringify(s)}`,"invalid_max_lifetime");if(e.expires_at-n>s)throw new g(`server identity proof expires too far in the future: expires_at=${e.expires_at}, now=${n}, max lifetime=${s}s`,"expires_too_far");const c=m.stripHexPrefix(e.ephemeral_pubkey).toLowerCase();if(c.length!==m.COMPRESSED_PUBKEY_HEX_LEN||!V.HEX_RE.test(c))throw new g(`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 g(`ephemeral_pubkey must be compressed (prefix 02/03); got ${u}`,"invalid_ephemeral_pubkey");const d=B(c);if(!L.isPoint(d))throw new g("ephemeral_pubkey is not a valid secp256k1 point","invalid_ephemeral_pubkey");const _=m.stripHexPrefix(e.signature).toLowerCase();if(_.length!==m.SCHNORR_SIG_HEX_LEN||!V.HEX_RE.test(_))throw new g(`signature must be 64-byte Schnorr hex; got ${_.length} chars`,"invalid_signature_encoding");const w=Fe(Ke,B(c),e.expires_at);if(!Me(w,B(o),B(_)))throw new g("BIP-322 signature verification failed — ephemeral key is not attested by pinned server pubkey","signature_verification_failed")}const Q=new Set(["vaultProvider_submitDepositorWotsKey","vaultProvider_submitDepositorPresignatures","vaultProvider_requestDepositorPresignTransactions"]),ee=new Set(["vaultProvider_requestDepositorClaimerArtifacts"]),qe=6e4,G="auth_createDepositorToken",j="auth_createDepositorTokenGrpc";function he(r,e){return new D.JsonRpcClient({baseUrl:r,timeout:qe,headers:e,retryableFor:t=>t===G||t===j})}const te=4102444800,Je=30;class Ye{constructor(e){p(this,"client");p(this,"peginTxid");p(this,"authAnchorHex");p(this,"pinnedServerPubkey");p(this,"authGatedMethods");p(this,"grpcGatedMethods");p(this,"refreshSkewSecs");p(this,"now");p(this,"cachedJsonRpc",null);p(this,"inFlightJsonRpc",null);p(this,"cachedGrpc",null);p(this,"inFlightGrpc",null);this.client=e.client,this.peginTxid=e.peginTxid,this.authAnchorHex=e.authAnchorHex,this.pinnedServerPubkey=e.pinnedServerPubkey,this.authGatedMethods=e.authGatedMethods,this.grpcGatedMethods=e.grpcGatedMethods,this.refreshSkewSecs=e.refreshSkewSecs??Je,this.now=e.now??(()=>Math.floor(Date.now()/1e3))}async getToken(e){return e===G||e===j?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"?j:G,s=(async()=>{try{const i=await this.client.call(n,{pegin_txid:this.peginTxid,auth_anchor:this.authAnchorHex});if(pe({proof:i.server_identity,pinnedServerPubkey:this.pinnedServerPubkey,now:this.now()}),typeof i.token!="string"||i.token.length===0)throw new Error(`VpTokenProvider: invalid token in acquire response (expected non-empty string, got ${typeof i.token})`);const o=this.now();if(!Number.isSafeInteger(i.expires_at)||i.expires_at<=o||i.expires_at>te)throw new Error(`VpTokenProvider: invalid expires_at in acquire response (got ${JSON.stringify(i.expires_at)}; must be a safe integer in (${o}, ${te}])`);const c={token:i.token,expiresAt:i.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=s:this.inFlightJsonRpc=s,s}}class ge{constructor(){p(this,"entries",new Map)}getOrCreate(e){const t=e.enableGrpcArtifactAuth??!1,n=this.entries.get(e.peginTxid);if(n){if(n.authAnchorHex!==e.authAnchorHex)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to authAnchorHex ${n.authAnchorHex.slice(0,8)}…; got ${e.authAnchorHex.slice(0,8)}…`);if(n.pinnedServerPubkey!==e.pinnedServerPubkey)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to pinnedServerPubkey ${n.pinnedServerPubkey.slice(0,8)}…; got ${e.pinnedServerPubkey.slice(0,8)}…`);if(n.enableGrpcArtifactAuth!==t)throw new Error(`VpTokenRegistry: peginTxid ${e.peginTxid} already bound to enableGrpcArtifactAuth=${n.enableGrpcArtifactAuth}; got ${t}`);return n.provider.setClient(e.client),n.provider}const s=new Ye({client:e.client,peginTxid:e.peginTxid,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,authGatedMethods:t?Q:new Set([...Q,...ee]),grpcGatedMethods:t?ee:new Set});return this.entries.set(e.peginTxid,{provider:s,authAnchorHex:e.authAnchorHex,pinnedServerPubkey:e.pinnedServerPubkey,enableGrpcArtifactAuth:t}),s}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 M=new ge;function ze(r){var n;const e=he(r.baseUrl,(n=r.options)==null?void 0:n.headers),t=M.getOrCreate({client:e,peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,enableGrpcArtifactAuth:r.enableGrpcArtifactAuth});return new ce(r.baseUrl,{...r.options,tokenProvider:t})}function We(r){M.getOrCreate({client:he(r.baseUrl,r.headers),peginTxid:r.peginTxid,authAnchorHex:r.authAnchorHex,pinnedServerPubkey:r.pinnedServerPubkey,enableGrpcArtifactAuth:r.enableGrpcArtifactAuth})}exports.OnChainBtcVaultStatus=re;exports.ServerIdentityError=g;exports.VaultProviderRpcClient=ce;exports.ViemProtocolParamsReader=Pe;exports.ViemUniversalChallengerReader=ve;exports.ViemVaultKeeperReader=we;exports.VpResponseValidationError=a;exports.VpTokenRegistry=ge;exports.batchPollByProvider=Oe;exports.createAuthenticatedVpClient=ze;exports.primeVpTokenRegistry=We;exports.resolveProtocolAddresses=ye;exports.validateRequestDepositorClaimerArtifactsResponse=ae;exports.verifyServerIdentity=pe;exports.vpTokenRegistry=M;
2
+ //# sourceMappingURL=primeVpAuth-DhbTaCKm.cjs.map