@babylonlabs-io/ts-sdk 0.17.1 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{errors-DKLboMnq.cjs → errors-DAKpPfl7.cjs} +2 -2
- package/dist/{errors-DKLboMnq.cjs.map → errors-DAKpPfl7.cjs.map} +1 -1
- package/dist/{errors-KY63mgWT.js → errors-DARTQrP3.js} +2 -2
- package/dist/{errors-KY63mgWT.js.map → errors-DARTQrP3.js.map} +1 -1
- package/dist/index-DKfhZvdn.cjs +2 -0
- package/dist/index-DKfhZvdn.cjs.map +1 -0
- package/dist/{index-Dw7FAwne.js → index-qIcjkxLw.js} +135 -137
- package/dist/index-qIcjkxLw.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +2 -2
- package/dist/tbv/core/clients/eth/vault-registry-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +1 -1
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +54 -0
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.js +2 -2
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +2 -2
- package/dist/tbv/integrations/aave/clients/abis/AaveSpoke.abi.json.d.ts +140 -0
- package/dist/tbv/integrations/aave/clients/index.d.ts +1 -1
- package/dist/tbv/integrations/aave/clients/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/clients/query.d.ts +12 -1
- package/dist/tbv/integrations/aave/clients/query.d.ts.map +1 -1
- 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 +2 -2
- package/dist/tbv/integrations/aave/index.d.ts.map +1 -1
- package/dist/tbv/integrations/aave/index.js +141 -129
- package/dist/tbv/integrations/aave/index.js.map +1 -1
- package/dist/tbv/integrations/aave/types.d.ts +10 -0
- package/dist/tbv/integrations/aave/types.d.ts.map +1 -1
- package/package.json +1 -1
- package/dist/index-D3z3SZAj.cjs +0 -2
- package/dist/index-D3z3SZAj.cjs.map +0 -1
- package/dist/index-Dw7FAwne.js.map +0 -1
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";var S=Object.defineProperty;var F=(n,t,e)=>t in n?S(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var g=(n,t,e)=>F(n,typeof t!="symbol"?t+"":t,e);const P=require("./types-DEWiqXYp.cjs"),k=21e6*1e8,h=3e4;async function d(n,t){const e=new AbortController,r=setTimeout(()=>e.abort(),h),o=[e.signal,t==null?void 0:t.signal].filter(Boolean);try{return await fetch(n,{...t,signal:AbortSignal.any(o)})}catch(s){throw clearTimeout(r),s!=null&&typeof s=="object"&&"name"in s&&s.name==="AbortError"?new Error(`Mempool API request timed out after ${h}ms: ${n}`):s}}const v=1e4;function T(n){return Number.isInteger(n)&&n>0&&n<=k}function j(n){return Number.isInteger(n)&&n>0&&n<=v}function x(n,t){return!Number.isInteger(n)||n<0?!1:t===void 0||n<t}const $={mainnet:"https://mempool.space/api",testnet:"https://mempool.space/testnet/api",signet:"https://mempool.space/signet/api"};async function c(n,t){try{const e=await d(n,t);if(!e.ok){const o=await e.text();throw new Error(`Mempool API error (${e.status}): ${o||e.statusText}`)}const r=e.headers.get("content-type");return r!=null&&r.includes("application/json")?await e.json():await e.text()}catch(e){throw e instanceof Error?new Error(`Failed to fetch from mempool API: ${e.message}`):new Error("Failed to fetch from mempool API: Unknown error")}}async function R(n,t){try{const e=await d(`${t}/tx`,{method:"POST",body:n,headers:{"Content-Type":"text/plain"}});if(!e.ok){const o=await e.text();let s;try{s=JSON.parse(o).message}catch{s=o}throw new Error(s||`Failed to broadcast transaction: ${e.statusText}`)}return await e.text()}catch(e){throw e instanceof Error?new Error(`Failed to broadcast BTC transaction: ${e.message}`):new Error("Failed to broadcast BTC transaction: Unknown error")}}async function V(n,t){return c(`${t}/tx/${n}`)}async function B(n,t){try{const e=await d(`${t}/tx/${n}/hex`);if(!e.ok){const r=await e.text();throw new Error(`Mempool API error (${e.status}): ${r||e.statusText}`)}return await e.text()}catch(e){throw e instanceof Error?new Error(`Failed to get transaction hex for ${n}: ${e.message}`):new Error(`Failed to get transaction hex for ${n}: Unknown error`)}}async function C(n,t,e){const r=await V(n,e);if(!x(t,r.vout.length))throw new Error(`Invalid vout ${t} for transaction ${n} (has ${r.vout.length} outputs)`);const o=r.vout[t];if(!T(o.value))throw new Error(`Invalid UTXO value ${o.value} for ${n}:${t}`);return{txid:n,vout:t,value:o.value,scriptPubKey:o.scriptpubkey}}async function M(n,t){try{const e=await c(`${t}/address/${n}/utxo`),r=await c(`${t}/v1/validate-address/${n}`);if(!r.isvalid)throw new Error(`Invalid Bitcoin address: ${n}. Mempool API validation failed.`);for(const s of e){if(!x(s.vout))throw new Error(`Invalid vout ${s.vout} for ${s.txid}`);if(!T(s.value))throw new Error(`Invalid UTXO value ${s.value} for ${s.txid}:${s.vout}`)}return e.sort((s,m)=>m.value-s.value).map(s=>({txid:s.txid,vout:s.vout,value:s.value,scriptPubKey:r.scriptPubKey,confirmed:s.status.confirmed}))}catch(e){throw e instanceof Error?new Error(`Failed to get UTXOs for address ${n}: ${e.message}`):new Error(`Failed to get UTXOs for address ${n}: Unknown error`)}}function D(n){return $[n]}async function O(n,t){return c(`${t}/address/${n}/txs`)}async function U(n){const t=await d(`${n}/v1/fees/recommended`);if(!t.ok)throw new Error(`Failed to fetch network fees: ${t.status} ${t.statusText}`);const e=await t.json(),r=["fastestFee","halfHourFee","hourFee","economyFee","minimumFee"];for(const o of r)if(!j(e[o]))throw new Error(`Invalid fee rate ${o}=${e[o]} from mempool API: expected a positive number ≤ ${v}`);if(e.minimumFee>e.economyFee||e.economyFee>e.hourFee||e.hourFee>e.halfHourFee||e.halfHourFee>e.fastestFee)throw new Error(`Fee rate ordering violation from mempool API: expected minimumFee (${e.minimumFee}) <= economyFee (${e.economyFee}) <= hourFee (${e.hourFee}) <= halfHourFee (${e.halfHourFee}) <= fastestFee (${e.fastestFee}).`);return e}const f=[{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"}],b=new Set(Object.values(P.DaemonStatus)),H=200;function i(n){var t;return((t=JSON.stringify(n))==null?void 0:t.slice(0,H))??"undefined"}const N="The vault provider returned an unexpected response. Please try again or contact support.";class a extends Error{constructor(e){super(N);g(this,"detail");this.name="VpResponseValidationError",this.detail=e}}const q=/^[0-9a-fA-F]+$/,_=64,w=66,y=64;function p(n){return typeof n=="string"&&n.length>0&&q.test(n)}function E(n){return typeof n=="string"&&n.length>0}function A(n,t){if(!p(n))throw new a(`VP response validation failed: "${t}" must be a non-empty hex string, got ${i(n)}`)}function u(n,t){if(!E(n))throw new a(`VP response validation failed: "${t}" must be a non-empty string, got ${i(n)}`)}function I(n,t){if(!p(n)||n.length!==_&&n.length!==w)throw new a(`VP response validation failed: "${t}" must be a ${_} or ${w}-char hex string (BTC pubkey), got ${i(n)}`)}function X(n){const t=n.presigning;if(t==null)return;if(typeof t!="object"||Array.isArray(t))throw new a('VP response validation failed: "progress.presigning" must be an object if present');const e=t;if(e.depositor_graph_created!==void 0&&typeof e.depositor_graph_created!="boolean")throw new a(`VP response validation failed: "progress.presigning.depositor_graph_created" must be a boolean if present, got ${i(e.depositor_graph_created)}`);if(e.vk_challenger_presigning_completed!==void 0&&typeof e.vk_challenger_presigning_completed!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_completed" must be a number if present, got ${i(e.vk_challenger_presigning_completed)}`);if(e.vk_challenger_presigning_total!==void 0&&typeof e.vk_challenger_presigning_total!="number")throw new a(`VP response validation failed: "progress.presigning.vk_challenger_presigning_total" must be a number if present, got ${i(e.vk_challenger_presigning_total)}`)}function K(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: getPeginStatus response is not an object");const t=n;if(!p(t.pegin_txid)||t.pegin_txid.length!==y)throw new a(`VP response validation failed: "pegin_txid" must be a ${y}-char hex string (txid), got ${i(t.pegin_txid)}`);if(typeof t.status!="string")throw new a('VP response validation failed: "status" must be a string');if(!b.has(t.status))throw new a(`VP response validation failed: unrecognized status "${t.status}". Expected one of: ${[...b].join(", ")}`);if(t.progress===null||typeof t.progress!="object"||Array.isArray(t.progress))throw new a('VP response validation failed: "progress" must be an object');if(X(t.progress),typeof t.health_info!="string")throw new a('VP response validation failed: "health_info" must be a string');if(t.last_error!==void 0&&typeof t.last_error!="string")throw new a(`VP response validation failed: "last_error" must be a string if present, got ${i(t.last_error)}`)}function L(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: requestDepositorPresignTransactions response is not an object");const t=n;if(!Array.isArray(t.txs))throw new a('VP response validation failed: "txs" must be an array');for(let e=0;e<t.txs.length;e++)W(t.txs[e],`txs[${e}]`);if(t.depositor_graph===null||typeof t.depositor_graph!="object")throw new a('VP response validation failed: "depositor_graph" must be an object');Q(t.depositor_graph)}function l(n,t){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${t}" must be an object`);A(n.tx_hex,`${t}.tx_hex`)}function W(n,t){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${t}" must be an object`);const e=n;I(e.claimer_pubkey,`${t}.claimer_pubkey`),l(e.claim_tx,`${t}.claim_tx`),l(e.assert_tx,`${t}.assert_tx`),l(e.payout_tx,`${t}.payout_tx`),u(e.payout_psbt,`${t}.payout_psbt`)}function J(n,t){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${t}" must be an object`);const e=n;u(e.wots_pks_json,`${t}.wots_pks_json`),u(e.gc_wots_keys_json,`${t}.gc_wots_keys_json`)}function G(n,t){if(n===null||typeof n!="object")throw new a(`VP response validation failed: "${t}" must be an object`);const e=n;if(I(e.challenger_pubkey,`${t}.challenger_pubkey`),l(e.challenge_assert_x_tx,`${t}.challenge_assert_x_tx`),l(e.challenge_assert_y_tx,`${t}.challenge_assert_y_tx`),l(e.nopayout_tx,`${t}.nopayout_tx`),u(e.nopayout_psbt,`${t}.nopayout_psbt`),!Array.isArray(e.challenge_assert_connectors))throw new a(`VP response validation failed: "${t}.challenge_assert_connectors" must be an array`);for(let r=0;r<e.challenge_assert_connectors.length;r++)J(e.challenge_assert_connectors[r],`${t}.challenge_assert_connectors[${r}]`);if(!Array.isArray(e.output_label_hashes))throw new a(`VP response validation failed: "${t}.output_label_hashes" must be an array`);for(let r=0;r<e.output_label_hashes.length;r++)A(e.output_label_hashes[r],`${t}.output_label_hashes[${r}]`)}function Y(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: requestDepositorClaimerArtifacts response is not an object");const t=n;if(!E(t.tx_graph_json))throw new a(`VP response validation failed: "tx_graph_json" must be a non-empty string, got ${i(t.tx_graph_json)}`);if(!p(t.verifying_key_hex))throw new a(`VP response validation failed: "verifying_key_hex" must be a non-empty hex string, got ${i(t.verifying_key_hex)}`);if(t.babe_sessions===null||typeof t.babe_sessions!="object")throw new a('VP response validation failed: "babe_sessions" must be an object');for(const[e,r]of Object.entries(t.babe_sessions)){if(r===null||typeof r!="object")throw new a(`VP response validation failed: "babe_sessions.${e}" must be an object`);const o=r;if(!p(o.decryptor_artifacts_hex))throw new a(`VP response validation failed: "babe_sessions.${e}.decryptor_artifacts_hex" must be a non-empty hex string, got ${i(o.decryptor_artifacts_hex)}`)}}function z(n){if(n===null||typeof n!="object")throw new a("VP response validation failed: getPegoutStatus response is not an object");const t=n;if(!p(t.pegin_txid)||t.pegin_txid.length!==y)throw new a(`VP response validation failed: "pegin_txid" must be a ${y}-char hex string (txid), got ${i(t.pegin_txid)}`);if(typeof t.found!="boolean")throw new a(`VP response validation failed: "found" must be a boolean, got ${i(t.found)}`);if(t.claimer!==void 0){if(t.claimer===null||typeof t.claimer!="object")throw new a('VP response validation failed: "claimer" must be an object if present');const e=t.claimer;if(typeof e.status!="string")throw new a(`VP response validation failed: "claimer.status" must be a string, got ${i(e.status)}`);if(typeof e.failed!="boolean")throw new a(`VP response validation failed: "claimer.failed" must be a boolean, got ${i(e.failed)}`)}if(t.challenger!==void 0){if(t.challenger===null||typeof t.challenger!="object")throw new a('VP response validation failed: "challenger" must be an object if present');const e=t.challenger;if(typeof e.status!="string")throw new a(`VP response validation failed: "challenger.status" must be a string, got ${i(e.status)}`)}}function Q(n){if(l(n.claim_tx,"depositor_graph.claim_tx"),l(n.assert_tx,"depositor_graph.assert_tx"),l(n.payout_tx,"depositor_graph.payout_tx"),u(n.payout_psbt,"depositor_graph.payout_psbt"),!Array.isArray(n.challenger_presign_data))throw new a('VP response validation failed: "depositor_graph.challenger_presign_data" must be an array');for(let t=0;t<n.challenger_presign_data.length;t++)G(n.challenger_presign_data[t],`depositor_graph.challenger_presign_data[${t}]`);if(typeof n.offchain_params_version!="number")throw new a('VP response validation failed: "depositor_graph.offchain_params_version" must be a number')}const Z=6e4;class ee{constructor(t,e){g(this,"client");const r={baseUrl:t,timeout:(e==null?void 0:e.timeout)??Z,retries:e==null?void 0:e.retries,retryDelay:e==null?void 0:e.retryDelay,retryableFor:e==null?void 0:e.retryableFor,headers:e==null?void 0:e.headers};this.client=new P.JsonRpcClient(r)}async requestDepositorPresignTransactions(t,e){const r=await this.client.call("vaultProvider_requestDepositorPresignTransactions",t,e);return L(r),r}async submitDepositorPresignatures(t,e){return this.client.call("vaultProvider_submitDepositorPresignatures",t,e)}async submitDepositorWotsKey(t,e){return this.client.call("vaultProvider_submitDepositorWotsKey",t,e)}async requestDepositorClaimerArtifacts(t,e){const r=await this.client.call("vaultProvider_requestDepositorClaimerArtifacts",t,e);return Y(r),r}async getPeginStatus(t,e){const r=await this.client.call("vaultProvider_getPeginStatus",t,e);return K(r),r}async getPegoutStatus(t,e){const r=await this.client.call("vaultProvider_getPegoutStatus",t,e);return z(r),r}}class te{constructor(t,e){this.publicClient=t,this.contractAddress=e}async getVaultBasicInfo(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getBtcVaultBasicInfo",args:[t]});return{depositor:e[0],depositorBtcPubKey:e[1],amount:e[2],vaultProvider:e[3],status:e[4],applicationEntryPoint:e[5],createdAt:e[6]}}async getVaultProtocolInfo(t){const e=await this.publicClient.readContract({address:this.contractAddress,abi:f,functionName:"getBtcVaultProtocolInfo",args:[t]});return{depositorSignedPeginTx:e[0],universalChallengersVersion:e[1],appVaultKeepersVersion:e[2],offchainParamsVersion:e[3],verifiedAt:e[4],depositorWotsPkHash:e[5],hashlock:e[6],htlcVout:e[7],depositorPopSignature:e[8],prePeginTxHash:e[9],vaultProviderCommissionBps:e[10]}}async getVaultData(t){const[e,r]=await Promise.all([this.getVaultBasicInfo(t),this.getVaultProtocolInfo(t)]);if(!r.depositorSignedPeginTx||r.depositorSignedPeginTx==="0x")throw new Error(`Vault ${t} not found on-chain or has no pegin transaction`);return{basic:e,protocol:r}}}exports.BTCVaultRegistryABI=f;exports.MEMPOOL_API_URLS=$;exports.VaultProviderRpcClient=ee;exports.ViemVaultRegistryReader=te;exports.VpResponseValidationError=a;exports.getAddressTxs=O;exports.getAddressUtxos=M;exports.getMempoolApiUrl=D;exports.getNetworkFees=U;exports.getTxHex=B;exports.getTxInfo=V;exports.getUtxoInfo=C;exports.pushTx=R;
|
|
2
|
+
//# sourceMappingURL=index-DKfhZvdn.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index-DKfhZvdn.cjs","sources":["../src/tbv/core/clients/mempool/mempoolApi.ts","../src/tbv/core/contracts/abis/BTCVaultRegistry.abi.ts","../src/tbv/core/clients/vault-provider/validators.ts","../src/tbv/core/clients/vault-provider/api.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 * 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] 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 * 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","BTCVaultRegistryABI","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","ViemVaultRegistryReader","publicClient","contractAddress","vaultId","result","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,C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