@babylonlabs-io/ts-sdk 0.19.0 → 0.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +56 -12
- package/dist/bitcoin-CNnPFU6Y.cjs +2 -0
- package/dist/bitcoin-CNnPFU6Y.cjs.map +1 -0
- package/dist/{constants-Q7v2O7Ps.js → bitcoin-nOOgeRyl.js} +64 -76
- package/dist/bitcoin-nOOgeRyl.js.map +1 -0
- package/dist/buildAndBroadcastRefund-DWEQvj9T.cjs +2 -0
- package/dist/buildAndBroadcastRefund-DWEQvj9T.cjs.map +1 -0
- package/dist/buildAndBroadcastRefund-DnTQkCgG.js +1331 -0
- package/dist/buildAndBroadcastRefund-DnTQkCgG.js.map +1 -0
- package/dist/challengeAssert-D1lpvuMv.js +283 -0
- package/dist/challengeAssert-D1lpvuMv.js.map +1 -0
- package/dist/challengeAssert-nYlgeAI8.cjs +2 -0
- package/dist/challengeAssert-nYlgeAI8.cjs.map +1 -0
- package/dist/errors-D9EtjJoD.cjs +2 -0
- package/dist/errors-D9EtjJoD.cjs.map +1 -0
- package/dist/{errors-aMocmFr-.js → errors-D_PI__IT.js} +98 -97
- package/dist/errors-D_PI__IT.js.map +1 -0
- package/dist/fundPeginTransaction-BLYXxLBv.js +70 -0
- package/dist/fundPeginTransaction-BLYXxLBv.js.map +1 -0
- package/dist/fundPeginTransaction-DxNOeyNI.cjs +2 -0
- package/dist/fundPeginTransaction-DxNOeyNI.cjs.map +1 -0
- package/dist/index-BpXpESWu.cjs +2 -0
- package/dist/index-BpXpESWu.cjs.map +1 -0
- package/dist/{index-BvFLf3vm.js → index-CFwoGJNQ.js} +146 -518
- package/dist/index-CFwoGJNQ.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +133 -109
- package/dist/payout-DzGsAnhf.js +261 -0
- package/dist/payout-DzGsAnhf.js.map +1 -0
- package/dist/payout-RFIh7GLN.cjs +2 -0
- package/dist/payout-RFIh7GLN.cjs.map +1 -0
- package/dist/psbtInputFields-05ZrwRzf.cjs +2 -0
- package/dist/psbtInputFields-05ZrwRzf.cjs.map +1 -0
- package/dist/psbtInputFields-r1ss6WLU.js +237 -0
- package/dist/psbtInputFields-r1ss6WLU.js.map +1 -0
- package/dist/signing-DeWVBl7m.js +64 -0
- package/dist/signing-DeWVBl7m.js.map +1 -0
- package/dist/signing-cl-lowxV.cjs +2 -0
- package/dist/signing-cl-lowxV.cjs.map +1 -0
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +2 -2
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.d.ts +3 -1
- package/dist/tbv/core/index.d.ts.map +1 -1
- package/dist/tbv/core/index.js +130 -106
- package/dist/tbv/core/managers/PeginManager.d.ts +1 -1
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.d.ts +3 -2
- package/dist/tbv/core/primitives/index.d.ts.map +1 -1
- package/dist/tbv/core/primitives/index.js +24 -23
- package/dist/tbv/core/primitives/psbt/__tests__/helpers.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/index.d.ts +1 -1
- package/dist/tbv/core/primitives/psbt/payout.d.ts.map +1 -1
- package/dist/tbv/core/primitives/psbt/pegin.d.ts +2 -3
- package/dist/tbv/core/primitives/psbt/pegin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts +4 -0
- package/dist/tbv/core/primitives/utils/bitcoin.d.ts.map +1 -1
- package/dist/tbv/core/primitives/utils/index.d.ts +1 -1
- package/dist/tbv/core/primitives/utils/index.d.ts.map +1 -1
- package/dist/tbv/core/services/activation/__tests__/activateVault.test.d.ts +2 -0
- package/dist/tbv/core/services/activation/__tests__/activateVault.test.d.ts.map +1 -0
- package/dist/tbv/core/services/activation/activateVault.d.ts +77 -0
- package/dist/tbv/core/services/activation/activateVault.d.ts.map +1 -0
- package/dist/tbv/core/services/activation/index.d.ts +7 -0
- package/dist/tbv/core/services/activation/index.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/__tests__/peginState.test.d.ts +2 -0
- package/dist/tbv/core/services/deposit/__tests__/peginState.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/__tests__/validation.test.d.ts +5 -0
- package/dist/tbv/core/services/deposit/__tests__/validation.test.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/index.d.ts +4 -0
- package/dist/tbv/core/services/deposit/index.d.ts.map +1 -1
- package/dist/tbv/core/services/deposit/peginState.d.ts +93 -0
- package/dist/tbv/core/services/deposit/peginState.d.ts.map +1 -0
- package/dist/tbv/core/services/deposit/validation.d.ts +114 -0
- package/dist/tbv/core/services/deposit/validation.d.ts.map +1 -0
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.d.ts +3 -0
- package/dist/tbv/core/services/index.d.ts.map +1 -1
- package/dist/tbv/core/services/index.js +25 -7
- package/dist/tbv/core/services/index.js.map +1 -1
- package/dist/tbv/core/services/pegout/__tests__/state.test.d.ts +2 -0
- package/dist/tbv/core/services/pegout/__tests__/state.test.d.ts.map +1 -0
- package/dist/tbv/core/services/pegout/index.d.ts +2 -0
- package/dist/tbv/core/services/pegout/index.d.ts.map +1 -0
- package/dist/tbv/core/services/pegout/state.d.ts +30 -0
- package/dist/tbv/core/services/pegout/state.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/__tests__/buildAndBroadcastRefund.test.d.ts +2 -0
- package/dist/tbv/core/services/refund/__tests__/buildAndBroadcastRefund.test.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts +103 -0
- package/dist/tbv/core/services/refund/buildAndBroadcastRefund.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/errors.d.ts +13 -0
- package/dist/tbv/core/services/refund/errors.d.ts.map +1 -0
- package/dist/tbv/core/services/refund/index.d.ts +8 -0
- package/dist/tbv/core/services/refund/index.d.ts.map +1 -0
- package/dist/tbv/core/utils/index.cjs +1 -1
- package/dist/tbv/core/utils/index.js +30 -24
- package/dist/tbv/core/utils/transaction/fundPeginTransaction.d.ts +1 -1
- package/dist/tbv/core/utils/utxo/__tests__/availability.test.d.ts +3 -0
- package/dist/tbv/core/utils/utxo/__tests__/availability.test.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts +3 -0
- package/dist/tbv/core/utils/utxo/__tests__/reservation.test.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/availability.d.ts +62 -0
- package/dist/tbv/core/utils/utxo/availability.d.ts.map +1 -0
- package/dist/tbv/core/utils/utxo/index.d.ts +2 -0
- package/dist/tbv/core/utils/utxo/index.d.ts.map +1 -1
- package/dist/tbv/core/utils/utxo/reservation.d.ts +91 -0
- package/dist/tbv/core/utils/utxo/reservation.d.ts.map +1 -0
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +130 -106
- package/dist/tbv/integrations/aave/index.cjs +1 -1
- package/dist/tbv/integrations/aave/index.cjs.map +1 -1
- package/dist/tbv/integrations/aave/index.d.ts +3 -3
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +145 -169
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/utils/healthFactor.d.ts +0 -30
- package/dist/tbv/integrations/aave/utils/healthFactor.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/utils/index.d.ts +2 -2
- package/dist/tbv/integrations/aave/utils/index.d.ts.map +1 -1
- package/dist/types-B-p4dhEH.cjs +2 -0
- package/dist/types-B-p4dhEH.cjs.map +1 -0
- package/dist/types-DWjaqVfP.js +608 -0
- package/dist/types-DWjaqVfP.js.map +1 -0
- package/package.json +5 -1
- package/dist/challengeAssert-D_k_ADgP.cjs +0 -2
- package/dist/challengeAssert-D_k_ADgP.cjs.map +0 -1
- package/dist/challengeAssert-k5_LWUtO.js +0 -362
- package/dist/challengeAssert-k5_LWUtO.js.map +0 -1
- package/dist/constants-EiyZkXce.cjs +0 -2
- package/dist/constants-EiyZkXce.cjs.map +0 -1
- package/dist/constants-Q7v2O7Ps.js.map +0 -1
- package/dist/errors-DVNYib5y.cjs +0 -2
- package/dist/errors-DVNYib5y.cjs.map +0 -1
- package/dist/errors-aMocmFr-.js.map +0 -1
- package/dist/fundPeginTransaction-DpwnDslW.js +0 -50
- package/dist/fundPeginTransaction-DpwnDslW.js.map +0 -1
- package/dist/fundPeginTransaction-EbrZzlrh.cjs +0 -2
- package/dist/fundPeginTransaction-EbrZzlrh.cjs.map +0 -1
- package/dist/index-BX-V3C9t.js +0 -995
- package/dist/index-BX-V3C9t.js.map +0 -1
- package/dist/index-BgnxXV5G.cjs +0 -2
- package/dist/index-BgnxXV5G.cjs.map +0 -1
- package/dist/index-BvFLf3vm.js.map +0 -1
- package/dist/index-DpKhuCta.cjs +0 -2
- package/dist/index-DpKhuCta.cjs.map +0 -1
- package/dist/payout-Ce9vSs9e.js +0 -164
- package/dist/payout-Ce9vSs9e.js.map +0 -1
- package/dist/payout-CfsDnjKI.cjs +0 -2
- package/dist/payout-CfsDnjKI.cjs.map +0 -1
- package/dist/psbtInputFields-C0nKn_GD.cjs +0 -2
- package/dist/psbtInputFields-C0nKn_GD.cjs.map +0 -1
- package/dist/psbtInputFields-DO0ELwiv.js +0 -116
- package/dist/psbtInputFields-DO0ELwiv.js.map +0 -1
- package/dist/signing-Deg5lCoC.cjs +0 -2
- package/dist/signing-Deg5lCoC.cjs.map +0 -1
- package/dist/signing-Drwr3bXB.js +0 -16
- package/dist/signing-Drwr3bXB.js.map +0 -1
- package/dist/types-D1rYwwCu.js +0 -235
- package/dist/types-D1rYwwCu.js.map +0 -1
- package/dist/types-DEWiqXYp.cjs +0 -2
- package/dist/types-DEWiqXYp.cjs.map +0 -1
package/dist/index-DpKhuCta.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";var j=Object.defineProperty;var M=(n,e,t)=>e in n?j(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var h=(n,e,t)=>M(n,typeof e!="symbol"?e+"":e,t);const $=require("./types-DEWiqXYp.cjs"),K=21e6*1e8,_=3e4;async function b(n,e){const t=new AbortController,a=setTimeout(()=>t.abort(),_),i=[t.signal,e==null?void 0:e.signal].filter(Boolean);try{return await fetch(n,{...e,signal:AbortSignal.any(i)})}catch(s){throw clearTimeout(a),s!=null&&typeof s=="object"&&"name"in s&&s.name==="AbortError"?new Error(`Mempool API request timed out after ${_}ms: ${n}`):s}}const I=1e4;function E(n){return Number.isInteger(n)&&n>0&&n<=K}function N(n){return Number.isInteger(n)&&n>0&&n<=I}function B(n,e){return!Number.isInteger(n)||n<0?!1:e===void 0||n<e}const k={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function d(n,e){try{const t=await b(n,e);if(!t.ok){const i=await t.text();throw new Error(`Mempool API error (${t.status}): ${i||t.statusText}`)}const a=t.headers.get("content-type");return a!=null&&a.includes("application/json")?await t.json():await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to fetch from mempool API: ${t.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function U(n,e){try{const t=await b(`${e}/tx`,{method:"POST",body:n,headers:{"Content-Type":"text/plain"}});if(!t.ok){const i=await t.text();let s;try{s=JSON.parse(i).message}catch{s=i}throw new Error(s||`Failed to broadcast transaction: ${t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to broadcast BTC transaction: ${t.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function R(n,e){return d(`${e}/tx/${n}`)}async function D(n,e){try{const t=await b(`${e}/tx/${n}/hex`);if(!t.ok){const a=await t.text();throw new Error(`Mempool API error (${t.status}): ${a||t.statusText}`)}return await t.text()}catch(t){throw t instanceof Error?new Error(`Failed to get transaction hex for ${n}: ${t.message}`):new Error(`Failed to get transaction hex for ${n}: Unknown error`)}}async function H(n,e,t){const a=await R(n,t);if(!B(e,a.vout.length))throw new Error(`Invalid vout ${e} for transaction ${n} (has ${a.vout.length} outputs)`);const i=a.vout[e];if(!E(i.value))throw new Error(`Invalid UTXO value ${i.value} for ${n}:${e}`);return{txid:n,vout:e,value:i.value,scriptPubKey:i.scriptpubkey}}async function L(n,e){try{const t=await d(`${e}/address/${n}/utxo`),a=await d(`${e}/v1/validate-address/${n}`);if(!a.isvalid)throw new Error(`Invalid Bitcoin address: ${n}. Mempool API validation failed.`);for(const s of t){if(!B(s.vout))throw new Error(`Invalid vout ${s.vout} for ${s.txid}`);if(!E(s.value))throw new Error(`Invalid UTXO value ${s.value} for ${s.txid}:${s.vout}`)}return t.sort((s,T)=>T.value-s.value).map(s=>({txid:s.txid,vout:s.vout,value:s.value,scriptPubKey:a.scriptPubKey,confirmed:s.status.confirmed}))}catch(t){throw t instanceof Error?new Error(`Failed to get UTXOs for address ${n}: ${t.message}`):new Error(`Failed to get UTXOs for address ${n}: Unknown error`)}}function q(n){return k[n]}async function X(n,e){return d(`${e}/address/${n}/txs`)}async function W(n){const e=await b(`${n}/v1/fees/recommended`);if(!e.ok)throw new Error(`Failed to fetch network fees: ${e.status} ${e.statusText}`);const t=await e.json(),a=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const i of a)if(!N(t[i]))throw new Error(`Invalid fee rate ${i}=${t[i]} from mempool API: expected a positive number ≤ ${I}`);if(t.minimumFee>t.economyFee||t.economyFee>t.hourFee||t.hourFee>t.halfHourFee||t.halfHourFee>t.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${t.minimumFee}) <= economyFee (${t.economyFee}) <= hourFee (${t.hourFee}) <= halfHourFee (${t.halfHourFee}) <= fastestFee (${t.fastestFee}).`);return t}const m=[{type:"function",name:"getVaultKeepersByVersion",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"},{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentVaultKeepers",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentVaultKeepersVersion",inputs:[{name:"appEntryPoint",type:"address",internalType:"address"}],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"}],c=[{type:"function",name:"submitPeginRequest",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"payable"},{type:"function",name:"submitPeginRequest",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"referralCode",type:"uint32",internalType:"uint32"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"",type:"bytes32",internalType:"bytes32"}],stateMutability:"payable"},{type:"function",name:"submitPeginRequestBatch",inputs:[{name:"depositor",type:"address",internalType:"address"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"requests",type:"tuple[]",internalType:"struct IBTCVaultRegistry.BatchPeginRequest[]",components:[{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"btcPopSignature",type:"bytes",internalType:"bytes"},{name:"unsignedPrePeginTx",type:"bytes",internalType:"bytes"},{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"referralCode",type:"uint32",internalType:"uint32"},{name:"depositorPayoutBtcAddress",type:"bytes",internalType:"bytes"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"}]}],outputs:[{name:"vaultIds",type:"bytes32[]",internalType:"bytes32[]"}],stateMutability:"payable"},{type:"function",name:"activateVaultWithSecret",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"},{name:"s",type:"bytes32",internalType:"bytes32"},{name:"activationMetadata",type:"bytes",internalType:"bytes"}],outputs:[],stateMutability:"nonpayable"},{type:"function",name:"getPegInFee",inputs:[{name:"vaultProvider",type:"address",internalType:"address"}],outputs:[{name:"totalFee",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"function",name:"getBtcVaultBasicInfo",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"depositor",type:"address",internalType:"address"},{name:"depositorBtcPubKey",type:"bytes32",internalType:"bytes32"},{name:"amount",type:"uint256",internalType:"uint256"},{name:"vaultProvider",type:"address",internalType:"address"},{name:"status",type:"uint8",internalType:"enum IBTCVaultRegistry.BTCVaultStatus"},{name:"applicationEntryPoint",type:"address",internalType:"address"},{name:"createdAt",type:"uint256",internalType:"uint256"}],stateMutability:"view"},{type:"error",name:"InvalidPeginFee",inputs:[{name:"provided",type:"uint256",internalType:"uint256"},{name:"required",type:"uint256",internalType:"uint256"}]},{type:"error",name:"InvalidSecret",inputs:[]},{type:"error",name:"ActivationDeadlineExpired",inputs:[]},{type:"error",name:"InvalidHashlock",inputs:[]},{type:"error",name:"DuplicateHashlock",inputs:[]},{type:"error",name:"CapExceeded",inputs:[]},{type:"error",name:"InvalidOutputIndex",inputs:[]},{type:"error",name:"PeginSignaturesIncomplete",inputs:[]},{type:"function",name:"getBtcVaultProtocolInfo",inputs:[{name:"vaultId",type:"bytes32",internalType:"bytes32"}],outputs:[{name:"depositorSignedPeginTx",type:"bytes",internalType:"bytes"},{name:"universalChallengersVersion",type:"uint32",internalType:"uint32"},{name:"appVaultKeepersVersion",type:"uint32",internalType:"uint32"},{name:"offchainParamsVersion",type:"uint32",internalType:"uint32"},{name:"verifiedAt",type:"uint256",internalType:"uint256"},{name:"depositorWotsPkHash",type:"bytes32",internalType:"bytes32"},{name:"hashlock",type:"bytes32",internalType:"bytes32"},{name:"htlcVout",type:"uint8",internalType:"uint8"},{name:"depositorPopSignature",type:"bytes",internalType:"bytes"},{name:"prePeginTxHash",type:"bytes32",internalType:"bytes32"},{name:"vaultProviderCommissionBps",type:"uint16",internalType:"uint16"}],stateMutability:"view"},{type:"function",name:"protocolParams",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IProtocolParams"}],stateMutability:"view"},{type:"function",name:"applicationRegistry",inputs:[],outputs:[{name:"",type:"address",internalType:"contract IApplicationRegistry"}],stateMutability:"view"}],l=[{type:"function",name:"getTBVProtocolParams",inputs:[],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.TBVProtocolParams",components:[{name:"minimumPegInAmount",type:"uint64",internalType:"uint64"},{name:"maxPegInAmount",type:"uint64",internalType:"uint64"},{name:"pegInAckTimeout",type:"uint64",internalType:"uint64"},{name:"pegInActivationTimeout",type:"uint64",internalType:"uint64"},{name:"maxHtlcOutputCount",type:"uint8",internalType:"uint8"}]}],stateMutability:"view"},{type:"function",name:"getLatestOffchainParams",inputs:[],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.VersionedOffchainParams",components:[{name:"timelockAssert",type:"uint256",internalType:"uint256"},{name:"timelockChallengeAssert",type:"uint256",internalType:"uint256"},{name:"securityCouncilKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"councilQuorum",type:"uint8",internalType:"uint8"},{name:"feeRate",type:"uint64",internalType:"uint64"},{name:"babeTotalInstances",type:"uint16",internalType:"uint16"},{name:"babeInstancesToFinalize",type:"uint8",internalType:"uint8"},{name:"minVpCommissionBps",type:"uint16",internalType:"uint16"},{name:"tRefund",type:"uint32",internalType:"uint32"},{name:"tStale",type:"uint32",internalType:"uint32"},{name:"minPeginFeeRate",type:"uint64",internalType:"uint64"},{name:"proverProgramVersion",type:"uint16",internalType:"uint16"},{name:"minPrepeginDepth",type:"uint32",internalType:"uint32"}]}],stateMutability:"view"},{type:"function",name:"getOffchainParamsByVersion",inputs:[{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple",internalType:"struct IProtocolParams.VersionedOffchainParams",components:[{name:"timelockAssert",type:"uint256",internalType:"uint256"},{name:"timelockChallengeAssert",type:"uint256",internalType:"uint256"},{name:"securityCouncilKeys",type:"bytes32[]",internalType:"bytes32[]"},{name:"councilQuorum",type:"uint8",internalType:"uint8"},{name:"feeRate",type:"uint64",internalType:"uint64"},{name:"babeTotalInstances",type:"uint16",internalType:"uint16"},{name:"babeInstancesToFinalize",type:"uint8",internalType:"uint8"},{name:"minVpCommissionBps",type:"uint16",internalType:"uint16"},{name:"tRefund",type:"uint32",internalType:"uint32"},{name:"tStale",type:"uint32",internalType:"uint32"},{name:"minPeginFeeRate",type:"uint64",internalType:"uint64"},{name:"proverProgramVersion",type:"uint16",internalType:"uint16"},{name:"minPrepeginDepth",type:"uint32",internalType:"uint32"}]}],stateMutability:"view"},{type:"function",name:"latestOffchainParamsVersion",inputs:[],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"},{type:"function",name:"getUniversalChallengersByVersion",inputs:[{name:"versionNumber",type:"uint16",internalType:"uint16"}],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"getCurrentUniversalChallengers",inputs:[],outputs:[{name:"",type:"tuple[]",internalType:"struct BTCVaultTypes.AddressBTCKeyPair[]",components:[{name:"ethAddress",type:"address",internalType:"address"},{name:"btcPubKey",type:"bytes32",internalType:"bytes32"}]}],stateMutability:"view"},{type:"function",name:"latestUniversalChallengersVersion",inputs:[],outputs:[{name:"",type:"uint16",internalType:"uint16"}],stateMutability:"view"}],w=new Set(Object.values($.DaemonStatus)),z=200;function o(n){var e;return((e=JSON.stringify(n))==null?void 0:e.slice(0,z))??"undefined"}const J="The vault provider returned an unexpected response. Please try again or contact support.";class r extends Error{constructor(t){super(J);h(this,"detail");this.name="VpResponseValidationError",this.detail=t}}const Q=/^[0-9a-fA-F]+$/,v=64,V=66,g=64;function u(n){return typeof n=="string"&&n.length>0&&Q.test(n)}function F(n){return typeof n=="string"&&n.length>0}function S(n,e){if(!u(n))throw new r(`VP response validation failed: "${e}" must be a non-empty hex string, got ${o(n)}`)}function y(n,e){if(!F(n))throw new r(`VP response validation failed: "${e}" must be a non-empty string, got ${o(n)}`)}function O(n,e){if(!u(n)||n.length!==v&&n.length!==V)throw new r(`VP response validation failed: "${e}" must be a ${v} or ${V}-char hex string (BTC pubkey), got ${o(n)}`)}function G(n){const e=n.presigning;if(e==null)return;if(typeof e!="object"||Array.isArray(e))throw new r('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 r(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${o(t.depositor_graph_created)}`);if(t.vk_challenger_presigning_completed!==void 0&&typeof t.vk_challenger_presigning_completed!="number")throw new r(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${o(t.vk_challenger_presigning_completed)}`);if(t.vk_challenger_presigning_total!==void 0&&typeof t.vk_challenger_presigning_total!="number")throw new r(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${o(t.vk_challenger_presigning_total)}`)}function Y(n){if(n===null||typeof n!="object")throw new r("VP response validation failed: getPeginStatus response is not an object");const e=n;if(!u(e.pegin_txid)||e.pegin_txid.length!==g)throw new r(`VP response validation failed: "pegin_txid" must be a ${g}-char hex string (txid), got ${o(e.pegin_txid)}`);if(typeof e.status!="string")throw new r('VP response validation failed: "status" must be a string');if(!w.has(e.status))throw new r(`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 r('VP response validation failed: "progress" must be an object');if(G(e.progress),typeof e.health_info!="string")throw new r('VP response validation failed: "health_info" must be a string');if(e.last_error!==void 0&&typeof e.last_error!="string")throw new r(`VP response validation failed: "last_error" must be a string if present, got ${o(e.last_error)}`)}function Z(n){if(n===null||typeof n!="object")throw new r("VP response validation failed: requestDepositorPresignTransactions response is not an object");const e=n;if(!Array.isArray(e.txs))throw new r('VP response validation failed: "txs" must be an array');for(let t=0;t<e.txs.length;t++)ee(e.txs[t],`txs[${t}]`);if(e.depositor_graph===null||typeof e.depositor_graph!="object")throw new r('VP response validation failed: "depositor_graph" must be an object');se(e.depositor_graph)}function p(n,e){if(n===null||typeof n!="object")throw new r(`VP response validation failed: "${e}" must be an object`);S(n.tx_hex,`${e}.tx_hex`)}function ee(n,e){if(n===null||typeof n!="object")throw new r(`VP response validation failed: "${e}" must be an object`);const t=n;O(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`),y(t.payout_psbt,`${e}.payout_psbt`)}function te(n,e){if(n===null||typeof n!="object")throw new r(`VP response validation failed: "${e}" must be an object`);const t=n;y(t.wots_pks_json,`${e}.wots_pks_json`),y(t.gc_wots_keys_json,`${e}.gc_wots_keys_json`)}function ne(n,e){if(n===null||typeof n!="object")throw new r(`VP response validation failed: "${e}" must be an object`);const t=n;if(O(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`),y(t.nopayout_psbt,`${e}.nopayout_psbt`),!Array.isArray(t.challenge_assert_connectors))throw new r(`VP response validation failed: "${e}.challenge_assert_connectors" must be an array`);for(let a=0;a<t.challenge_assert_connectors.length;a++)te(t.challenge_assert_connectors[a],`${e}.challenge_assert_connectors[${a}]`);if(!Array.isArray(t.output_label_hashes))throw new r(`VP response validation failed: "${e}.output_label_hashes" must be an array`);for(let a=0;a<t.output_label_hashes.length;a++)S(t.output_label_hashes[a],`${e}.output_label_hashes[${a}]`)}function ae(n){if(n===null||typeof n!="object")throw new r("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const e=n;if(!F(e.tx_graph_json))throw new r(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${o(e.tx_graph_json)}`);if(!u(e.verifying_key_hex))throw new r(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${o(e.verifying_key_hex)}`);if(e.babe_sessions===null||typeof e.babe_sessions!="object")throw new r('VP response validation failed: "babe_sessions" must be an object');for(const[t,a]of Object.entries(e.babe_sessions)){if(a===null||typeof a!="object")throw new r(`VP response validation failed: "babe_sessions.${t}" must be an object`);const i=a;if(!u(i.decryptor_artifacts_hex))throw new r(`VP response validation failed: "babe_sessions.${t}.decryptor_artifacts_hex" must be a non-empty hex string, got ${o(i.decryptor_artifacts_hex)}`)}}function re(n){if(n===null||typeof n!="object")throw new r("VP response validation failed: getPegoutStatus response is not an object");const e=n;if(!u(e.pegin_txid)||e.pegin_txid.length!==g)throw new r(`VP response validation failed: "pegin_txid" must be a ${g}-char hex string (txid), got ${o(e.pegin_txid)}`);if(typeof e.found!="boolean")throw new r(`VP response validation failed: "found" must be a boolean, got ${o(e.found)}`);if(e.claimer!==void 0){if(e.claimer===null||typeof e.claimer!="object")throw new r('VP response validation failed: "claimer" must be an object if present');const t=e.claimer;if(typeof t.status!="string")throw new r(`VP response validation failed: "claimer.status" must be a string, got ${o(t.status)}`);if(typeof t.failed!="boolean")throw new r(`VP response validation failed: "claimer.failed" must be a boolean, got ${o(t.failed)}`)}if(e.challenger!==void 0){if(e.challenger===null||typeof e.challenger!="object")throw new r('VP response validation failed: "challenger" must be an object if present');const t=e.challenger;if(typeof t.status!="string")throw new r(`VP response validation failed: "challenger.status" must be a string, got ${o(t.status)}`)}}function se(n){if(p(n.claim_tx,"depositor_graph.claim_tx"),p(n.assert_tx,"depositor_graph.assert_tx"),p(n.payout_tx,"depositor_graph.payout_tx"),y(n.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(n.challenger_presign_data))throw new r('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let e=0;e<n.challenger_presign_data.length;e++)ne(n.challenger_presign_data[e],`depositor_graph.challenger_presign_data[${e}]`);if(typeof n.offchain_params_version!="number")throw new r('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const ie=6e4;class oe{constructor(e,t){h(this,"client");const a={baseUrl:e,timeout:(t==null?void 0:t.timeout)??ie,retries:t==null?void 0:t.retries,retryDelay:t==null?void 0:t.retryDelay,retryableFor:t==null?void 0:t.retryableFor,headers:t==null?void 0:t.headers};this.client=new $.JsonRpcClient(a)}async requestDepositorPresignTransactions(e,t){const a=await this.client.call("vaultProvider_requestDepositorPresignTransactions",e,t);return Z(a),a}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 a=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",e,t);return ae(a),a}async getPeginStatus(e,t){const a=await this.client.call("vaultProvider_getPeginStatus",e,t);return Y(a),a}async getPegoutStatus(e,t){const a=await this.client.call("vaultProvider_getPegoutStatus",e,t);return re(a),a}}async function le(n,e){const[t,a]=await n.multicall({contracts:[{address:e,abi:c,functionName:"protocolParams"},{address:e,abi:c,functionName:"applicationRegistry"}],allowFailure:!1});return{protocolParams:t,applicationRegistry:a}}const x=65535;function P(n){return{timelockAssert:n.timelockAssert,timelockChallengeAssert:n.timelockChallengeAssert,securityCouncilKeys:[...n.securityCouncilKeys],councilQuorum:n.councilQuorum,feeRate:n.feeRate,babeTotalInstances:n.babeTotalInstances,babeInstancesToFinalize:n.babeInstancesToFinalize,minVpCommissionBps:n.minVpCommissionBps,tRefund:n.tRefund,tStale:n.tStale,minPeginFeeRate:n.minPeginFeeRate,proverProgramVersion:n.proverProgramVersion,minPrepeginDepth:n.minPrepeginDepth}}function A(n){return{minimumPegInAmount:n.minimumPegInAmount,maxPegInAmount:n.maxPegInAmount,pegInAckTimeout:n.pegInAckTimeout,pegInActivationTimeout:n.pegInActivationTimeout,maxHtlcOutputCount:n.maxHtlcOutputCount}}function C(n){if(n>BigInt(x))throw new Error(`timelockAssert value ${n} exceeds uint16 max (${x})`);return Number(n)}class pe{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getTBVProtocolParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:l,functionName:"getTBVProtocolParams"});return A(e)}async getLatestOffchainParams(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:l,functionName:"getLatestOffchainParams"});return P(e)}async getOffchainParamsByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:l,functionName:"getOffchainParamsByVersion",args:[e]});return P(t)}async getLatestOffchainParamsVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:l,functionName:"latestOffchainParamsVersion"})}async getTimelockPeginByVersion(e){const t=await this.getOffchainParamsByVersion(e);return C(t.timelockAssert)}async getPegInConfiguration(){const e=await this.publicClient.multicall({contracts:[{address:this.contractAddress,abi:l,functionName:"getTBVProtocolParams"},{address:this.contractAddress,abi:l,functionName:"getLatestOffchainParams"}],allowFailure:!1}),t=A(e[0]),a=P(e[1]);return{minimumPegInAmount:t.minimumPegInAmount,maxPegInAmount:t.maxPegInAmount,pegInAckTimeout:t.pegInAckTimeout,pegInActivationTimeout:t.pegInActivationTimeout,maxHtlcOutputCount:t.maxHtlcOutputCount,timelockPegin:C(a.timelockAssert),timelockRefund:a.tRefund,minVpCommissionBps:a.minVpCommissionBps,offchainParams:a}}}function f(n){return n.map(e=>({ethAddress:e.ethAddress,btcPubKey:e.btcPubKey}))}class ue{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultKeepersByVersion(e,t){const a=await this.publicClient.readContract({address:this.contractAddress,abi:m,functionName:"getVaultKeepersByVersion",args:[e,t]});return f(a)}async getCurrentVaultKeepers(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:m,functionName:"getCurrentVaultKeepers",args:[e]});return f(t)}async getCurrentVaultKeepersVersion(e){return await this.publicClient.readContract({address:this.contractAddress,abi:m,functionName:"getCurrentVaultKeepersVersion",args:[e]})}}class ce{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getUniversalChallengersByVersion(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:l,functionName:"getUniversalChallengersByVersion",args:[e]});return f(t)}async getCurrentUniversalChallengers(){const e=await this.publicClient.readContract({address:this.contractAddress,abi:l,functionName:"getCurrentUniversalChallengers"});return f(e)}async getLatestUniversalChallengersVersion(){return await this.publicClient.readContract({address:this.contractAddress,abi:l,functionName:"latestUniversalChallengersVersion"})}}class ye{constructor(e,t){this.publicClient=e,this.contractAddress=t}async getVaultBasicInfo(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:c,functionName:"getBtcVaultBasicInfo",args:[e]});return{depositor:t[0],depositorBtcPubKey:t[1],amount:t[2],vaultProvider:t[3],status:t[4],applicationEntryPoint:t[5],createdAt:t[6]}}async getVaultProtocolInfo(e){const t=await this.publicClient.readContract({address:this.contractAddress,abi:c,functionName:"getBtcVaultProtocolInfo",args:[e]});return{depositorSignedPeginTx:t[0],universalChallengersVersion:t[1],appVaultKeepersVersion:t[2],offchainParamsVersion:t[3],verifiedAt:t[4],depositorWotsPkHash:t[5],hashlock:t[6],htlcVout:t[7],depositorPopSignature:t[8],prePeginTxHash:t[9],vaultProviderCommissionBps:t[10]}}async getVaultData(e){const[t,a]=await Promise.all([this.getVaultBasicInfo(e),this.getVaultProtocolInfo(e)]);if(!a.depositorSignedPeginTx||a.depositorSignedPeginTx==="0x")throw new Error(`Vault ${e} not found on-chain or has no pegin transaction`);return{basic:t,protocol:a}}}exports.ApplicationRegistryABI=m;exports.BTCVaultRegistryABI=c;exports.MEMPOOL_API_URLS=k;exports.ProtocolParamsABI=l;exports.VaultProviderRpcClient=oe;exports.ViemProtocolParamsReader=pe;exports.ViemUniversalChallengerReader=ce;exports.ViemVaultKeeperReader=ue;exports.ViemVaultRegistryReader=ye;exports.VpResponseValidationError=r;exports.getAddressTxs=X;exports.getAddressUtxos=L;exports.getMempoolApiUrl=q;exports.getNetworkFees=W;exports.getTxHex=D;exports.getTxInfo=R;exports.getUtxoInfo=H;exports.pushTx=U;exports.resolveProtocolAddresses=le;
|
|
2
|
-
//# sourceMappingURL=index-DpKhuCta.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index-DpKhuCta.cjs","sources":["../src/tbv/core/clients/mempool/mempoolApi.ts","../src/tbv/core/contracts/abis/ApplicationRegistry.abi.ts","../src/tbv/core/contracts/abis/BTCVaultRegistry.abi.ts","../src/tbv/core/contracts/abis/ProtocolParams.abi.ts","../src/tbv/core/clients/vault-provider/validators.ts","../src/tbv/core/clients/vault-provider/api.ts","../src/tbv/core/clients/eth/contract-address-resolver.ts","../src/tbv/core/clients/eth/protocol-params-reader.ts","../src/tbv/core/clients/eth/signer-set-reader.ts","../src/tbv/core/clients/eth/vault-registry-reader.ts"],"sourcesContent":["/**\n * Mempool API Client\n *\n * Client for interacting with mempool.space API for Bitcoin network operations.\n * Used for broadcasting transactions and fetching UTXO data.\n *\n * @module clients/mempool/mempoolApi\n */\n\nimport type { MempoolUTXO, NetworkFees, TxInfo, UtxoInfo } from \"./types\";\n\n/** Maximum valid satoshi value: 21 million BTC × 10^8 sats/BTC */\nconst MAX_SATOSHIS = 21_000_000 * 1e8;\n\n/** Timeout for mempool API requests — prevents indefinite hangs from stalled endpoints */\nconst MEMPOOL_REQUEST_TIMEOUT_MS = 30_000;\n\n/**\n * Fetch wrapper with AbortController-based timeout.\n * Ensures all mempool API requests fail bounded rather than hanging indefinitely.\n */\nasync function fetchWithTimeout(\n url: string,\n options?: RequestInit,\n): Promise<Response> {\n const controller = new AbortController();\n const timeoutId = setTimeout(\n () => controller.abort(),\n MEMPOOL_REQUEST_TIMEOUT_MS,\n );\n\n // Compose timeout signal with any caller-supplied signal so both can cancel\n const signals = [controller.signal, options?.signal].filter(\n Boolean,\n ) as AbortSignal[];\n\n try {\n // Don't clear timeout here — let it cover body consumption by callers\n return await fetch(url, {\n ...options,\n signal: AbortSignal.any(signals),\n });\n } catch (error) {\n clearTimeout(timeoutId);\n if (\n error != null &&\n typeof error === \"object\" &&\n \"name\" in error &&\n error.name === \"AbortError\"\n ) {\n throw new Error(\n `Mempool API request timed out after ${MEMPOOL_REQUEST_TIMEOUT_MS}ms: ${url}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Maximum sane fee rate in sat/vByte.\n * The April 2024 Runes spike peaked around 1,805 sat/vB — 10,000 provides ample headroom.\n */\nconst MAX_FEE_RATE = 10_000;\n\nfunction isValidSatoshiValue(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_SATOSHIS;\n}\n\nfunction isValidFeeRate(value: number): boolean {\n return Number.isInteger(value) && value > 0 && value <= MAX_FEE_RATE;\n}\n\nfunction isValidVout(vout: number, outputCount?: number): boolean {\n if (!Number.isInteger(vout) || vout < 0) return false;\n return outputCount === undefined || vout < outputCount;\n}\n\n/**\n * Default mempool API URLs by network.\n */\nexport const MEMPOOL_API_URLS = {\n mainnet: \"https://mempool.space/api\",\n testnet: \"https://mempool.space/testnet/api\",\n signet: \"https://mempool.space/signet/api\",\n} as const;\n\n/**\n * Fetch wrapper with error handling.\n */\nasync function fetchApi<T>(\n url: string,\n options?: RequestInit,\n): Promise<T> {\n try {\n const response = await fetchWithTimeout(url, options);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n const contentType = response.headers.get(\"content-type\");\n if (contentType?.includes(\"application/json\")) {\n return (await response.json()) as T;\n } else {\n return (await response.text()) as T;\n }\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to fetch from mempool API: ${error.message}`);\n }\n throw new Error(\"Failed to fetch from mempool API: Unknown error\");\n }\n}\n\n/**\n * Push a signed transaction to the Bitcoin network.\n *\n * @param txHex - The signed transaction hex string\n * @param apiUrl - Mempool API base URL\n * @returns The transaction ID\n * @throws Error if broadcasting fails\n */\nexport async function pushTx(txHex: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx`, {\n method: \"POST\",\n body: txHex,\n headers: {\n \"Content-Type\": \"text/plain\",\n },\n });\n\n if (!response.ok) {\n const errorText = await response.text();\n // Try to extract error message from response using robust JSON parsing\n let message: string | undefined;\n try {\n const errorJson = JSON.parse(errorText);\n message = errorJson.message;\n } catch {\n // Not JSON, use raw text\n message = errorText;\n }\n throw new Error(\n message || `Failed to broadcast transaction: ${response.statusText}`,\n );\n }\n\n // Response is the transaction ID (plain text)\n const txId = await response.text();\n return txId;\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to broadcast BTC transaction: ${error.message}`);\n }\n throw new Error(\"Failed to broadcast BTC transaction: Unknown error\");\n }\n}\n\n/**\n * Get transaction information from mempool.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns Transaction information\n */\nexport async function getTxInfo(txid: string, apiUrl: string): Promise<TxInfo> {\n return fetchApi<TxInfo>(`${apiUrl}/tx/${txid}`);\n}\n\n/**\n * Get the hex representation of a transaction.\n *\n * @param txid - The transaction ID\n * @param apiUrl - Mempool API base URL\n * @returns The transaction hex string\n * @throws Error if the request fails or transaction is not found\n */\nexport async function getTxHex(txid: string, apiUrl: string): Promise<string> {\n try {\n const response = await fetchWithTimeout(`${apiUrl}/tx/${txid}/hex`);\n\n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(\n `Mempool API error (${response.status}): ${errorText || response.statusText}`,\n );\n }\n\n return await response.text();\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(`Failed to get transaction hex for ${txid}: ${error.message}`);\n }\n throw new Error(`Failed to get transaction hex for ${txid}: Unknown error`);\n }\n}\n\n/**\n * Get UTXO information for a specific transaction output.\n *\n * This is used for constructing PSBTs where we need the witnessUtxo data.\n * Only supports Taproot (P2TR) and native SegWit (P2WPKH, P2WSH) script types.\n *\n * @param txid - The transaction ID containing the UTXO\n * @param vout - The output index\n * @param apiUrl - Mempool API base URL\n * @returns UTXO information with value and scriptPubKey\n */\nexport async function getUtxoInfo(\n txid: string,\n vout: number,\n apiUrl: string,\n): Promise<UtxoInfo> {\n const txInfo = await getTxInfo(txid, apiUrl);\n\n if (!isValidVout(vout, txInfo.vout.length)) {\n throw new Error(\n `Invalid vout ${vout} for transaction ${txid} (has ${txInfo.vout.length} outputs)`,\n );\n }\n\n const output = txInfo.vout[vout];\n if (!isValidSatoshiValue(output.value)) {\n throw new Error(`Invalid UTXO value ${output.value} for ${txid}:${vout}`);\n }\n\n return {\n txid,\n vout,\n value: output.value,\n scriptPubKey: output.scriptpubkey,\n };\n}\n\n/**\n * Get all UTXOs for a Bitcoin address.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of UTXOs sorted by value (largest first)\n */\nexport async function getAddressUtxos(\n address: string,\n apiUrl: string,\n): Promise<MempoolUTXO[]> {\n try {\n // Fetch UTXOs for the address\n const utxos = await fetchApi<\n {\n txid: string;\n vout: number;\n value: number;\n status: {\n confirmed: boolean;\n };\n }[]\n >(`${apiUrl}/address/${address}/utxo`);\n\n // Fetch scriptPubKey for the address\n const addressInfo = await fetchApi<{\n isvalid: boolean;\n scriptPubKey: string;\n }>(`${apiUrl}/v1/validate-address/${address}`);\n\n if (!addressInfo.isvalid) {\n throw new Error(\n `Invalid Bitcoin address: ${address}. Mempool API validation failed.`,\n );\n }\n\n // Validate UTXO fields from the external API.\n // Note: upper-bound vout check is omitted because we don't fetch\n // full transactions here. Out-of-range indices surface downstream.\n for (const utxo of utxos) {\n if (!isValidVout(utxo.vout)) {\n throw new Error(`Invalid vout ${utxo.vout} for ${utxo.txid}`);\n }\n if (!isValidSatoshiValue(utxo.value)) {\n throw new Error(\n `Invalid UTXO value ${utxo.value} for ${utxo.txid}:${utxo.vout}`,\n );\n }\n }\n\n // Sort by value (largest first) and map to our UTXO format\n const sortedUTXOs = utxos.sort((a, b) => b.value - a.value);\n\n return sortedUTXOs.map((utxo) => ({\n txid: utxo.txid,\n vout: utxo.vout,\n value: utxo.value,\n scriptPubKey: addressInfo.scriptPubKey,\n confirmed: utxo.status.confirmed,\n }));\n } catch (error) {\n if (error instanceof Error) {\n throw new Error(\n `Failed to get UTXOs for address ${address}: ${error.message}`,\n );\n }\n throw new Error(\n `Failed to get UTXOs for address ${address}: Unknown error`,\n );\n }\n}\n\n/**\n * Get the mempool API URL for a given network.\n *\n * @param network - Bitcoin network (mainnet, testnet, signet)\n * @returns The mempool API URL\n */\nexport function getMempoolApiUrl(\n network: \"mainnet\" | \"testnet\" | \"signet\",\n): string {\n return MEMPOOL_API_URLS[network];\n}\n\n/**\n * Transaction summary from address transactions endpoint.\n */\nexport interface AddressTx {\n txid: string;\n status: {\n confirmed: boolean;\n block_height?: number;\n };\n}\n\n/**\n * Get recent transactions for a Bitcoin address.\n *\n * Returns the last 25 confirmed transactions plus any unconfirmed (mempool) transactions.\n * This is useful for checking if a specific transaction has been broadcast.\n *\n * @param address - The Bitcoin address\n * @param apiUrl - Mempool API base URL\n * @returns Array of recent transactions\n */\nexport async function getAddressTxs(\n address: string,\n apiUrl: string,\n): Promise<AddressTx[]> {\n return fetchApi<AddressTx[]>(`${apiUrl}/address/${address}/txs`);\n}\n\n/**\n * Fetches Bitcoin network fee recommendations from mempool.space API.\n *\n * @param apiUrl - Mempool API base URL\n * @returns Fee rates in sat/vbyte for different confirmation times\n * @throws Error if request fails or returns invalid data\n *\n * @see https://mempool.space/docs/api/rest#get-recommended-fees\n */\nexport async function getNetworkFees(apiUrl: string): Promise<NetworkFees> {\n const response = await fetchWithTimeout(`${apiUrl}/v1/fees/recommended`);\n\n if (!response.ok) {\n throw new Error(\n `Failed to fetch network fees: ${response.status} ${response.statusText}`,\n );\n }\n\n const data = await response.json();\n\n const feeFields = [\n \"fastestFee\",\n \"halfHourFee\",\n \"hourFee\",\n \"economyFee\",\n \"minimumFee\",\n ] as const;\n\n for (const field of feeFields) {\n if (!isValidFeeRate(data[field])) {\n throw new Error(\n `Invalid fee rate ${field}=${data[field]} from mempool API: expected a positive number ≤ ${MAX_FEE_RATE}`,\n );\n }\n }\n\n if (\n data.minimumFee > data.economyFee ||\n data.economyFee > data.hourFee ||\n data.hourFee > data.halfHourFee ||\n data.halfHourFee > data.fastestFee\n ) {\n throw new Error(\n `Fee rate ordering violation from mempool API: expected ` +\n `minimumFee (${data.minimumFee}) <= economyFee (${data.economyFee}) <= ` +\n `hourFee (${data.hourFee}) <= halfHourFee (${data.halfHourFee}) <= ` +\n `fastestFee (${data.fastestFee}).`,\n );\n }\n\n return data as NetworkFees;\n}\n\n","/**\n * ApplicationRegistry Contract ABI\n *\n * Minimal ABI containing only the vault keeper read functions needed by the SDK.\n * Generated from vault-contracts-aave-v4 IApplicationRegistry.sol interface.\n *\n * @module contracts/abis/ApplicationRegistry\n */\n\nexport const ApplicationRegistryABI = [\n {\n type: \"function\",\n name: \"getVaultKeepersByVersion\",\n inputs: [\n {\n name: \"appEntryPoint\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"versionNumber\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"tuple[]\",\n internalType: \"struct BTCVaultTypes.AddressBTCKeyPair[]\",\n components: [\n {\n name: \"ethAddress\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"btcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getCurrentVaultKeepers\",\n inputs: [\n {\n name: \"appEntryPoint\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"tuple[]\",\n internalType: \"struct BTCVaultTypes.AddressBTCKeyPair[]\",\n components: [\n {\n name: \"ethAddress\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"btcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getCurrentVaultKeepersVersion\",\n inputs: [\n {\n name: \"appEntryPoint\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n","/**\n * BTCVaultRegistry Contract ABI\n *\n * Minimal ABI containing only the functions needed by the SDK.\n * Full ABI is available in the vault service package.\n *\n * @module contracts/abis/BTCVaultRegistry\n */\n\n/**\n * Minimal ABI for BTCVaultRegistry contract.\n * Contains submitPeginRequest, submitPeginRequestBatch, activateVaultWithSecret, getPegInFee, and getBtcVaultBasicInfo.\n */\nexport const BTCVaultRegistryABI = [\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequest\",\n inputs: [\n {\n name: \"depositor\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"depositorBtcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"btcPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"unsignedPrePeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"referralCode\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"depositorPayoutBtcAddress\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"submitPeginRequestBatch\",\n inputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n {\n name: \"requests\",\n type: \"tuple[]\",\n internalType: \"struct IBTCVaultRegistry.BatchPeginRequest[]\",\n components: [\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"btcPopSignature\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"unsignedPrePeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorSignedPeginTx\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"hashlock\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"htlcVout\", type: \"uint8\", internalType: \"uint8\" },\n { name: \"referralCode\", type: \"uint32\", internalType: \"uint32\" },\n { name: \"depositorPayoutBtcAddress\", type: \"bytes\", internalType: \"bytes\" },\n { name: \"depositorWotsPkHash\", type: \"bytes32\", internalType: \"bytes32\" },\n ],\n },\n ],\n outputs: [\n { name: \"vaultIds\", type: \"bytes32[]\", internalType: \"bytes32[]\" },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"activateVaultWithSecret\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"s\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"activationMetadata\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getPegInFee\",\n inputs: [\n {\n name: \"vaultProvider\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"totalFee\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getBtcVaultBasicInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n { name: \"depositor\", type: \"address\", internalType: \"address\" },\n { name: \"depositorBtcPubKey\", type: \"bytes32\", internalType: \"bytes32\" },\n { name: \"amount\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"vaultProvider\", type: \"address\", internalType: \"address\" },\n { name: \"status\", type: \"uint8\", internalType: \"enum IBTCVaultRegistry.BTCVaultStatus\" },\n { name: \"applicationEntryPoint\", type: \"address\", internalType: \"address\" },\n { name: \"createdAt\", type: \"uint256\", internalType: \"uint256\" },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"error\",\n name: \"InvalidPeginFee\",\n inputs: [\n {\n name: \"provided\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"required\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n ],\n },\n {\n type: \"error\",\n name: \"InvalidSecret\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"ActivationDeadlineExpired\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"DuplicateHashlock\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"CapExceeded\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"InvalidOutputIndex\",\n inputs: [],\n },\n {\n type: \"error\",\n name: \"PeginSignaturesIncomplete\",\n inputs: [],\n },\n {\n type: \"function\",\n name: \"getBtcVaultProtocolInfo\",\n inputs: [\n {\n name: \"vaultId\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"depositorSignedPeginTx\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"universalChallengersVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"appVaultKeepersVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"offchainParamsVersion\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"verifiedAt\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"depositorWotsPkHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"hashlock\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"htlcVout\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"depositorPopSignature\",\n type: \"bytes\",\n internalType: \"bytes\",\n },\n {\n name: \"prePeginTxHash\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"vaultProviderCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"protocolParams\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"address\",\n internalType: \"contract IProtocolParams\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"applicationRegistry\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"address\",\n internalType: \"contract IApplicationRegistry\",\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n","/**\n * ProtocolParams Contract ABI\n *\n * Minimal ABI containing only the read functions needed by the SDK.\n * Generated from vault-contracts-aave-v4 IProtocolParams.sol interface.\n *\n * @module contracts/abis/ProtocolParams\n */\n\nexport const ProtocolParamsABI = [\n {\n type: \"function\",\n name: \"getTBVProtocolParams\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n internalType: \"struct IProtocolParams.TBVProtocolParams\",\n components: [\n {\n name: \"minimumPegInAmount\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"maxPegInAmount\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"pegInAckTimeout\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"pegInActivationTimeout\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"maxHtlcOutputCount\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getLatestOffchainParams\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n internalType: \"struct IProtocolParams.VersionedOffchainParams\",\n components: [\n {\n name: \"timelockAssert\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"timelockChallengeAssert\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"securityCouncilKeys\",\n type: \"bytes32[]\",\n internalType: \"bytes32[]\",\n },\n {\n name: \"councilQuorum\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"feeRate\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"babeTotalInstances\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"babeInstancesToFinalize\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"minVpCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"tRefund\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"tStale\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"minPeginFeeRate\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"proverProgramVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"minPrepeginDepth\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getOffchainParamsByVersion\",\n inputs: [\n {\n name: \"versionNumber\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"tuple\",\n internalType: \"struct IProtocolParams.VersionedOffchainParams\",\n components: [\n {\n name: \"timelockAssert\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"timelockChallengeAssert\",\n type: \"uint256\",\n internalType: \"uint256\",\n },\n {\n name: \"securityCouncilKeys\",\n type: \"bytes32[]\",\n internalType: \"bytes32[]\",\n },\n {\n name: \"councilQuorum\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"feeRate\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"babeTotalInstances\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"babeInstancesToFinalize\",\n type: \"uint8\",\n internalType: \"uint8\",\n },\n {\n name: \"minVpCommissionBps\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"tRefund\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"tStale\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n {\n name: \"minPeginFeeRate\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n {\n name: \"proverProgramVersion\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n {\n name: \"minPrepeginDepth\",\n type: \"uint32\",\n internalType: \"uint32\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"latestOffchainParamsVersion\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getUniversalChallengersByVersion\",\n inputs: [\n {\n name: \"versionNumber\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"tuple[]\",\n internalType: \"struct BTCVaultTypes.AddressBTCKeyPair[]\",\n components: [\n {\n name: \"ethAddress\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"btcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"getCurrentUniversalChallengers\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"tuple[]\",\n internalType: \"struct BTCVaultTypes.AddressBTCKeyPair[]\",\n components: [\n {\n name: \"ethAddress\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"btcPubKey\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"latestUniversalChallengersVersion\",\n inputs: [],\n outputs: [\n {\n name: \"\",\n type: \"uint16\",\n internalType: \"uint16\",\n },\n ],\n stateMutability: \"view\",\n },\n] as const;\n","/**\n * Runtime validation for vault provider RPC responses.\n *\n * All VP RPC methods return untyped JSON that TypeScript generics cast without\n * inspection. These validators check the critical top-level fields and\n * security-relevant values (status, txids, pubkeys). Optional progress\n * sub-fields (gc_data, ack_collection, claimer_graphs) are NOT validated\n * since they are informational and not used for signing or transaction\n * construction. Only `progress.presigning` sub-fields are checked.\n */\n\nimport { DaemonStatus } from \"./types\";\nimport type {\n GetPeginStatusResponse,\n GetPegoutStatusResponse,\n RequestDepositorClaimerArtifactsResponse,\n RequestDepositorPresignTransactionsResponse,\n} from \"./types\";\n\nconst DAEMON_STATUS_VALUES = new Set<string>(Object.values(DaemonStatus));\n\nconst VP_ERROR_PREVIEW_MAX_LEN = 200;\n\nfunction preview(value: unknown): string {\n return (\n JSON.stringify(value)?.slice(0, VP_ERROR_PREVIEW_MAX_LEN) ?? \"undefined\"\n );\n}\n\nconst VP_VALIDATION_USER_MESSAGE =\n \"The vault provider returned an unexpected response. Please try again or contact support.\";\n\n/**\n * Thrown when a VP RPC response fails runtime validation.\n *\n * `.message` is a user-facing string safe to display in the UI.\n * `.detail` contains the technical reason, suitable for logging.\n */\nexport class VpResponseValidationError extends Error {\n readonly detail: string;\n\n constructor(detail: string) {\n super(VP_VALIDATION_USER_MESSAGE);\n this.name = \"VpResponseValidationError\";\n this.detail = detail;\n }\n}\n\n/** Non-empty string of hexadecimal characters (case-insensitive). */\nconst HEX_RE = /^[0-9a-fA-F]+$/;\n\n/** Expected length (in hex chars) of an x-only Bitcoin public key (32 bytes). */\nconst X_ONLY_PUBKEY_HEX_LEN = 64;\n/** Expected length (in hex chars) of a compressed Bitcoin public key (33 bytes). */\nconst COMPRESSED_PUBKEY_HEX_LEN = 66;\n\n/** Expected length (in hex chars) of a Bitcoin transaction ID (32 bytes). */\nconst TXID_HEX_LEN = 64;\n\nfunction isNonEmptyHex(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0 && HEX_RE.test(value);\n}\n\nfunction isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction assertNonEmptyHex(value: unknown, field: string): void {\n if (!isNonEmptyHex(value)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a non-empty hex string, got ${preview(value)}`,\n );\n }\n}\n\nfunction assertNonEmptyString(value: unknown, field: string): void {\n if (!isNonEmptyString(value)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a non-empty string, got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Accept both x-only (64-char) and compressed (66-char) pubkeys from VP responses.\n * The signing code normalizes to x-only via processPublicKeyToXOnly().\n */\nfunction assertBtcPubkey(value: unknown, field: string): void {\n if (\n !isNonEmptyHex(value) ||\n (value.length !== X_ONLY_PUBKEY_HEX_LEN &&\n value.length !== COMPRESSED_PUBKEY_HEX_LEN)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be a ${X_ONLY_PUBKEY_HEX_LEN} or ${COMPRESSED_PUBKEY_HEX_LEN}-char hex string (BTC pubkey), got ${preview(value)}`,\n );\n }\n}\n\n/**\n * Validate the optional presigning progress fields returned inside PeginProgressDetails.\n */\nfunction validatePresigningProgressFields(\n progress: Record<string, unknown>,\n): void {\n const presigning = progress.presigning;\n if (presigning === undefined || presigning === null) return;\n if (typeof presigning !== \"object\" || Array.isArray(presigning)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning\" must be an object if present`,\n );\n }\n\n const p = presigning as Record<string, unknown>;\n\n if (\n p.depositor_graph_created !== undefined &&\n typeof p.depositor_graph_created !== \"boolean\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.depositor_graph_created\" must be a boolean if present, got ${preview(p.depositor_graph_created)}`,\n );\n }\n\n if (\n p.vk_challenger_presigning_completed !== undefined &&\n typeof p.vk_challenger_presigning_completed !== \"number\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.vk_challenger_presigning_completed\" must be a number if present, got ${preview(p.vk_challenger_presigning_completed)}`,\n );\n }\n\n if (\n p.vk_challenger_presigning_total !== undefined &&\n typeof p.vk_challenger_presigning_total !== \"number\"\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress.presigning.vk_challenger_presigning_total\" must be a number if present, got ${preview(p.vk_challenger_presigning_total)}`,\n );\n }\n}\n\n/**\n * Validate a getPeginStatus response.\n *\n * Throws if the status field is not a recognized DaemonStatus value.\n */\nexport function validateGetPeginStatusResponse(\n response: unknown,\n): asserts response is GetPeginStatusResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: getPeginStatus response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyHex(r.pegin_txid) || r.pegin_txid.length !== TXID_HEX_LEN) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string (txid), got ${preview(r.pegin_txid)}`,\n );\n }\n\n if (typeof r.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"status\" must be a string`,\n );\n }\n\n if (!DAEMON_STATUS_VALUES.has(r.status)) {\n throw new VpResponseValidationError(\n `VP response validation failed: unrecognized status \"${r.status}\". Expected one of: ${[...DAEMON_STATUS_VALUES].join(\", \")}`,\n );\n }\n\n if (\n r.progress === null ||\n typeof r.progress !== \"object\" ||\n Array.isArray(r.progress)\n ) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"progress\" must be an object`,\n );\n }\n\n validatePresigningProgressFields(r.progress as Record<string, unknown>);\n\n if (typeof r.health_info !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"health_info\" must be a string`,\n );\n }\n\n if (r.last_error !== undefined && typeof r.last_error !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"last_error\" must be a string if present, got ${preview(r.last_error)}`,\n );\n }\n}\n\n/**\n * Validate a requestDepositorPresignTransactions response.\n */\nexport function validateRequestDepositorPresignTransactionsResponse(\n response: unknown,\n): asserts response is RequestDepositorPresignTransactionsResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: requestDepositorPresignTransactions response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!Array.isArray(r.txs)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"txs\" must be an array`,\n );\n }\n\n for (let i = 0; i < r.txs.length; i++) {\n validateClaimerTransactions(r.txs[i], `txs[${i}]`);\n }\n\n if (r.depositor_graph === null || typeof r.depositor_graph !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph\" must be an object`,\n );\n }\n\n validateDepositorGraphTransactions(\n r.depositor_graph as Record<string, unknown>,\n );\n}\n\nfunction validateTransactionData(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n const tx = value as Record<string, unknown>;\n assertNonEmptyHex(tx.tx_hex, `${field}.tx_hex`);\n}\n\nfunction validateClaimerTransactions(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const tx = value as Record<string, unknown>;\n\n assertBtcPubkey(tx.claimer_pubkey, `${field}.claimer_pubkey`);\n validateTransactionData(tx.claim_tx, `${field}.claim_tx`);\n validateTransactionData(tx.assert_tx, `${field}.assert_tx`);\n validateTransactionData(tx.payout_tx, `${field}.payout_tx`);\n assertNonEmptyString(tx.payout_psbt, `${field}.payout_psbt`);\n}\n\nfunction validateChallengeAssertConnectorData(\n value: unknown,\n field: string,\n): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const c = value as Record<string, unknown>;\n assertNonEmptyString(c.wots_pks_json, `${field}.wots_pks_json`);\n assertNonEmptyString(c.gc_wots_keys_json, `${field}.gc_wots_keys_json`);\n}\n\nfunction validatePresignDataPerChallenger(value: unknown, field: string): void {\n if (value === null || typeof value !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}\" must be an object`,\n );\n }\n\n const d = value as Record<string, unknown>;\n\n assertBtcPubkey(d.challenger_pubkey, `${field}.challenger_pubkey`);\n validateTransactionData(\n d.challenge_assert_x_tx,\n `${field}.challenge_assert_x_tx`,\n );\n validateTransactionData(\n d.challenge_assert_y_tx,\n `${field}.challenge_assert_y_tx`,\n );\n validateTransactionData(d.nopayout_tx, `${field}.nopayout_tx`);\n assertNonEmptyString(d.nopayout_psbt, `${field}.nopayout_psbt`);\n\n if (!Array.isArray(d.challenge_assert_connectors)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.challenge_assert_connectors\" must be an array`,\n );\n }\n\n for (let i = 0; i < d.challenge_assert_connectors.length; i++) {\n validateChallengeAssertConnectorData(\n d.challenge_assert_connectors[i],\n `${field}.challenge_assert_connectors[${i}]`,\n );\n }\n\n if (!Array.isArray(d.output_label_hashes)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"${field}.output_label_hashes\" must be an array`,\n );\n }\n\n for (let i = 0; i < d.output_label_hashes.length; i++) {\n assertNonEmptyHex(\n d.output_label_hashes[i],\n `${field}.output_label_hashes[${i}]`,\n );\n }\n}\n\n/**\n * Validate a requestDepositorClaimerArtifacts response.\n */\nexport function validateRequestDepositorClaimerArtifactsResponse(\n response: unknown,\n): asserts response is RequestDepositorClaimerArtifactsResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: requestDepositorClaimerArtifacts response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyString(r.tx_graph_json)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"tx_graph_json\" must be a non-empty string, got ${preview(r.tx_graph_json)}`,\n );\n }\n\n if (!isNonEmptyHex(r.verifying_key_hex)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"verifying_key_hex\" must be a non-empty hex string, got ${preview(r.verifying_key_hex)}`,\n );\n }\n\n if (r.babe_sessions === null || typeof r.babe_sessions !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions\" must be an object`,\n );\n }\n\n for (const [key, session] of Object.entries(\n r.babe_sessions as Record<string, unknown>,\n )) {\n if (session === null || typeof session !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions.${key}\" must be an object`,\n );\n }\n const s = session as Record<string, unknown>;\n if (!isNonEmptyHex(s.decryptor_artifacts_hex)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"babe_sessions.${key}.decryptor_artifacts_hex\" must be a non-empty hex string, got ${preview(s.decryptor_artifacts_hex)}`,\n );\n }\n }\n}\n\n/**\n * Validate a getPegoutStatus response.\n */\nexport function validateGetPegoutStatusResponse(\n response: unknown,\n): asserts response is GetPegoutStatusResponse {\n if (response === null || typeof response !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: getPegoutStatus response is not an object`,\n );\n }\n\n const r = response as Record<string, unknown>;\n\n if (!isNonEmptyHex(r.pegin_txid) || r.pegin_txid.length !== TXID_HEX_LEN) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"pegin_txid\" must be a ${TXID_HEX_LEN}-char hex string (txid), got ${preview(r.pegin_txid)}`,\n );\n }\n\n if (typeof r.found !== \"boolean\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"found\" must be a boolean, got ${preview(r.found)}`,\n );\n }\n\n if (r.claimer !== undefined) {\n if (r.claimer === null || typeof r.claimer !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer\" must be an object if present`,\n );\n }\n const claimer = r.claimer as Record<string, unknown>;\n if (typeof claimer.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.status\" must be a string, got ${preview(claimer.status)}`,\n );\n }\n if (typeof claimer.failed !== \"boolean\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"claimer.failed\" must be a boolean, got ${preview(claimer.failed)}`,\n );\n }\n }\n\n if (r.challenger !== undefined) {\n if (r.challenger === null || typeof r.challenger !== \"object\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challenger\" must be an object if present`,\n );\n }\n const challenger = r.challenger as Record<string, unknown>;\n if (typeof challenger.status !== \"string\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"challenger.status\" must be a string, got ${preview(challenger.status)}`,\n );\n }\n }\n}\n\nfunction validateDepositorGraphTransactions(\n graph: Record<string, unknown>,\n): void {\n validateTransactionData(graph.claim_tx, \"depositor_graph.claim_tx\");\n validateTransactionData(graph.assert_tx, \"depositor_graph.assert_tx\");\n validateTransactionData(graph.payout_tx, \"depositor_graph.payout_tx\");\n assertNonEmptyString(graph.payout_psbt, \"depositor_graph.payout_psbt\");\n\n if (!Array.isArray(graph.challenger_presign_data)) {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph.challenger_presign_data\" must be an array`,\n );\n }\n\n for (let i = 0; i < graph.challenger_presign_data.length; i++) {\n validatePresignDataPerChallenger(\n graph.challenger_presign_data[i],\n `depositor_graph.challenger_presign_data[${i}]`,\n );\n }\n\n if (typeof graph.offchain_params_version !== \"number\") {\n throw new VpResponseValidationError(\n `VP response validation failed: \"depositor_graph.offchain_params_version\" must be a number`,\n );\n }\n}\n","/**\n * JSON-RPC client for the Vault Provider API.\n *\n * Wraps {@link JsonRpcClient} with typed methods matching the\n * `vaultProvider_*` RPC namespace defined in the btc-vault pegin spec.\n *\n * Implements the narrow service interfaces (PeginStatusReader, WotsKeySubmitter,\n * PresignClient, ClaimerArtifactsReader) so it can be passed directly to\n * any deposit protocol service function.\n *\n * @see https://github.com/babylonlabs-io/btc-vault/blob/main/docs/pegin.md\n */\n\nimport type { PeginStatusReader, WotsKeySubmitter, PresignClient, ClaimerArtifactsReader } from \"../../services/deposit/interfaces\";\n\nimport { JsonRpcClient, type JsonRpcClientConfig } from \"./json-rpc-client\";\nimport type {\n GetPeginStatusParams,\n GetPeginStatusResponse,\n GetPegoutStatusParams,\n GetPegoutStatusResponse,\n RequestDepositorClaimerArtifactsParams,\n RequestDepositorClaimerArtifactsResponse,\n RequestDepositorPresignTransactionsParams,\n RequestDepositorPresignTransactionsResponse,\n SubmitDepositorPresignaturesParams,\n SubmitDepositorWotsKeyParams,\n} from \"./types\";\nimport {\n validateGetPeginStatusResponse,\n validateGetPegoutStatusResponse,\n validateRequestDepositorClaimerArtifactsResponse,\n validateRequestDepositorPresignTransactionsResponse,\n} from \"./validators\";\n\nexport interface VaultProviderRpcClientOptions {\n /** Timeout in milliseconds per request (default: 60000) */\n timeout?: number;\n /** Number of retry attempts for safe methods (default: 3) */\n retries?: number;\n /** Initial retry delay in milliseconds (default: 1000) */\n retryDelay?: number;\n /** Custom retry predicate (default: only retry get* status methods) */\n retryableFor?: (method: string) => boolean;\n /** Custom headers */\n headers?: Record<string, string>;\n}\n\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * Concrete VP RPC client implementing all service interfaces.\n *\n * Usage:\n * ```ts\n * const client = new VaultProviderRpcClient(\"https://vp.example.com/rpc\");\n * const status = await client.getPeginStatus({ pegin_txid: \"abc...\" });\n * ```\n */\nexport class VaultProviderRpcClient\n implements PeginStatusReader, WotsKeySubmitter, PresignClient, ClaimerArtifactsReader\n{\n private client: JsonRpcClient;\n\n constructor(baseUrl: string, options?: VaultProviderRpcClientOptions) {\n const config: JsonRpcClientConfig = {\n baseUrl,\n timeout: options?.timeout ?? DEFAULT_TIMEOUT_MS,\n retries: options?.retries,\n retryDelay: options?.retryDelay,\n retryableFor: options?.retryableFor,\n headers: options?.headers,\n };\n this.client = new JsonRpcClient(config);\n }\n\n /**\n * Request the payout/claim/assert transactions that the depositor\n * needs to pre-sign before the vault can be activated on Bitcoin.\n */\n async requestDepositorPresignTransactions(\n params: RequestDepositorPresignTransactionsParams,\n signal?: AbortSignal,\n ): Promise<RequestDepositorPresignTransactionsResponse> {\n const response = await this.client.call<\n RequestDepositorPresignTransactionsParams,\n unknown\n >(\"vaultProvider_requestDepositorPresignTransactions\", params, signal);\n validateRequestDepositorPresignTransactionsResponse(response);\n return response;\n }\n\n /**\n * Submit the depositor's pre-signatures for the payout transactions\n * and the depositor-as-claimer graph.\n */\n async submitDepositorPresignatures(\n params: SubmitDepositorPresignaturesParams,\n signal?: AbortSignal,\n ): Promise<void> {\n return this.client.call<SubmitDepositorPresignaturesParams, void>(\n \"vaultProvider_submitDepositorPresignatures\",\n params,\n signal,\n );\n }\n\n /**\n * Submit the depositor's WOTS public key to the vault provider.\n * Called after the pegin is finalized on Ethereum, when the VP is in\n * `PendingDepositorWotsPK` status.\n */\n async submitDepositorWotsKey(\n params: SubmitDepositorWotsKeyParams,\n signal?: AbortSignal,\n ): Promise<void> {\n return this.client.call<SubmitDepositorWotsKeyParams, void>(\n \"vaultProvider_submitDepositorWotsKey\",\n params,\n signal,\n );\n }\n\n /**\n * Request the BaBe DecryptorArtifacts needed for the depositor to\n * independently evaluate garbled circuits during a challenge.\n */\n async requestDepositorClaimerArtifacts(\n params: RequestDepositorClaimerArtifactsParams,\n signal?: AbortSignal,\n ): Promise<RequestDepositorClaimerArtifactsResponse> {\n const response = await this.client.call<\n RequestDepositorClaimerArtifactsParams,\n unknown\n >(\"vaultProvider_requestDepositorClaimerArtifacts\", params, signal);\n validateRequestDepositorClaimerArtifactsResponse(response);\n return response;\n }\n\n /** Get the current pegin status from the vault provider daemon. */\n async getPeginStatus(\n params: GetPeginStatusParams,\n signal?: AbortSignal,\n ): Promise<GetPeginStatusResponse> {\n const response = await this.client.call<GetPeginStatusParams, unknown>(\n \"vaultProvider_getPeginStatus\",\n params,\n signal,\n );\n validateGetPeginStatusResponse(response);\n return response;\n }\n\n /** Get the current pegout status from the vault provider daemon. */\n async getPegoutStatus(\n params: GetPegoutStatusParams,\n signal?: AbortSignal,\n ): Promise<GetPegoutStatusResponse> {\n const response = await this.client.call<GetPegoutStatusParams, unknown>(\n \"vaultProvider_getPegoutStatus\",\n params,\n signal,\n );\n validateGetPegoutStatusResponse(response);\n return response;\n }\n}\n","/**\n * Contract Address Resolver\n *\n * Resolves ProtocolParams and ApplicationRegistry contract addresses\n * from the BTCVaultRegistry contract. These addresses are needed to\n * construct the SDK's contract readers.\n *\n * @module clients/eth/contract-address-resolver\n */\n\nimport type { Address, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\n\nexport interface ProtocolAddresses {\n /** Address of the ProtocolParams contract */\n protocolParams: Address;\n /** Address of the ApplicationRegistry contract */\n applicationRegistry: Address;\n}\n\n/**\n * Resolve ProtocolParams and ApplicationRegistry addresses from BTCVaultRegistry.\n *\n * Uses a single multicall for atomicity and efficiency.\n *\n * @param publicClient - viem PublicClient instance\n * @param btcVaultRegistryAddress - Address of the BTCVaultRegistry contract\n * @returns Resolved contract addresses\n */\nexport async function resolveProtocolAddresses(\n publicClient: PublicClient,\n btcVaultRegistryAddress: Address,\n): Promise<ProtocolAddresses> {\n const [protocolParams, applicationRegistry] = await publicClient.multicall({\n contracts: [\n {\n address: btcVaultRegistryAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"protocolParams\",\n },\n {\n address: btcVaultRegistryAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"applicationRegistry\",\n },\n ],\n allowFailure: false,\n });\n\n return {\n protocolParams: protocolParams as Address,\n applicationRegistry: applicationRegistry as Address,\n };\n}\n","/**\n * Concrete ProtocolParams reader using viem's readContract and multicall.\n *\n * This is an optional utility — callers can use their own implementation\n * of the ProtocolParamsReader interface.\n */\n\nimport type { Address, Hex, PublicClient } from \"viem\";\n\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport type {\n PegInConfiguration,\n ProtocolParamsReader,\n TBVProtocolParams,\n VersionedOffchainParams,\n} from \"./types\";\n\n/**\n * Maximum value for a Solidity uint16.\n * PeginLogic.sol casts timelockAssert to uint16, so values above this are invalid.\n */\nconst UINT16_MAX = 65535;\n\n/**\n * Raw shape viem returns for VersionedOffchainParams struct.\n * viem resolves ABI struct outputs to named objects (not tuples).\n */\ninterface RawOffchainParams {\n timelockAssert: bigint;\n timelockChallengeAssert: bigint;\n securityCouncilKeys: readonly Hex[];\n councilQuorum: number;\n feeRate: bigint;\n babeTotalInstances: number;\n babeInstancesToFinalize: number;\n minVpCommissionBps: number;\n tRefund: number;\n tStale: number;\n minPeginFeeRate: bigint;\n proverProgramVersion: number;\n minPrepeginDepth: number;\n}\n\n/** Raw shape viem returns for TBVProtocolParams struct. */\ninterface RawTBVParams {\n minimumPegInAmount: bigint;\n maxPegInAmount: bigint;\n pegInAckTimeout: bigint;\n pegInActivationTimeout: bigint;\n maxHtlcOutputCount: number;\n}\n\n/** Map viem struct result to VersionedOffchainParams. */\nfunction mapOffchainParams(result: RawOffchainParams): VersionedOffchainParams {\n return {\n timelockAssert: result.timelockAssert,\n timelockChallengeAssert: result.timelockChallengeAssert,\n securityCouncilKeys: [...result.securityCouncilKeys],\n councilQuorum: result.councilQuorum,\n feeRate: result.feeRate,\n babeTotalInstances: result.babeTotalInstances,\n babeInstancesToFinalize: result.babeInstancesToFinalize,\n minVpCommissionBps: result.minVpCommissionBps,\n tRefund: result.tRefund,\n tStale: result.tStale,\n minPeginFeeRate: result.minPeginFeeRate,\n proverProgramVersion: result.proverProgramVersion,\n minPrepeginDepth: result.minPrepeginDepth,\n };\n}\n\n/** Map viem struct result to TBVProtocolParams. */\nfunction mapTBVParams(result: RawTBVParams): TBVProtocolParams {\n return {\n minimumPegInAmount: result.minimumPegInAmount,\n maxPegInAmount: result.maxPegInAmount,\n pegInAckTimeout: result.pegInAckTimeout,\n pegInActivationTimeout: result.pegInActivationTimeout,\n maxHtlcOutputCount: result.maxHtlcOutputCount,\n };\n}\n\n/**\n * Derive timelockPegin from timelockAssert.\n *\n * Matches PeginLogic.sol: `uint16(timelockAssert)`.\n * The contract validates `timelockAssert <= type(uint16).max` on write,\n * but we enforce the same bound here to reject invalid values early\n * rather than silently truncating.\n *\n * @throws if timelockAssert exceeds uint16 max (65535)\n */\nfunction deriveTimelockPegin(timelockAssert: bigint): number {\n if (timelockAssert > BigInt(UINT16_MAX)) {\n throw new Error(\n `timelockAssert value ${timelockAssert} exceeds uint16 max (${UINT16_MAX})`,\n );\n }\n return Number(timelockAssert);\n}\n\n/**\n * Concrete protocol params reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemProtocolParamsReader(publicClient, protocolParamsAddress);\n * const config = await reader.getPegInConfiguration();\n * ```\n */\nexport class ViemProtocolParamsReader implements ProtocolParamsReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getTBVProtocolParams(): Promise<TBVProtocolParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n })) as RawTBVParams;\n\n return mapTBVParams(result);\n }\n\n async getLatestOffchainParams(): Promise<VersionedOffchainParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getLatestOffchainParams\",\n })) as RawOffchainParams;\n\n return mapOffchainParams(result);\n }\n\n async getOffchainParamsByVersion(\n version: number,\n ): Promise<VersionedOffchainParams> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getOffchainParamsByVersion\",\n args: [version],\n })) as RawOffchainParams;\n\n return mapOffchainParams(result);\n }\n\n async getLatestOffchainParamsVersion(): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestOffchainParamsVersion\",\n })) as number;\n\n return result;\n }\n\n async getTimelockPeginByVersion(version: number): Promise<number> {\n const params = await this.getOffchainParamsByVersion(version);\n return deriveTimelockPegin(params.timelockAssert);\n }\n\n /**\n * Read TBV protocol params and latest offchain params atomically via multicall.\n * Prevents TOCTOU inconsistency if governance updates params between reads.\n */\n async getPegInConfiguration(): Promise<PegInConfiguration> {\n const results = await this.publicClient.multicall({\n contracts: [\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getTBVProtocolParams\",\n },\n {\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getLatestOffchainParams\",\n },\n ],\n allowFailure: false,\n });\n\n const tbvParams = mapTBVParams(results[0] as RawTBVParams);\n const offchainParams = mapOffchainParams(results[1] as RawOffchainParams);\n\n return {\n minimumPegInAmount: tbvParams.minimumPegInAmount,\n maxPegInAmount: tbvParams.maxPegInAmount,\n pegInAckTimeout: tbvParams.pegInAckTimeout,\n pegInActivationTimeout: tbvParams.pegInActivationTimeout,\n maxHtlcOutputCount: tbvParams.maxHtlcOutputCount,\n timelockPegin: deriveTimelockPegin(offchainParams.timelockAssert),\n timelockRefund: offchainParams.tRefund,\n minVpCommissionBps: offchainParams.minVpCommissionBps,\n offchainParams,\n };\n }\n}\n","/**\n * Concrete signer-set readers for vault keepers and universal challengers.\n *\n * These are optional utilities — callers can use their own implementations\n * of the VaultKeeperReader and UniversalChallengerReader interfaces.\n */\n\nimport type { Address, Hex, PublicClient } from \"viem\";\n\nimport { ApplicationRegistryABI } from \"../../contracts/abis/ApplicationRegistry.abi\";\nimport { ProtocolParamsABI } from \"../../contracts/abis/ProtocolParams.abi\";\nimport type {\n AddressBTCKeyPair,\n UniversalChallengerReader,\n VaultKeeperReader,\n} from \"./types\";\n\n/** Map viem tuple array to AddressBTCKeyPair[]. */\nfunction mapKeyPairs(\n result: readonly { ethAddress: Address; btcPubKey: Hex }[],\n): AddressBTCKeyPair[] {\n return result.map((pair) => ({\n ethAddress: pair.ethAddress,\n btcPubKey: pair.btcPubKey,\n }));\n}\n\n/**\n * Reads vault keepers from the ApplicationRegistry contract.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultKeeperReader(publicClient, applicationRegistryAddress);\n * const keepers = await reader.getCurrentVaultKeepers(appEntryPoint);\n * ```\n */\nexport class ViemVaultKeeperReader implements VaultKeeperReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getVaultKeepersByVersion(\n appEntryPoint: Address,\n version: number,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getVaultKeepersByVersion\",\n args: [appEntryPoint, version],\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentVaultKeepers(\n appEntryPoint: Address,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getCurrentVaultKeepers\",\n args: [appEntryPoint],\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentVaultKeepersVersion(\n appEntryPoint: Address,\n ): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ApplicationRegistryABI,\n functionName: \"getCurrentVaultKeepersVersion\",\n args: [appEntryPoint],\n })) as number;\n\n return result;\n }\n}\n\n/**\n * Reads universal challengers from the ProtocolParams contract.\n *\n * Usage:\n * ```ts\n * const reader = new ViemUniversalChallengerReader(publicClient, protocolParamsAddress);\n * const challengers = await reader.getCurrentUniversalChallengers();\n * ```\n */\nexport class ViemUniversalChallengerReader implements UniversalChallengerReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getUniversalChallengersByVersion(\n version: number,\n ): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getUniversalChallengersByVersion\",\n args: [version],\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getCurrentUniversalChallengers(): Promise<AddressBTCKeyPair[]> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"getCurrentUniversalChallengers\",\n })) as readonly { ethAddress: Address; btcPubKey: Hex }[];\n\n return mapKeyPairs(result);\n }\n\n async getLatestUniversalChallengersVersion(): Promise<number> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: ProtocolParamsABI,\n functionName: \"latestUniversalChallengersVersion\",\n })) as number;\n\n return result;\n }\n}\n","/**\n * Concrete BTCVaultRegistry reader using viem's readContract.\n *\n * This is an optional utility — callers can use their own implementation\n * of the VaultRegistryReader interface.\n */\n\nimport type { Address, Hex, PublicClient } from \"viem\";\n\nimport { BTCVaultRegistryABI } from \"../../contracts/abis/BTCVaultRegistry.abi\";\nimport type {\n VaultBasicInfo,\n VaultData,\n VaultProtocolInfo,\n VaultRegistryReader,\n} from \"./types\";\n\n/**\n * Concrete vault registry reader using viem.\n *\n * Usage:\n * ```ts\n * const reader = new ViemVaultRegistryReader(publicClient, registryAddress);\n * const data = await reader.getVaultData(vaultId);\n * ```\n */\nexport class ViemVaultRegistryReader implements VaultRegistryReader {\n constructor(\n private publicClient: PublicClient,\n private contractAddress: Address,\n ) {}\n\n async getVaultBasicInfo(vaultId: Hex): Promise<VaultBasicInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultBasicInfo\",\n args: [vaultId],\n })) as readonly [Address, Hex, bigint, Address, number, Address, bigint];\n\n return {\n depositor: result[0],\n depositorBtcPubKey: result[1],\n amount: result[2],\n vaultProvider: result[3],\n status: result[4],\n applicationEntryPoint: result[5],\n createdAt: result[6],\n };\n }\n\n async getVaultProtocolInfo(vaultId: Hex): Promise<VaultProtocolInfo> {\n const result = (await this.publicClient.readContract({\n address: this.contractAddress,\n abi: BTCVaultRegistryABI,\n functionName: \"getBtcVaultProtocolInfo\",\n args: [vaultId],\n })) as readonly [\n Hex,\n number,\n number,\n number,\n bigint,\n Hex,\n Hex,\n number,\n Hex,\n Hex,\n number,\n ];\n\n return {\n depositorSignedPeginTx: result[0],\n universalChallengersVersion: result[1],\n appVaultKeepersVersion: result[2],\n offchainParamsVersion: result[3],\n verifiedAt: result[4],\n depositorWotsPkHash: result[5],\n hashlock: result[6],\n htlcVout: result[7],\n depositorPopSignature: result[8],\n prePeginTxHash: result[9],\n vaultProviderCommissionBps: result[10],\n };\n }\n\n async getVaultData(vaultId: Hex): Promise<VaultData> {\n const [basic, protocol] = await Promise.all([\n this.getVaultBasicInfo(vaultId),\n this.getVaultProtocolInfo(vaultId),\n ]);\n\n if (\n !protocol.depositorSignedPeginTx ||\n protocol.depositorSignedPeginTx === \"0x\"\n ) {\n throw new Error(\n `Vault ${vaultId} not found on-chain or has no pegin transaction`,\n );\n }\n\n return { basic, protocol };\n }\n}\n"],"names":["MAX_SATOSHIS","MEMPOOL_REQUEST_TIMEOUT_MS","fetchWithTimeout","url","options","controller","timeoutId","signals","error","MAX_FEE_RATE","isValidSatoshiValue","value","isValidFeeRate","isValidVout","vout","outputCount","MEMPOOL_API_URLS","fetchApi","response","errorText","contentType","pushTx","txHex","apiUrl","message","getTxInfo","txid","getTxHex","getUtxoInfo","txInfo","output","getAddressUtxos","address","utxos","addressInfo","utxo","a","b","getMempoolApiUrl","network","getAddressTxs","getNetworkFees","data","feeFields","field","ApplicationRegistryABI","BTCVaultRegistryABI","ProtocolParamsABI","DAEMON_STATUS_VALUES","DaemonStatus","VP_ERROR_PREVIEW_MAX_LEN","preview","_a","VP_VALIDATION_USER_MESSAGE","VpResponseValidationError","detail","__publicField","HEX_RE","X_ONLY_PUBKEY_HEX_LEN","COMPRESSED_PUBKEY_HEX_LEN","TXID_HEX_LEN","isNonEmptyHex","isNonEmptyString","assertNonEmptyHex","assertNonEmptyString","assertBtcPubkey","validatePresigningProgressFields","progress","presigning","p","validateGetPeginStatusResponse","r","validateRequestDepositorPresignTransactionsResponse","i","validateClaimerTransactions","validateDepositorGraphTransactions","validateTransactionData","tx","validateChallengeAssertConnectorData","c","validatePresignDataPerChallenger","d","validateRequestDepositorClaimerArtifactsResponse","key","session","s","validateGetPegoutStatusResponse","claimer","challenger","graph","DEFAULT_TIMEOUT_MS","VaultProviderRpcClient","baseUrl","config","JsonRpcClient","params","signal","resolveProtocolAddresses","publicClient","btcVaultRegistryAddress","protocolParams","applicationRegistry","UINT16_MAX","mapOffchainParams","result","mapTBVParams","deriveTimelockPegin","timelockAssert","ViemProtocolParamsReader","contractAddress","version","results","tbvParams","offchainParams","mapKeyPairs","pair","ViemVaultKeeperReader","appEntryPoint","ViemUniversalChallengerReader","ViemVaultRegistryReader","vaultId","basic","protocol"],"mappings":"yNAYMA,EAAe,KAAa,IAG5BC,EAA6B,IAMnC,eAAeC,EACbC,EACAC,EACmB,CACnB,MAAMC,EAAa,IAAI,gBACjBC,EAAY,WAChB,IAAMD,EAAW,MAAA,EACjBJ,CAAA,EAIIM,EAAU,CAACF,EAAW,OAAQD,GAAA,YAAAA,EAAS,MAAM,EAAE,OACnD,OAAA,EAGF,GAAI,CAEF,OAAO,MAAM,MAAMD,EAAK,CACtB,GAAGC,EACH,OAAQ,YAAY,IAAIG,CAAO,CAAA,CAChC,CACH,OAASC,EAAO,CAEd,MADA,aAAaF,CAAS,EAEpBE,GAAS,MACT,OAAOA,GAAU,UACjB,SAAUA,GACVA,EAAM,OAAS,aAET,IAAI,MACR,uCAAuCP,CAA0B,OAAOE,CAAG,EAAA,EAGzEK,CACR,CACF,CAMA,MAAMC,EAAe,IA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,KAAK,kBAAkBF,CAAO,EAC9B,KAAK,qBAAqBA,CAAO,CAAA,CAClC,EAED,GACE,CAACE,EAAS,wBACVA,EAAS,yBAA2B,KAEpC,MAAM,IAAI,MACR,SAASF,CAAO,iDAAA,EAIpB,MAAO,CAAE,MAAAC,EAAO,SAAAC,CAAA,CAClB,CACF"}
|
package/dist/payout-Ce9vSs9e.js
DELETED
|
@@ -1,164 +0,0 @@
|
|
|
1
|
-
import { createPayoutConnector as E, tapInternalPubkey as B } from "@babylonlabs-io/babylon-tbv-rust-wasm";
|
|
2
|
-
import { Buffer as l } from "buffer";
|
|
3
|
-
import { Transaction as f, Psbt as $ } from "bitcoinjs-lib";
|
|
4
|
-
import { s as S, h as v, u as d, j as A } from "./constants-Q7v2O7Ps.js";
|
|
5
|
-
async function m(t) {
|
|
6
|
-
const r = await E(
|
|
7
|
-
{
|
|
8
|
-
depositor: t.depositor,
|
|
9
|
-
vaultProvider: t.vaultProvider,
|
|
10
|
-
vaultKeepers: t.vaultKeepers,
|
|
11
|
-
universalChallengers: t.universalChallengers,
|
|
12
|
-
timelockPegin: t.timelockPegin
|
|
13
|
-
},
|
|
14
|
-
t.network
|
|
15
|
-
);
|
|
16
|
-
return {
|
|
17
|
-
payoutScript: r.payoutScript,
|
|
18
|
-
taprootScriptHash: r.taprootScriptHash,
|
|
19
|
-
scriptPubKey: r.scriptPubKey,
|
|
20
|
-
address: r.address,
|
|
21
|
-
payoutControlBlock: r.payoutControlBlock
|
|
22
|
-
};
|
|
23
|
-
}
|
|
24
|
-
async function q(t) {
|
|
25
|
-
const r = S(t.payoutTxHex), e = S(t.peginTxHex), s = S(t.assertTxHex), o = await m({
|
|
26
|
-
depositor: t.depositorBtcPubkey,
|
|
27
|
-
vaultProvider: t.vaultProviderBtcPubkey,
|
|
28
|
-
vaultKeepers: t.vaultKeeperBtcPubkeys,
|
|
29
|
-
universalChallengers: t.universalChallengerBtcPubkeys,
|
|
30
|
-
timelockPegin: t.timelockPegin,
|
|
31
|
-
network: t.network
|
|
32
|
-
}), n = v(o.payoutScript), i = v(o.payoutControlBlock), c = f.fromHex(r), P = f.fromHex(e), w = f.fromHex(s), u = new $();
|
|
33
|
-
if (u.setVersion(c.version), u.setLocktime(c.locktime), c.ins.length !== 2)
|
|
34
|
-
throw new Error(
|
|
35
|
-
`Payout transaction must have exactly 2 inputs, got ${c.ins.length}`
|
|
36
|
-
);
|
|
37
|
-
const a = c.ins[0], p = c.ins[1], x = d(
|
|
38
|
-
new Uint8Array(a.hash).slice().reverse()
|
|
39
|
-
), k = P.getId();
|
|
40
|
-
if (x !== k)
|
|
41
|
-
throw new Error(
|
|
42
|
-
`Input 0 does not reference pegin transaction. Expected ${k}, got ${x}`
|
|
43
|
-
);
|
|
44
|
-
const h = d(
|
|
45
|
-
new Uint8Array(p.hash).slice().reverse()
|
|
46
|
-
), H = w.getId();
|
|
47
|
-
if (h !== H)
|
|
48
|
-
throw new Error(
|
|
49
|
-
`Input 1 does not reference assert transaction. Expected ${H}, got ${h}`
|
|
50
|
-
);
|
|
51
|
-
const y = P.outs[a.index];
|
|
52
|
-
if (!y)
|
|
53
|
-
throw new Error(
|
|
54
|
-
`Previous output not found for input 0 (txid: ${x}, index: ${a.index})`
|
|
55
|
-
);
|
|
56
|
-
const g = w.outs[p.index];
|
|
57
|
-
if (!g)
|
|
58
|
-
throw new Error(
|
|
59
|
-
`Previous output not found for input 1 (txid: ${h}, index: ${p.index})`
|
|
60
|
-
);
|
|
61
|
-
u.addInput({
|
|
62
|
-
hash: a.hash,
|
|
63
|
-
index: a.index,
|
|
64
|
-
sequence: a.sequence,
|
|
65
|
-
witnessUtxo: {
|
|
66
|
-
script: y.script,
|
|
67
|
-
value: y.value
|
|
68
|
-
},
|
|
69
|
-
tapLeafScript: [
|
|
70
|
-
{
|
|
71
|
-
leafVersion: A,
|
|
72
|
-
script: l.from(n),
|
|
73
|
-
controlBlock: l.from(i)
|
|
74
|
-
}
|
|
75
|
-
],
|
|
76
|
-
tapInternalKey: l.from(B)
|
|
77
|
-
// sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot
|
|
78
|
-
}), u.addInput({
|
|
79
|
-
hash: p.hash,
|
|
80
|
-
index: p.index,
|
|
81
|
-
sequence: p.sequence,
|
|
82
|
-
witnessUtxo: {
|
|
83
|
-
script: g.script,
|
|
84
|
-
value: g.value
|
|
85
|
-
}
|
|
86
|
-
// No tapLeafScript - depositor doesn't sign this input
|
|
87
|
-
});
|
|
88
|
-
for (const T of c.outs)
|
|
89
|
-
u.addOutput({
|
|
90
|
-
script: T.script,
|
|
91
|
-
value: T.value
|
|
92
|
-
});
|
|
93
|
-
return {
|
|
94
|
-
psbtHex: u.toHex()
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
function W(t, r, e = 0) {
|
|
98
|
-
const s = $.fromHex(t);
|
|
99
|
-
if (e >= s.data.inputs.length)
|
|
100
|
-
throw new Error(
|
|
101
|
-
`Input index ${e} out of range (${s.data.inputs.length} inputs)`
|
|
102
|
-
);
|
|
103
|
-
const o = s.data.inputs[e];
|
|
104
|
-
if (o.tapScriptSig && o.tapScriptSig.length > 0) {
|
|
105
|
-
const n = v(r);
|
|
106
|
-
for (const i of o.tapScriptSig)
|
|
107
|
-
if (i.pubkey.equals(l.from(n)))
|
|
108
|
-
return b(i.signature, e);
|
|
109
|
-
throw new Error(
|
|
110
|
-
`No signature found for depositor pubkey: ${r} at input ${e}`
|
|
111
|
-
);
|
|
112
|
-
}
|
|
113
|
-
if (o.finalScriptWitness && o.finalScriptWitness.length > 0) {
|
|
114
|
-
const n = C(o.finalScriptWitness);
|
|
115
|
-
if (n.length >= 1)
|
|
116
|
-
return b(n[0], e);
|
|
117
|
-
}
|
|
118
|
-
throw new Error(
|
|
119
|
-
`No tapScriptSig or finalScriptWitness found in signed PSBT at input ${e}`
|
|
120
|
-
);
|
|
121
|
-
}
|
|
122
|
-
function b(t, r) {
|
|
123
|
-
if (t.length === 64)
|
|
124
|
-
return d(new Uint8Array(t));
|
|
125
|
-
if (t.length === 65) {
|
|
126
|
-
const e = t[64];
|
|
127
|
-
if (e !== f.SIGHASH_ALL)
|
|
128
|
-
throw new Error(
|
|
129
|
-
`Unexpected sighash type 0x${e.toString(16).padStart(2, "0")} at input ${r}. Expected SIGHASH_ALL (0x01).`
|
|
130
|
-
);
|
|
131
|
-
return d(new Uint8Array(t.subarray(0, 64)));
|
|
132
|
-
}
|
|
133
|
-
throw new Error(
|
|
134
|
-
`Unexpected signature length at input ${r}: ${t.length}`
|
|
135
|
-
);
|
|
136
|
-
}
|
|
137
|
-
function C(t) {
|
|
138
|
-
const r = [];
|
|
139
|
-
let e = 0;
|
|
140
|
-
const s = () => {
|
|
141
|
-
const n = t[e++];
|
|
142
|
-
if (n < 253) return n;
|
|
143
|
-
if (n === 253) {
|
|
144
|
-
const i = t[e] | t[e + 1] << 8;
|
|
145
|
-
return e += 2, i;
|
|
146
|
-
}
|
|
147
|
-
if (n === 254) {
|
|
148
|
-
const i = t[e] | t[e + 1] << 8 | t[e + 2] << 16 | t[e + 3] << 24;
|
|
149
|
-
return e += 4, i;
|
|
150
|
-
}
|
|
151
|
-
return e += 8, 0;
|
|
152
|
-
}, o = s();
|
|
153
|
-
for (let n = 0; n < o; n++) {
|
|
154
|
-
const i = s();
|
|
155
|
-
r.push(t.subarray(e, e + i)), e += i;
|
|
156
|
-
}
|
|
157
|
-
return r;
|
|
158
|
-
}
|
|
159
|
-
export {
|
|
160
|
-
q as b,
|
|
161
|
-
m as c,
|
|
162
|
-
W as e
|
|
163
|
-
};
|
|
164
|
-
//# sourceMappingURL=payout-Ce9vSs9e.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"payout-Ce9vSs9e.js","sources":["../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/payout.ts"],"sourcesContent":["/**\n * Payout Script Generator Primitive\n *\n * This module provides pure functions for generating payout scripts and taproot information\n * by wrapping the WASM implementation from @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * The payout script is used for signing payout transactions in the vault system.\n * It defines the spending conditions for the vault output, enabling the depositor\n * to authorize payouts during the peg-in flow (Step 3).\n *\n * @remarks\n * This is a low-level primitive. For most use cases, prefer using {@link buildPayoutPsbt}\n * which handles script creation internally. For high-level wallet orchestration, use\n * PayoutManager from the managers module.\n *\n * @see {@link buildPayoutPsbt} - Higher-level function that uses this internally\n *\n * @module primitives/scripts/payout\n */\n\nimport {\n createPayoutConnector,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\n/**\n * Parameters for creating a payout script.\n *\n * These parameters define the participants in a vault and are used to generate\n * the taproot script that controls how funds can be spent from the vault.\n */\nexport interface PayoutScriptParams {\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * This is the user depositing BTC into the vault. The depositor must sign\n * payout transactions to authorize fund distribution.\n */\n depositor: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * The service provider managing vault operations. Also referred to as\n * \"claimer\" in the WASM layer.\n */\n vaultProvider: string;\n\n /**\n * Array of vault keeper BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * Vault keepers participate in vault operations and script spending conditions.\n */\n vaultKeepers: string[];\n\n /**\n * Array of universal challenger BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * These parties can challenge the vault under certain conditions.\n */\n universalChallengers: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network for script generation.\n *\n * Must match the network used for all other vault operations to ensure\n * address encoding compatibility.\n */\n network: Network;\n}\n\n/**\n * Result of creating a payout script.\n *\n * Contains all the taproot-related data needed for constructing and signing\n * payout transactions from the vault.\n */\nexport interface PayoutScriptResult {\n /**\n * The payout script hex used in taproot script path spending.\n *\n * This is the raw script bytes that define the spending conditions,\n * encoded as a hexadecimal string. Used when constructing the\n * tapLeafScript for PSBT signing.\n */\n payoutScript: string;\n\n /**\n * The taproot script hash (leaf hash) for the payout script.\n *\n * This is the tagged hash of the script used in taproot tree construction.\n * Required for computing the control block during script path spending.\n */\n taprootScriptHash: string;\n\n /**\n * The full scriptPubKey for the vault output address.\n *\n * This is the complete output script (OP_1 <32-byte-key>) that should be\n * used when creating the vault output in a peg-in transaction.\n */\n scriptPubKey: string;\n\n /**\n * The vault Bitcoin address derived from the script.\n *\n * A human-readable bech32m address (bc1p... for mainnet, tb1p... for testnet/signet)\n * that can be used to receive funds into the vault.\n */\n address: string;\n\n /**\n * Serialized control block for Taproot script path spend (hex encoded).\n *\n * Computed by the Rust WASM PeginPayoutConnector. Used directly in\n * tapLeafScript when building payout PSBTs.\n */\n payoutControlBlock: string;\n}\n\n/**\n * Create payout script and taproot information using WASM.\n *\n * This is a pure function that wraps the Rust WASM implementation.\n * The payout connector generates the necessary taproot scripts and information\n * required for signing payout transactions.\n *\n * @remarks\n * The generated script encodes spending conditions that require signatures from\n * the depositor and vault provider (or liquidators in challenge scenarios).\n * This script is used internally by {@link buildPayoutPsbt}.\n *\n * @param params - Payout script parameters defining vault participants and network\n * @returns Payout script and taproot information for PSBT construction\n *\n * @see {@link buildPayoutPsbt} - Use this for building complete payout PSBTs\n */\nexport async function createPayoutScript(\n params: PayoutScriptParams,\n): Promise<PayoutScriptResult> {\n // Call the WASM wrapper with the correct parameter structure\n const connector = await createPayoutConnector(\n {\n depositor: params.depositor,\n vaultProvider: params.vaultProvider,\n vaultKeepers: params.vaultKeepers,\n universalChallengers: params.universalChallengers,\n timelockPegin: params.timelockPegin,\n },\n params.network,\n );\n\n return {\n payoutScript: connector.payoutScript,\n taprootScriptHash: connector.taprootScriptHash,\n scriptPubKey: connector.scriptPubKey,\n address: connector.address,\n payoutControlBlock: connector.payoutControlBlock,\n };\n}\n","/**\n * Payout PSBT Builder Primitives\n *\n * This module provides pure functions for building unsigned payout PSBTs and extracting\n * Schnorr signatures from signed PSBTs. It uses WASM-generated scripts from the payout\n * connector and bitcoinjs-lib for PSBT construction.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @module primitives/psbt/payout\n */\n\nimport {\n type Network,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building an unsigned Payout PSBT\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface PayoutParams {\n /**\n * Payout transaction hex (unsigned)\n * This is the transaction that needs to be signed by the depositor\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex\n * Payout input 1 references Assert output 0\n */\n assertTxHex: string;\n\n /**\n * Peg-in transaction hex\n * This transaction created the vault output that we're spending\n */\n peginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix)\n */\n depositorBtcPubkey: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex)\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex)\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex)\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network\n */\n network: Network;\n}\n\n/**\n * Result of building an unsigned payout PSBT\n */\nexport interface PayoutPsbtResult {\n /**\n * Unsigned PSBT hex ready for signing\n */\n psbtHex: string;\n}\n\n/**\n * Build unsigned Payout PSBT for depositor to sign.\n *\n * Payout is used in the **challenge path** when the claimer proves validity:\n * 1. Vault provider submits Claim transaction\n * 2. Challenge is raised during challenge period\n * 3. Claimer submits Assert transaction to prove validity\n * 4. Payout can be executed (references Assert tx)\n *\n * Payout transactions have the following structure:\n * - Input 0: from PeginTx output0 (signed by depositor)\n * - Input 1: from Assert output0 (NOT signed by depositor)\n *\n * @param params - Payout parameters\n * @returns Unsigned PSBT ready for depositor to sign\n *\n * @throws If payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference the pegin transaction\n * @throws If input 1 does not reference the assert transaction\n * @throws If previous output is not found for either input\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n // Normalize hex inputs (strip 0x prefix if present)\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const assertTxHex = stripHexPrefix(params.assertTxHex);\n\n // Get payout script from WASM\n const payoutConnector = await createPayoutScript({\n depositor: params.depositorBtcPubkey,\n vaultProvider: params.vaultProviderBtcPubkey,\n vaultKeepers: params.vaultKeeperBtcPubkeys,\n universalChallengers: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: params.network,\n });\n\n const payoutScriptBytes = hexToUint8Array(payoutConnector.payoutScript);\n const controlBlock = hexToUint8Array(payoutConnector.payoutControlBlock);\n\n // Parse transactions\n const payoutTx = Transaction.fromHex(payoutTxHex);\n const peginTx = Transaction.fromHex(peginTxHex);\n const assertTx = Transaction.fromHex(assertTxHex);\n\n // Create PSBT\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // PayoutTx has exactly 2 inputs:\n // - Input 0: from PeginTx output0 (signed by depositor using taproot script path)\n // - Input 1: from Assert output0 (signed by claimer/challengers, not depositor)\n //\n // IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL inputs'\n // prevouts, not just the one being signed. Therefore, we must include BOTH inputs\n // in the PSBT so the wallet computes the correct sighash that the VP expects.\n\n // Verify payout transaction has expected structure\n if (payoutTx.ins.length !== 2) {\n throw new Error(\n `Payout transaction must have exactly 2 inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n // Verify input 0 references the pegin transaction\n const input0Txid = uint8ArrayToHex(\n new Uint8Array(input0.hash).slice().reverse(),\n );\n const peginTxid = peginTx.getId();\n\n if (input0Txid !== peginTxid) {\n throw new Error(\n `Input 0 does not reference pegin transaction. ` +\n `Expected ${peginTxid}, got ${input0Txid}`,\n );\n }\n\n // Verify input 1 references the assert transaction\n const input1Txid = uint8ArrayToHex(\n new Uint8Array(input1.hash).slice().reverse(),\n );\n const expectedInput1Txid = assertTx.getId();\n\n if (input1Txid !== expectedInput1Txid) {\n throw new Error(\n `Input 1 does not reference assert transaction. ` +\n `Expected ${expectedInput1Txid}, got ${input1Txid}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n if (!peginPrevOut) {\n throw new Error(\n `Previous output not found for input 0 (txid: ${input0Txid}, index: ${input0.index})`,\n );\n }\n\n const input1PrevOut = assertTx.outs[input1.index];\n if (!input1PrevOut) {\n throw new Error(\n `Previous output not found for input 1 (txid: ${input1Txid}, index: ${input1.index})`,\n );\n }\n\n // Input 0: Depositor signs using Taproot script path spend\n // This input includes tapLeafScript for signing\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(payoutScriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: From Assert transaction (NOT signed by depositor)\n // We include this with witnessUtxo so the sighash is computed correctly,\n // but we do NOT include tapLeafScript since the depositor doesn't sign it.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: input1PrevOut.script,\n value: input1PrevOut.value,\n },\n // No tapLeafScript - depositor doesn't sign this input\n });\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return {\n psbtHex: psbt.toHex(),\n };\n}\n\n/**\n * Extract Schnorr signature from signed payout PSBT.\n *\n * This function supports two cases:\n * 1. Non-finalized PSBT: Extracts from tapScriptSig field\n * 2. Finalized PSBT: Extracts from witness data\n *\n * The signature is returned as a 64-byte hex string (128 hex characters)\n * with any sighash flag byte removed if present.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's public key (x-only, 64-char hex)\n * @param inputIndex - Input index to extract signature from (default: 0)\n * @returns 64-byte Schnorr signature (128 hex characters, no sighash flag)\n *\n * @throws If no signature is found in the PSBT\n * @throws If the signature has an unexpected length\n */\nexport function extractPayoutSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n inputIndex = 0,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n if (inputIndex >= signedPsbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${signedPsbt.data.inputs.length} inputs)`,\n );\n }\n\n const input = signedPsbt.data.inputs[inputIndex];\n\n // Case 1: Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = hexToUint8Array(depositorPubkey);\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(Buffer.from(depositorPubkeyBytes))) {\n return extractSchnorrSig(sigEntry.signature, inputIndex);\n }\n }\n\n throw new Error(\n `No signature found for depositor pubkey: ${depositorPubkey} at input ${inputIndex}`,\n );\n }\n\n // Case 2: Finalized PSBT — extract from finalScriptWitness\n // Taproot script-path witness: [signature, script, controlBlock]\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n const witnessStack = parseWitnessStack(input.finalScriptWitness);\n if (witnessStack.length >= 1) {\n return extractSchnorrSig(witnessStack[0], inputIndex);\n }\n }\n\n throw new Error(\n `No tapScriptSig or finalScriptWitness found in signed PSBT at input ${inputIndex}`,\n );\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Rejects signatures with sighash types other than SIGHASH_ALL (0x01) to prevent\n * acceptance of signatures that don't commit to all outputs (e.g. SIGHASH_NONE).\n * @internal\n */\nfunction extractSchnorrSig(sig: Uint8Array, inputIndex: number): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n } else if (sig.length === 65) {\n const sighashByte = sig[64];\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} at input ${inputIndex}. Expected SIGHASH_ALL (0x01).`,\n );\n }\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(\n `Unexpected signature length at input ${inputIndex}: ${sig.length}`,\n );\n}\n\n/**\n * Parse a BIP-141 serialized witness stack into individual stack items.\n * Format: [varint item_count] [varint len, data]...\n * @internal\n */\nfunction parseWitnessStack(witness: Buffer): Buffer[] {\n const items: Buffer[] = [];\n let offset = 0;\n\n const readVarInt = (): number => {\n const first = witness[offset++];\n if (first < 0xfd) return first;\n if (first === 0xfd) {\n const val = witness[offset] | (witness[offset + 1] << 8);\n offset += 2;\n return val;\n }\n if (first === 0xfe) {\n const val =\n witness[offset] |\n (witness[offset + 1] << 8) |\n (witness[offset + 2] << 16) |\n (witness[offset + 3] << 24);\n offset += 4;\n return val;\n }\n // 0xff — 8-byte, won't happen for witness data\n offset += 8;\n return 0;\n };\n\n const count = readVarInt();\n for (let i = 0; i < count; i++) {\n const len = readVarInt();\n items.push(witness.subarray(offset, offset + len) as Buffer);\n offset += len;\n }\n\n return items;\n}\n\n"],"names":["createPayoutScript","params","connector","createPayoutConnector","buildPayoutPsbt","payoutTxHex","stripHexPrefix","peginTxHex","assertTxHex","payoutConnector","payoutScriptBytes","hexToUint8Array","controlBlock","payoutTx","Transaction","peginTx","assertTx","psbt","Psbt","input0","input1","input0Txid","uint8ArrayToHex","peginTxid","input1Txid","expectedInput1Txid","peginPrevOut","input1PrevOut","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPayoutSignature","signedPsbtHex","depositorPubkey","inputIndex","signedPsbt","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","witnessStack","parseWitnessStack","sig","sighashByte","witness","items","offset","readVarInt","first","val","count","i","len"],"mappings":";;;;AA8IA,eAAsBA,EACpBC,GAC6B;AAE7B,QAAMC,IAAY,MAAMC;AAAA,IACtB;AAAA,MACE,WAAWF,EAAO;AAAA,MAClB,eAAeA,EAAO;AAAA,MACtB,cAAcA,EAAO;AAAA,MACrB,sBAAsBA,EAAO;AAAA,MAC7B,eAAeA,EAAO;AAAA,IAAA;AAAA,IAExBA,EAAO;AAAA,EAAA;AAGT,SAAO;AAAA,IACL,cAAcC,EAAU;AAAA,IACxB,mBAAmBA,EAAU;AAAA,IAC7B,cAAcA,EAAU;AAAA,IACxB,SAASA,EAAU;AAAA,IACnB,oBAAoBA,EAAU;AAAA,EAAA;AAElC;ACnDA,eAAsBE,EACpBH,GAC2B;AAE3B,QAAMI,IAAcC,EAAeL,EAAO,WAAW,GAC/CM,IAAaD,EAAeL,EAAO,UAAU,GAC7CO,IAAcF,EAAeL,EAAO,WAAW,GAG/CQ,IAAkB,MAAMT,EAAmB;AAAA,IAC/C,WAAWC,EAAO;AAAA,IAClB,eAAeA,EAAO;AAAA,IACtB,cAAcA,EAAO;AAAA,IACrB,sBAAsBA,EAAO;AAAA,IAC7B,eAAeA,EAAO;AAAA,IACtB,SAASA,EAAO;AAAA,EAAA,CACjB,GAEKS,IAAoBC,EAAgBF,EAAgB,YAAY,GAChEG,IAAeD,EAAgBF,EAAgB,kBAAkB,GAGjEI,IAAWC,EAAY,QAAQT,CAAW,GAC1CU,IAAUD,EAAY,QAAQP,CAAU,GACxCS,IAAWF,EAAY,QAAQN,CAAW,GAG1CS,IAAO,I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G,CAAW,GAC3DN,KAAUM;AAAA,EACZ;AAEA,SAAOP;AACT;"}
|
package/dist/payout-CfsDnjKI.cjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
"use strict";const H=require("@babylonlabs-io/babylon-tbv-rust-wasm"),x=require("buffer"),f=require("bitcoinjs-lib"),s=require("./constants-EiyZkXce.cjs");async function k(t){const r=await H.createPayoutConnector({depositor:t.depositor,vaultProvider:t.vaultProvider,vaultKeepers:t.vaultKeepers,universalChallengers:t.universalChallengers,timelockPegin:t.timelockPegin},t.network);return{payoutScript:r.payoutScript,taprootScriptHash:r.taprootScriptHash,scriptPubKey:r.scriptPubKey,address:r.address,payoutControlBlock:r.payoutControlBlock}}async function $(t){const r=s.stripHexPrefix(t.payoutTxHex),e=s.stripHexPrefix(t.peginTxHex),u=s.stripHexPrefix(t.assertTxHex),o=await k({depositor:t.depositorBtcPubkey,vaultProvider:t.vaultProviderBtcPubkey,vaultKeepers:t.vaultKeeperBtcPubkeys,universalChallengers:t.universalChallengerBtcPubkeys,timelockPegin:t.timelockPegin,network:t.network}),n=s.hexToUint8Array(o.payoutScript),i=s.hexToUint8Array(o.payoutControlBlock),c=f.Transaction.fromHex(r),P=f.Transaction.fromHex(e),S=f.Transaction.fromHex(u),a=new f.Psbt;if(a.setVersion(c.version),a.setLocktime(c.locktime),c.ins.length!==2)throw new Error(`Payout transaction must have exactly 2 inputs, got ${c.ins.length}`);const p=c.ins[0],l=c.ins[1],d=s.uint8ArrayToHex(new Uint8Array(p.hash).slice().reverse()),v=P.getId();if(d!==v)throw new Error(`Input 0 does not reference pegin transaction. Expected ${v}, got ${d}`);const y=s.uint8ArrayToHex(new Uint8Array(l.hash).slice().reverse()),T=S.getId();if(y!==T)throw new Error(`Input 1 does not reference assert transaction. Expected ${T}, got ${y}`);const h=P.outs[p.index];if(!h)throw new Error(`Previous output not found for input 0 (txid: ${d}, index: ${p.index})`);const g=S.outs[l.index];if(!g)throw new Error(`Previous output not found for input 1 (txid: ${y}, index: ${l.index})`);a.addInput({hash:p.hash,index:p.index,sequence:p.sequence,witnessUtxo:{script:h.script,value:h.value},tapLeafScript:[{leafVersion:s.TAPSCRIPT_LEAF_VERSION,script:x.Buffer.from(n),controlBlock:x.Buffer.from(i)}],tapInternalKey:x.Buffer.from(H.tapInternalPubkey)}),a.addInput({hash:l.hash,index:l.index,sequence:l.sequence,witnessUtxo:{script:g.script,value:g.value}});for(const w of c.outs)a.addOutput({script:w.script,value:w.value});return{psbtHex:a.toHex()}}function A(t,r,e=0){const u=f.Psbt.fromHex(t);if(e>=u.data.inputs.length)throw new Error(`Input index ${e} out of range (${u.data.inputs.length} inputs)`);const o=u.data.inputs[e];if(o.tapScriptSig&&o.tapScriptSig.length>0){const n=s.hexToUint8Array(r);for(const i of o.tapScriptSig)if(i.pubkey.equals(x.Buffer.from(n)))return b(i.signature,e);throw new Error(`No signature found for depositor pubkey: ${r} at input ${e}`)}if(o.finalScriptWitness&&o.finalScriptWitness.length>0){const n=B(o.finalScriptWitness);if(n.length>=1)return b(n[0],e)}throw new Error(`No tapScriptSig or finalScriptWitness found in signed PSBT at input ${e}`)}function b(t,r){if(t.length===64)return s.uint8ArrayToHex(new Uint8Array(t));if(t.length===65){const e=t[64];if(e!==f.Transaction.SIGHASH_ALL)throw new Error(`Unexpected sighash type 0x${e.toString(16).padStart(2,"0")} at input ${r}. Expected SIGHASH_ALL (0x01).`);return s.uint8ArrayToHex(new Uint8Array(t.subarray(0,64)))}throw new Error(`Unexpected signature length at input ${r}: ${t.length}`)}function B(t){const r=[];let e=0;const u=()=>{const n=t[e++];if(n<253)return n;if(n===253){const i=t[e]|t[e+1]<<8;return e+=2,i}if(n===254){const i=t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24;return e+=4,i}return e+=8,0},o=u();for(let n=0;n<o;n++){const i=u();r.push(t.subarray(e,e+i)),e+=i}return r}exports.buildPayoutPsbt=$;exports.createPayoutScript=k;exports.extractPayoutSignature=A;
|
|
2
|
-
//# sourceMappingURL=payout-CfsDnjKI.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"payout-CfsDnjKI.cjs","sources":["../src/tbv/core/primitives/scripts/payout.ts","../src/tbv/core/primitives/psbt/payout.ts"],"sourcesContent":["/**\n * Payout Script Generator Primitive\n *\n * This module provides pure functions for generating payout scripts and taproot information\n * by wrapping the WASM implementation from @babylonlabs-io/babylon-tbv-rust-wasm.\n *\n * The payout script is used for signing payout transactions in the vault system.\n * It defines the spending conditions for the vault output, enabling the depositor\n * to authorize payouts during the peg-in flow (Step 3).\n *\n * @remarks\n * This is a low-level primitive. For most use cases, prefer using {@link buildPayoutPsbt}\n * which handles script creation internally. For high-level wallet orchestration, use\n * PayoutManager from the managers module.\n *\n * @see {@link buildPayoutPsbt} - Higher-level function that uses this internally\n *\n * @module primitives/scripts/payout\n */\n\nimport {\n createPayoutConnector,\n type Network,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\n\n/**\n * Parameters for creating a payout script.\n *\n * These parameters define the participants in a vault and are used to generate\n * the taproot script that controls how funds can be spent from the vault.\n */\nexport interface PayoutScriptParams {\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * This is the user depositing BTC into the vault. The depositor must sign\n * payout transactions to authorize fund distribution.\n */\n depositor: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex without 0x prefix).\n *\n * The service provider managing vault operations. Also referred to as\n * \"claimer\" in the WASM layer.\n */\n vaultProvider: string;\n\n /**\n * Array of vault keeper BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * Vault keepers participate in vault operations and script spending conditions.\n */\n vaultKeepers: string[];\n\n /**\n * Array of universal challenger BTC public keys (x-only, 64-char hex without 0x prefix).\n *\n * These parties can challenge the vault under certain conditions.\n */\n universalChallengers: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network for script generation.\n *\n * Must match the network used for all other vault operations to ensure\n * address encoding compatibility.\n */\n network: Network;\n}\n\n/**\n * Result of creating a payout script.\n *\n * Contains all the taproot-related data needed for constructing and signing\n * payout transactions from the vault.\n */\nexport interface PayoutScriptResult {\n /**\n * The payout script hex used in taproot script path spending.\n *\n * This is the raw script bytes that define the spending conditions,\n * encoded as a hexadecimal string. Used when constructing the\n * tapLeafScript for PSBT signing.\n */\n payoutScript: string;\n\n /**\n * The taproot script hash (leaf hash) for the payout script.\n *\n * This is the tagged hash of the script used in taproot tree construction.\n * Required for computing the control block during script path spending.\n */\n taprootScriptHash: string;\n\n /**\n * The full scriptPubKey for the vault output address.\n *\n * This is the complete output script (OP_1 <32-byte-key>) that should be\n * used when creating the vault output in a peg-in transaction.\n */\n scriptPubKey: string;\n\n /**\n * The vault Bitcoin address derived from the script.\n *\n * A human-readable bech32m address (bc1p... for mainnet, tb1p... for testnet/signet)\n * that can be used to receive funds into the vault.\n */\n address: string;\n\n /**\n * Serialized control block for Taproot script path spend (hex encoded).\n *\n * Computed by the Rust WASM PeginPayoutConnector. Used directly in\n * tapLeafScript when building payout PSBTs.\n */\n payoutControlBlock: string;\n}\n\n/**\n * Create payout script and taproot information using WASM.\n *\n * This is a pure function that wraps the Rust WASM implementation.\n * The payout connector generates the necessary taproot scripts and information\n * required for signing payout transactions.\n *\n * @remarks\n * The generated script encodes spending conditions that require signatures from\n * the depositor and vault provider (or liquidators in challenge scenarios).\n * This script is used internally by {@link buildPayoutPsbt}.\n *\n * @param params - Payout script parameters defining vault participants and network\n * @returns Payout script and taproot information for PSBT construction\n *\n * @see {@link buildPayoutPsbt} - Use this for building complete payout PSBTs\n */\nexport async function createPayoutScript(\n params: PayoutScriptParams,\n): Promise<PayoutScriptResult> {\n // Call the WASM wrapper with the correct parameter structure\n const connector = await createPayoutConnector(\n {\n depositor: params.depositor,\n vaultProvider: params.vaultProvider,\n vaultKeepers: params.vaultKeepers,\n universalChallengers: params.universalChallengers,\n timelockPegin: params.timelockPegin,\n },\n params.network,\n );\n\n return {\n payoutScript: connector.payoutScript,\n taprootScriptHash: connector.taprootScriptHash,\n scriptPubKey: connector.scriptPubKey,\n address: connector.address,\n payoutControlBlock: connector.payoutControlBlock,\n };\n}\n","/**\n * Payout PSBT Builder Primitives\n *\n * This module provides pure functions for building unsigned payout PSBTs and extracting\n * Schnorr signatures from signed PSBTs. It uses WASM-generated scripts from the payout\n * connector and bitcoinjs-lib for PSBT construction.\n *\n * The Payout transaction references the Assert transaction (input 1).\n *\n * @module primitives/psbt/payout\n */\n\nimport {\n type Network,\n tapInternalPubkey,\n} from \"@babylonlabs-io/babylon-tbv-rust-wasm\";\nimport { Buffer } from \"buffer\";\nimport { Psbt, Transaction } from \"bitcoinjs-lib\";\nimport { createPayoutScript } from \"../scripts/payout\";\nimport {\n TAPSCRIPT_LEAF_VERSION,\n hexToUint8Array,\n stripHexPrefix,\n uint8ArrayToHex,\n} from \"../utils/bitcoin\";\n\n/**\n * Parameters for building an unsigned Payout PSBT\n *\n * Payout is used in the challenge path after Assert, when the claimer proves validity.\n * Input 1 references the Assert transaction.\n */\nexport interface PayoutParams {\n /**\n * Payout transaction hex (unsigned)\n * This is the transaction that needs to be signed by the depositor\n */\n payoutTxHex: string;\n\n /**\n * Assert transaction hex\n * Payout input 1 references Assert output 0\n */\n assertTxHex: string;\n\n /**\n * Peg-in transaction hex\n * This transaction created the vault output that we're spending\n */\n peginTxHex: string;\n\n /**\n * Depositor's BTC public key (x-only, 64-char hex without 0x prefix)\n */\n depositorBtcPubkey: string;\n\n /**\n * Vault provider's BTC public key (x-only, 64-char hex)\n */\n vaultProviderBtcPubkey: string;\n\n /**\n * Vault keeper BTC public keys (x-only, 64-char hex)\n */\n vaultKeeperBtcPubkeys: string[];\n\n /**\n * Universal challenger BTC public keys (x-only, 64-char hex)\n */\n universalChallengerBtcPubkeys: string[];\n\n /**\n * CSV timelock in blocks for the PegIn output.\n */\n timelockPegin: number;\n\n /**\n * Bitcoin network\n */\n network: Network;\n}\n\n/**\n * Result of building an unsigned payout PSBT\n */\nexport interface PayoutPsbtResult {\n /**\n * Unsigned PSBT hex ready for signing\n */\n psbtHex: string;\n}\n\n/**\n * Build unsigned Payout PSBT for depositor to sign.\n *\n * Payout is used in the **challenge path** when the claimer proves validity:\n * 1. Vault provider submits Claim transaction\n * 2. Challenge is raised during challenge period\n * 3. Claimer submits Assert transaction to prove validity\n * 4. Payout can be executed (references Assert tx)\n *\n * Payout transactions have the following structure:\n * - Input 0: from PeginTx output0 (signed by depositor)\n * - Input 1: from Assert output0 (NOT signed by depositor)\n *\n * @param params - Payout parameters\n * @returns Unsigned PSBT ready for depositor to sign\n *\n * @throws If payout transaction does not have exactly 2 inputs\n * @throws If input 0 does not reference the pegin transaction\n * @throws If input 1 does not reference the assert transaction\n * @throws If previous output is not found for either input\n */\nexport async function buildPayoutPsbt(\n params: PayoutParams,\n): Promise<PayoutPsbtResult> {\n // Normalize hex inputs (strip 0x prefix if present)\n const payoutTxHex = stripHexPrefix(params.payoutTxHex);\n const peginTxHex = stripHexPrefix(params.peginTxHex);\n const assertTxHex = stripHexPrefix(params.assertTxHex);\n\n // Get payout script from WASM\n const payoutConnector = await createPayoutScript({\n depositor: params.depositorBtcPubkey,\n vaultProvider: params.vaultProviderBtcPubkey,\n vaultKeepers: params.vaultKeeperBtcPubkeys,\n universalChallengers: params.universalChallengerBtcPubkeys,\n timelockPegin: params.timelockPegin,\n network: params.network,\n });\n\n const payoutScriptBytes = hexToUint8Array(payoutConnector.payoutScript);\n const controlBlock = hexToUint8Array(payoutConnector.payoutControlBlock);\n\n // Parse transactions\n const payoutTx = Transaction.fromHex(payoutTxHex);\n const peginTx = Transaction.fromHex(peginTxHex);\n const assertTx = Transaction.fromHex(assertTxHex);\n\n // Create PSBT\n const psbt = new Psbt();\n psbt.setVersion(payoutTx.version);\n psbt.setLocktime(payoutTx.locktime);\n\n // PayoutTx has exactly 2 inputs:\n // - Input 0: from PeginTx output0 (signed by depositor using taproot script path)\n // - Input 1: from Assert output0 (signed by claimer/challengers, not depositor)\n //\n // IMPORTANT: For Taproot SIGHASH_DEFAULT (0x00), the sighash commits to ALL inputs'\n // prevouts, not just the one being signed. Therefore, we must include BOTH inputs\n // in the PSBT so the wallet computes the correct sighash that the VP expects.\n\n // Verify payout transaction has expected structure\n if (payoutTx.ins.length !== 2) {\n throw new Error(\n `Payout transaction must have exactly 2 inputs, got ${payoutTx.ins.length}`,\n );\n }\n\n const input0 = payoutTx.ins[0];\n const input1 = payoutTx.ins[1];\n\n // Verify input 0 references the pegin transaction\n const input0Txid = uint8ArrayToHex(\n new Uint8Array(input0.hash).slice().reverse(),\n );\n const peginTxid = peginTx.getId();\n\n if (input0Txid !== peginTxid) {\n throw new Error(\n `Input 0 does not reference pegin transaction. ` +\n `Expected ${peginTxid}, got ${input0Txid}`,\n );\n }\n\n // Verify input 1 references the assert transaction\n const input1Txid = uint8ArrayToHex(\n new Uint8Array(input1.hash).slice().reverse(),\n );\n const expectedInput1Txid = assertTx.getId();\n\n if (input1Txid !== expectedInput1Txid) {\n throw new Error(\n `Input 1 does not reference assert transaction. ` +\n `Expected ${expectedInput1Txid}, got ${input1Txid}`,\n );\n }\n\n const peginPrevOut = peginTx.outs[input0.index];\n if (!peginPrevOut) {\n throw new Error(\n `Previous output not found for input 0 (txid: ${input0Txid}, index: ${input0.index})`,\n );\n }\n\n const input1PrevOut = assertTx.outs[input1.index];\n if (!input1PrevOut) {\n throw new Error(\n `Previous output not found for input 1 (txid: ${input1Txid}, index: ${input1.index})`,\n );\n }\n\n // Input 0: Depositor signs using Taproot script path spend\n // This input includes tapLeafScript for signing\n psbt.addInput({\n hash: input0.hash,\n index: input0.index,\n sequence: input0.sequence,\n witnessUtxo: {\n script: peginPrevOut.script,\n value: peginPrevOut.value,\n },\n tapLeafScript: [\n {\n leafVersion: TAPSCRIPT_LEAF_VERSION,\n script: Buffer.from(payoutScriptBytes),\n controlBlock: Buffer.from(controlBlock),\n },\n ],\n tapInternalKey: Buffer.from(tapInternalPubkey),\n // sighashType omitted - defaults to SIGHASH_DEFAULT (0x00) for Taproot\n });\n\n // Input 1: From Assert transaction (NOT signed by depositor)\n // We include this with witnessUtxo so the sighash is computed correctly,\n // but we do NOT include tapLeafScript since the depositor doesn't sign it.\n psbt.addInput({\n hash: input1.hash,\n index: input1.index,\n sequence: input1.sequence,\n witnessUtxo: {\n script: input1PrevOut.script,\n value: input1PrevOut.value,\n },\n // No tapLeafScript - depositor doesn't sign this input\n });\n\n // Add outputs\n for (const output of payoutTx.outs) {\n psbt.addOutput({\n script: output.script,\n value: output.value,\n });\n }\n\n return {\n psbtHex: psbt.toHex(),\n };\n}\n\n/**\n * Extract Schnorr signature from signed payout PSBT.\n *\n * This function supports two cases:\n * 1. Non-finalized PSBT: Extracts from tapScriptSig field\n * 2. Finalized PSBT: Extracts from witness data\n *\n * The signature is returned as a 64-byte hex string (128 hex characters)\n * with any sighash flag byte removed if present.\n *\n * @param signedPsbtHex - Signed PSBT hex\n * @param depositorPubkey - Depositor's public key (x-only, 64-char hex)\n * @param inputIndex - Input index to extract signature from (default: 0)\n * @returns 64-byte Schnorr signature (128 hex characters, no sighash flag)\n *\n * @throws If no signature is found in the PSBT\n * @throws If the signature has an unexpected length\n */\nexport function extractPayoutSignature(\n signedPsbtHex: string,\n depositorPubkey: string,\n inputIndex = 0,\n): string {\n const signedPsbt = Psbt.fromHex(signedPsbtHex);\n\n if (inputIndex >= signedPsbt.data.inputs.length) {\n throw new Error(\n `Input index ${inputIndex} out of range (${signedPsbt.data.inputs.length} inputs)`,\n );\n }\n\n const input = signedPsbt.data.inputs[inputIndex];\n\n // Case 1: Non-finalized PSBT — extract from tapScriptSig\n if (input.tapScriptSig && input.tapScriptSig.length > 0) {\n const depositorPubkeyBytes = hexToUint8Array(depositorPubkey);\n\n for (const sigEntry of input.tapScriptSig) {\n if (sigEntry.pubkey.equals(Buffer.from(depositorPubkeyBytes))) {\n return extractSchnorrSig(sigEntry.signature, inputIndex);\n }\n }\n\n throw new Error(\n `No signature found for depositor pubkey: ${depositorPubkey} at input ${inputIndex}`,\n );\n }\n\n // Case 2: Finalized PSBT — extract from finalScriptWitness\n // Taproot script-path witness: [signature, script, controlBlock]\n if (input.finalScriptWitness && input.finalScriptWitness.length > 0) {\n const witnessStack = parseWitnessStack(input.finalScriptWitness);\n if (witnessStack.length >= 1) {\n return extractSchnorrSig(witnessStack[0], inputIndex);\n }\n }\n\n throw new Error(\n `No tapScriptSig or finalScriptWitness found in signed PSBT at input ${inputIndex}`,\n );\n}\n\n/**\n * Extract and validate a 64-byte Schnorr signature, stripping sighash flag if present.\n * Rejects signatures with sighash types other than SIGHASH_ALL (0x01) to prevent\n * acceptance of signatures that don't commit to all outputs (e.g. SIGHASH_NONE).\n * @internal\n */\nfunction extractSchnorrSig(sig: Uint8Array, inputIndex: number): string {\n if (sig.length === 64) {\n return uint8ArrayToHex(new Uint8Array(sig));\n } else if (sig.length === 65) {\n const sighashByte = sig[64];\n if (sighashByte !== Transaction.SIGHASH_ALL) {\n throw new Error(\n `Unexpected sighash type 0x${sighashByte.toString(16).padStart(2, \"0\")} at input ${inputIndex}. Expected SIGHASH_ALL (0x01).`,\n );\n }\n return uint8ArrayToHex(new Uint8Array(sig.subarray(0, 64)));\n }\n throw new Error(\n `Unexpected signature length at input ${inputIndex}: ${sig.length}`,\n );\n}\n\n/**\n * Parse a BIP-141 serialized witness stack into individual stack items.\n * Format: [varint item_count] [varint len, data]...\n * @internal\n */\nfunction parseWitnessStack(witness: Buffer): Buffer[] {\n const items: Buffer[] = [];\n let offset = 0;\n\n const readVarInt = (): number => {\n const first = witness[offset++];\n if (first < 0xfd) return first;\n if (first === 0xfd) {\n const val = witness[offset] | (witness[offset + 1] << 8);\n offset += 2;\n return val;\n }\n if (first === 0xfe) {\n const val =\n witness[offset] |\n (witness[offset + 1] << 8) |\n (witness[offset + 2] << 16) |\n (witness[offset + 3] << 24);\n offset += 4;\n return val;\n }\n // 0xff — 8-byte, won't happen for witness data\n offset += 8;\n return 0;\n };\n\n const count = readVarInt();\n for (let i = 0; i < count; i++) {\n const len = readVarInt();\n items.push(witness.subarray(offset, offset + len) as Buffer);\n offset += len;\n }\n\n return items;\n}\n\n"],"names":["createPayoutScript","params","connector","createPayoutConnector","buildPayoutPsbt","payoutTxHex","stripHexPrefix","peginTxHex","assertTxHex","payoutConnector","payoutScriptBytes","hexToUint8Array","controlBlock","payoutTx","Transaction","peginTx","assertTx","psbt","Psbt","input0","input1","input0Txid","uint8ArrayToHex","peginTxid","input1Txid","expectedInput1Txid","peginPrevOut","input1PrevOut","TAPSCRIPT_LEAF_VERSION","Buffer","tapInternalPubkey","output","extractPayoutSignature","signedPsbtHex","depositorPubkey","inputIndex","signedPsbt","input","depositorPubkeyBytes","sigEntry","extractSchnorrSig","witnessStack","parseWitnessStack","sig","sighashByte","witness","items","offset","readVarInt","first","val","count","i","len"],"mappings":"2JA8IA,eAAsBA,EACpBC,EAC6B,CAE7B,MAAMC,EAAY,MAAMC,EAAAA,sBACtB,CACE,UAAWF,EAAO,UAClB,cAAeA,EAAO,cACtB,aAAcA,EAAO,aACrB,qBAAsBA,EAAO,qBAC7B,cAAeA,EAAO,aAAA,EAExBA,EAAO,OAAA,EAGT,MAAO,CACL,aAAcC,EAAU,aACxB,kBAAmBA,EAAU,kBAC7B,aAAcA,EAAU,aACxB,QAASA,EAAU,QACnB,mBAAoBA,EAAU,kBAAA,CAElC,CCnDA,eAAsBE,EACpBH,EAC2B,CAE3B,MAAMI,EAAcC,EAAAA,eAAeL,EAAO,WAAW,EAC/CM,EAAaD,EAAAA,eAAeL,EAAO,UAAU,EAC7CO,EAAcF,EAAAA,eAAeL,EAAO,WAAW,EAG/CQ,EAAkB,MAAMT,EAAmB,CAC/C,UAAWC,EAAO,mBAClB,cAAeA,EAAO,uBACtB,aAAcA,EAAO,sBACrB,qBAAsBA,EAAO,8BAC7B,cAAeA,EAAO,cACtB,QAASA,EAAO,OAAA,CACjB,EAEKS,EAAoBC,EAAAA,gBAAgBF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T=require("bitcoinjs-lib"),h=require("buffer"),i=require("./constants-EiyZkXce.cjs");function H(t,e,n,r){if(!Number.isInteger(r)||r<1)throw new Error(`Invalid numOutputs: expected a positive integer, got ${r}`);if(t.length===0)throw new Error("Insufficient funds: no UTXOs available");const d=t.filter(o=>{const c=h.Buffer.from(o.scriptPubKey,"hex");return!!T.script.decompile(c)});if(d.length===0)throw new Error("Insufficient funds: no valid UTXOs available (all have invalid scripts)");const P=[...d].sort((o,c)=>c.value-o.value),f=[];let a=0n,s=0n;for(const o of P){f.push(o),a+=BigInt(o.value);const c=f.length*i.P2TR_INPUT_SIZE,g=r*i.MAX_NON_LEGACY_OUTPUT_SIZE,w=c+g+i.TX_BUFFER_SIZE_OVERHEAD;if(s=BigInt(Math.ceil(w*n))+BigInt(i.rateBasedTxBufferFee(n)),a-e-s>i.DUST_THRESHOLD){const u=BigInt(Math.ceil(i.MAX_NON_LEGACY_OUTPUT_SIZE*n));s+=u}if(a>=e+s){const u=a-e-s;return{selectedUTXOs:f,totalValue:a,fee:s,changeAmount:u}}}throw new Error(`Insufficient funds: need ${e+s} sats (${e} pegin + ${s} fee), have ${a} sats`)}function U(t){return t>i.DUST_THRESHOLD}function I(){return i.BTC_DUST_SAT}function v(t){const e=t.startsWith("0x")?t.slice(2):t;return`0x${T.Transaction.fromHex(e).getId()}`}var l=(t=>(t.P2PKH="P2PKH",t.P2SH="P2SH",t.P2WPKH="P2WPKH",t.P2WSH="P2WSH",t.P2TR="P2TR",t.UNKNOWN="UNKNOWN",t))(l||{});function S(t){const e=t.length;return e===25&&t[0]===118&&t[1]===169&&t[2]===20&&t[23]===136&&t[24]===172?"P2PKH":e===23&&t[0]===169&&t[1]===20&&t[22]===135?"P2SH":e===22&&t[0]===0&&t[1]===20?"P2WPKH":e===34&&t[0]===0&&t[1]===32?"P2WSH":e===34&&t[0]===81&&t[1]===32?"P2TR":"UNKNOWN"}function E(t,e){const n=h.Buffer.from(t.scriptPubKey,"hex"),r=S(n);switch(r){case l.P2WPKH:return{witnessUtxo:{script:n,value:t.value}};case l.P2WSH:{if(!t.witnessScript)throw new Error("Missing witnessScript for P2WSH input");return{witnessUtxo:{script:n,value:t.value},witnessScript:h.Buffer.from(t.witnessScript,"hex")}}case l.P2TR:{if(e&&e.length!==32)throw new Error(`Invalid tapInternalKey length: expected 32 bytes, got ${e.length}`);return{witnessUtxo:{script:n,value:t.value},...e&&{tapInternalKey:e}}}default:throw new Error(`Unsupported script type: ${r}`)}}exports.BitcoinScriptType=l;exports.calculateBtcTxHash=v;exports.getDustThreshold=I;exports.getPsbtInputFields=E;exports.getScriptType=S;exports.selectUtxosForPegin=H;exports.shouldAddChangeOutput=U;
|
|
2
|
-
//# sourceMappingURL=psbtInputFields-C0nKn_GD.cjs.map
|