@babylonlabs-io/ts-sdk 0.62.1 → 0.64.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/{BTCVaultRegistry.abi-B3BLhpJ4.js → BTCVaultRegistry.abi-CJwWI2EO.js} +5 -1
- package/dist/{BTCVaultRegistry.abi-B3BLhpJ4.js.map → BTCVaultRegistry.abi-CJwWI2EO.js.map} +1 -1
- package/dist/{BTCVaultRegistry.abi-3VLWva2x.cjs → BTCVaultRegistry.abi-z7d_eP22.cjs} +2 -2
- package/dist/{BTCVaultRegistry.abi-3VLWva2x.cjs.map → BTCVaultRegistry.abi-z7d_eP22.cjs.map} +1 -1
- package/dist/{PeginManager-C8kIl0gw.js → PeginManager-BBl4xkWz.js} +7 -6
- package/dist/{PeginManager-C8kIl0gw.js.map → PeginManager-BBl4xkWz.js.map} +1 -1
- package/dist/{PeginManager-BgBt4hqp.cjs → PeginManager-p-ajwSxG.cjs} +2 -2
- package/dist/{PeginManager-BgBt4hqp.cjs.map → PeginManager-p-ajwSxG.cjs.map} +1 -1
- package/dist/{ProtocolParams.abi-CV938AYZ.js → ProtocolParams.abi-C0TSRaHV.js} +17 -1
- package/dist/{ProtocolParams.abi-CV938AYZ.js.map → ProtocolParams.abi-C0TSRaHV.js.map} +1 -1
- package/dist/{ProtocolParams.abi-C8U7BHCS.cjs → ProtocolParams.abi-CYZoV2EI.cjs} +2 -2
- package/dist/{ProtocolParams.abi-C8U7BHCS.cjs.map → ProtocolParams.abi-CYZoV2EI.cjs.map} +1 -1
- package/dist/batchPoll-6L5oToGr.cjs +2 -0
- package/dist/batchPoll-6L5oToGr.cjs.map +1 -0
- package/dist/{batchPoll-9w-Gv5dt.js → batchPoll-cIxrSLLJ.js} +43 -21
- package/dist/batchPoll-cIxrSLLJ.js.map +1 -0
- package/dist/{buildAndBroadcastRefund-CH2awK6h.js → buildAndBroadcastRefund-C2fP3Rva.js} +5 -5
- package/dist/{buildAndBroadcastRefund-CH2awK6h.js.map → buildAndBroadcastRefund-C2fP3Rva.js.map} +1 -1
- package/dist/{buildAndBroadcastRefund-CYzhA_B8.cjs → buildAndBroadcastRefund-CYtnT0D_.cjs} +2 -2
- package/dist/{buildAndBroadcastRefund-CYzhA_B8.cjs.map → buildAndBroadcastRefund-CYtnT0D_.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +157 -146
- package/dist/{mempoolApi-BXaOZL_I.js → mempoolApi-BxSINXIB.js} +2 -2
- package/dist/{mempoolApi-BXaOZL_I.js.map → mempoolApi-BxSINXIB.js.map} +1 -1
- package/dist/{mempoolApi-Bsurcl43.cjs → mempoolApi-CXfr-L6x.cjs} +2 -2
- package/dist/{mempoolApi-Bsurcl43.cjs.map → mempoolApi-CXfr-L6x.cjs.map} +1 -1
- package/dist/{noPayout-oaUVsEjk.js → noPayout-BaZGRLD2.js} +2 -2
- package/dist/{noPayout-oaUVsEjk.js.map → noPayout-BaZGRLD2.js.map} +1 -1
- package/dist/{noPayout-CbxQqBw1.cjs → noPayout-CnQ1WLtr.cjs} +2 -2
- package/dist/{noPayout-CbxQqBw1.cjs.map → noPayout-CnQ1WLtr.cjs.map} +1 -1
- package/dist/reconstructPeginParams-BVA67Iv8.js +400 -0
- package/dist/reconstructPeginParams-BVA67Iv8.js.map +1 -0
- package/dist/reconstructPeginParams-BmUVK7F_.cjs +2 -0
- package/dist/reconstructPeginParams-BmUVK7F_.cjs.map +1 -0
- package/dist/{signPsbtsWithFallback-DC4rUCsy.js → signPsbtsWithFallback-Bb66DfY5.js} +2 -2
- package/dist/{signPsbtsWithFallback-DC4rUCsy.js.map → signPsbtsWithFallback-Bb66DfY5.js.map} +1 -1
- package/dist/{signPsbtsWithFallback-DbOmw8Ou.cjs → signPsbtsWithFallback-PTgWxsG3.cjs} +2 -2
- package/dist/{signPsbtsWithFallback-DbOmw8Ou.cjs.map → signPsbtsWithFallback-PTgWxsG3.cjs.map} +1 -1
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts +11 -0
- package/dist/tbv/core/clients/eth/protocol-params-reader.d.ts.map +1 -1
- package/dist/tbv/core/clients/eth/types.d.ts +18 -0
- package/dist/tbv/core/clients/eth/types.d.ts.map +1 -1
- package/dist/tbv/core/clients/index.cjs +1 -1
- package/dist/tbv/core/clients/index.js +2 -2
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts +4 -0
- package/dist/tbv/core/contracts/abis/BTCVaultRegistry.abi.d.ts.map +1 -1
- package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts +10 -0
- package/dist/tbv/core/contracts/abis/ProtocolParams.abi.d.ts.map +1 -1
- package/dist/tbv/core/contracts/index.cjs +1 -1
- package/dist/tbv/core/contracts/index.js +2 -2
- package/dist/tbv/core/index.cjs +1 -1
- package/dist/tbv/core/index.d.ts +3 -0
- package/dist/tbv/core/index.d.ts.map +1 -1
- package/dist/tbv/core/index.js +151 -140
- package/dist/tbv/core/managers/index.cjs +1 -1
- package/dist/tbv/core/managers/index.js +2 -2
- package/dist/tbv/core/primitives/index.cjs +1 -1
- package/dist/tbv/core/primitives/index.js +2 -2
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts +16 -2
- package/dist/tbv/core/primitives/psbt/assertWasmPeginSizing.d.ts.map +1 -1
- package/dist/tbv/core/recovery/__tests__/deriveHashlocksFromPrePegin.test.d.ts +10 -0
- package/dist/tbv/core/recovery/__tests__/deriveHashlocksFromPrePegin.test.d.ts.map +1 -0
- package/dist/tbv/core/recovery/__tests__/peginSizingIntegrity.test.d.ts +16 -0
- package/dist/tbv/core/recovery/__tests__/peginSizingIntegrity.test.d.ts.map +1 -0
- package/dist/tbv/core/recovery/__tests__/reconstructPeginParams.test.d.ts +14 -0
- package/dist/tbv/core/recovery/__tests__/reconstructPeginParams.test.d.ts.map +1 -0
- package/dist/tbv/core/recovery/deriveHashlocksFromPrePegin.d.ts +37 -0
- package/dist/tbv/core/recovery/deriveHashlocksFromPrePegin.d.ts.map +1 -0
- package/dist/tbv/core/recovery/index.d.ts +18 -0
- package/dist/tbv/core/recovery/index.d.ts.map +1 -0
- package/dist/tbv/core/recovery/peginParamsCandidates.d.ts +98 -0
- package/dist/tbv/core/recovery/peginParamsCandidates.d.ts.map +1 -0
- package/dist/tbv/core/recovery/reconstructPeginParams.d.ts +112 -0
- package/dist/tbv/core/recovery/reconstructPeginParams.d.ts.map +1 -0
- package/dist/tbv/core/recovery/recoveryErrors.d.ts +97 -0
- package/dist/tbv/core/recovery/recoveryErrors.d.ts.map +1 -0
- package/dist/tbv/core/services/index.cjs +1 -1
- package/dist/tbv/core/services/index.js +2 -2
- package/dist/tbv/index.cjs +1 -1
- package/dist/tbv/index.js +151 -140
- package/dist/verifyScriptPathSchnorrSignature-DPAd_qke.cjs +2 -0
- package/dist/verifyScriptPathSchnorrSignature-DPAd_qke.cjs.map +1 -0
- package/dist/{verifyScriptPathSchnorrSignature-XsICweGG.js → verifyScriptPathSchnorrSignature-i-koT139.js} +176 -170
- package/dist/verifyScriptPathSchnorrSignature-i-koT139.js.map +1 -0
- package/package.json +1 -1
- package/dist/batchPoll-9w-Gv5dt.js.map +0 -1
- package/dist/batchPoll-WMXweT_O.cjs +0 -2
- package/dist/batchPoll-WMXweT_O.cjs.map +0 -1
- package/dist/errors-BxL9QObN.js +0 -137
- package/dist/errors-BxL9QObN.js.map +0 -1
- package/dist/errors-DwjbI9h1.cjs +0 -2
- package/dist/errors-DwjbI9h1.cjs.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-B8zK1ctE.cjs +0 -2
- package/dist/verifyScriptPathSchnorrSignature-B8zK1ctE.cjs.map +0 -1
- package/dist/verifyScriptPathSchnorrSignature-XsICweGG.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var Oe=Object.defineProperty;var $e=(s,t,e)=>t in s?Oe(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var T=(s,t,e)=>$e(s,typeof t!="symbol"?t+"":t,e);const x=require("./sha2-DsrLC4NM.cjs"),W=require("bitcoinjs-lib"),te=require("buffer"),V=require("viem"),R=require("./BTCVaultRegistry.abi-3VLWva2x.cjs"),O=require("./errors-CGcNP0rV.cjs"),D=require("@babylonlabs-io/babylon-tbv-rust-wasm"),$=require("./verifyScriptPathSchnorrSignature-B8zK1ctE.cjs"),Y=require("./peginInput-Ci921gTl.cjs"),h=require("./bitcoin-m84N5a8o.cjs"),Ve=require("./signing-Bnsro0hE.cjs"),ce=require("./validation-CDbOaDj7.cjs"),se=require("./parseFundingOutpoints-CIO9Ok1L.cjs"),N=require("./signPsbtsWithFallback-DbOmw8Ou.cjs"),H=require("./waitForTransactionReceiptSmartAware-AgZ-3WV_.cjs"),le=require("./fundPeginTransaction-BLD8FRL9.cjs"),L=require("./constants-DU5CGcqO.cjs"),ne=require("./mempoolApi-Bsurcl43.cjs");function Me(s){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const e in s)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(s,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>s[e]})}}return t.default=s,Object.freeze(t)}const me=Me(W),X=BigInt(2**32-1),ue=BigInt(32);function Fe(s,t=!1){return t?{h:Number(s&X),l:Number(s>>ue&X)}:{h:Number(s>>ue&X)|0,l:Number(s&X)|0}}function Ue(s,t=!1){const e=s.length;let n=new Uint32Array(e),o=new Uint32Array(e);for(let r=0;r<e;r++){const{h:i,l:a}=Fe(s[r],t);[n[r],o[r]]=[i,a]}return[n,o]}const Ne=(s,t,e)=>s<<e|t>>>32-e,We=(s,t,e)=>t<<e|s>>>32-e,De=(s,t,e)=>t<<e-32|s>>>64-e,Le=(s,t,e)=>s<<e-32|t>>>64-e,Xe=64;function Pe(s){const t=s.prepeginTxid.toLowerCase();if(!/^[0-9a-f]+$/.test(t)||t.length!==Xe)throw new Error(`buildDepositTerms: prepeginTxid must be 64 hex chars, got "${s.prepeginTxid}"`);if(s.peginAmounts.length===0)throw new Error("buildDepositTerms: at least one pegin amount is required");if(s.timelockPegin<=0||s.timelockAssert<=0||s.timelockRefund<=0)throw new Error("buildDepositTerms: timelocks must be positive");if(!Number.isInteger(s.maxAcceptableCommissionBps)||s.maxAcceptableCommissionBps<0||s.maxAcceptableCommissionBps>=L.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`buildDepositTerms: maxAcceptableCommissionBps must be an integer in [0, ${L.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${s.maxAcceptableCommissionBps}`);const e=BigInt(L.BPS_DENOMINATOR),n=s.peginAmounts.map((o,r)=>({htlcVout:r,vaultProviderBtcPubkey:s.vaultProviderBtcPubkey,peginAmount:o,commissionFee:o*BigInt(s.maxAcceptableCommissionBps)/e,depositorClaimValue:s.depositorClaimValue,peginMaxFee:s.peginMaxFee}));return{vaultCoreVersion:s.vaultCoreVersion,protocolFeeRate:s.protocolFeeRate,timelockPegin:s.timelockPegin,timelockAssert:s.timelockAssert,timelockRefund:s.timelockRefund,prepeginTxid:t,prepeginMaxFee:s.prepeginMaxFee,vaultKeeperBtcPubkeys:[...s.vaultKeeperBtcPubkeys],universalChallengerBtcPubkeys:[...s.universalChallengerBtcPubkeys],vaults:n}}const z=25,re=9999;function G(s){if(!Number.isInteger(s)||s<0||s>=L.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`Quoted commissionBps must be an integer in [0, ${L.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${s}`);return Math.min(s+z,re)}const qe=/^0x[0-9a-f]+$/i,Ke=/^[0-9a-f]+$/i,Ge=/^[A-Za-z0-9+/]+={0,2}$/;function M(s){if(typeof s!="string"||s.length===0)throw new Error("BTC wallet returned empty public key");return h.processPublicKeyToXOnly(s).toLowerCase()}function ze(s){if(typeof s!="string"||s.length===0)throw new Error("BTC wallet returned empty BIP-322 signature");if(s.startsWith("0x")||s.startsWith("0X")){if(!qe.test(s)||s.length<4||s.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return s.toLowerCase()}if(Ke.test(s)){if(s.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return`0x${s.toLowerCase()}`}if(!Ge.test(s)||s.length%4!==0)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");const t=te.Buffer.from(s,"base64");if(t.length===0||t.toString("base64")!==s)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");return`0x${t.toString("hex")}`}async function be(s){const{wallet:t,depositTerms:e,fundedPrePeginTxHex:n,depositorBtcPubkey:o}=s,r=typeof t.approveDepositTerms=="function"?t.approveDepositTerms:void 0;if(!r&&!e)return;const i=n.startsWith("0x")?n.slice(2):n,c=W.Transaction.fromHex(i).getId();if(e&&e.prepeginTxid.replace(/^0x/,"").toLowerCase()!==c)throw new Error(`Deposit terms do not match the transaction being broadcast: terms are for prepeginTxid ${e.prepeginTxid}, but this transaction is ${c}.`);if(!r)return;if(!e)throw new Error("This wallet requires approved deposit terms before signing the Pre-PegIn transaction, but none were provided. Pass PreparePeginResult.depositTerms (fresh flows) or a resume rebuild.");if(typeof t.deriveContextHash!="function")throw new Error("A deposit-approval wallet must also implement deriveContextHash, but this one does not.");const l=se.parseFundingOutpointsFromTx(n);(await se.deriveVaultRoot({deriveContextHash:t.deriveContextHash.bind(t)},{depositorBtcPubkey:h.hexToUint8Array(M(o)),fundingOutpoints:l})).fill(0),await r(e)}const je=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),xe=Uint8Array.from(new Array(16).fill(0).map((s,t)=>t)),Ye=xe.map(s=>(9*s+5)%16),we=(()=>{const e=[[xe],[Ye]];for(let n=0;n<4;n++)for(let o of e)o.push(o[n].map(r=>je[r]));return e})(),ye=we[0],ke=we[1],Te=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(s=>Uint8Array.from(s)),Qe=ye.map((s,t)=>s.map(e=>Te[t][e])),Ze=ke.map((s,t)=>s.map(e=>Te[t][e])),Je=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),et=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function he(s,t,e,n){return s===0?t^e^n:s===1?t&e|~t&n:s===2?(t|~e)^n:s===3?t&n|e&~n:t^(e|~n)}const q=new Uint32Array(16);class tt extends x.HashMD{constructor(){super(64,20,8,!0);T(this,"h0",1732584193);T(this,"h1",-271733879);T(this,"h2",-1732584194);T(this,"h3",271733878);T(this,"h4",-1009589776)}get(){const{h0:e,h1:n,h2:o,h3:r,h4:i}=this;return[e,n,o,r,i]}set(e,n,o,r,i){this.h0=e|0,this.h1=n|0,this.h2=o|0,this.h3=r|0,this.h4=i|0}process(e,n){for(let g=0;g<16;g++,n+=4)q[g]=e.getUint32(n,!0);let o=this.h0|0,r=o,i=this.h1|0,a=i,c=this.h2|0,l=c,u=this.h3|0,P=u,w=this.h4|0,y=w;for(let g=0;g<5;g++){const A=4-g,B=Je[g],p=et[g],S=ye[g],m=ke[g],b=Qe[g],E=Ze[g];for(let d=0;d<16;d++){const k=x.rotl(o+he(g,i,c,u)+q[S[d]]+B,b[d])+w|0;o=w,w=u,u=x.rotl(c,10)|0,c=i,i=k}for(let d=0;d<16;d++){const k=x.rotl(r+he(A,a,l,P)+q[m[d]]+p,E[d])+y|0;r=y,y=P,P=x.rotl(l,10)|0,l=a,a=k}}this.set(this.h1+c+P|0,this.h2+u+y|0,this.h3+w+r|0,this.h4+o+a|0,this.h0+i+l|0)}roundClean(){x.clean(q)}destroy(){this.destroyed=!0,x.clean(this.buffer),this.set(0,0,0,0,0)}}const st=x.createHasher(()=>new tt),nt=BigInt(0),U=BigInt(1),ot=BigInt(2),rt=BigInt(7),it=BigInt(256),at=BigInt(113),Be=[],Ee=[],ve=[];for(let s=0,t=U,e=1,n=0;s<24;s++){[e,n]=[n,(2*e+3*n)%5],Be.push(2*(5*n+e)),Ee.push((s+1)*(s+2)/2%64);let o=nt;for(let r=0;r<7;r++)t=(t<<U^(t>>rt)*at)%it,t&ot&&(o^=U<<(U<<BigInt(r))-U);ve.push(o)}const Ae=Ue(ve,!0),ct=Ae[0],lt=Ae[1],de=(s,t,e)=>e>32?De(s,t,e):Ne(s,t,e),ge=(s,t,e)=>e>32?Le(s,t,e):We(s,t,e);function ut(s,t=24){const e=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)e[i]=s[i]^s[i+10]^s[i+20]^s[i+30]^s[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=e[c],u=e[c+1],P=de(l,u,1)^e[a],w=ge(l,u,1)^e[a+1];for(let y=0;y<50;y+=10)s[i+y]^=P,s[i+y+1]^=w}let o=s[2],r=s[3];for(let i=0;i<24;i++){const a=Ee[i],c=de(o,r,a),l=ge(o,r,a),u=Be[i];o=s[u],r=s[u+1],s[u]=c,s[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)e[a]=s[i+a];for(let a=0;a<10;a++)s[i+a]^=~e[(a+2)%10]&e[(a+4)%10]}s[0]^=ct[n],s[1]^=lt[n]}x.clean(e)}class ie{constructor(t,e,n,o=!1,r=24){T(this,"state");T(this,"pos",0);T(this,"posOut",0);T(this,"finished",!1);T(this,"state32");T(this,"destroyed",!1);T(this,"blockLen");T(this,"suffix");T(this,"outputLen");T(this,"enableXOF",!1);T(this,"rounds");if(this.blockLen=t,this.suffix=e,this.outputLen=n,this.enableXOF=o,this.rounds=r,x.anumber(n,"outputLen"),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=x.u32(this.state)}clone(){return this._cloneInto()}keccak(){x.swap32IfBE(this.state32),ut(this.state32,this.rounds),x.swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(t){x.aexists(this),x.abytes(t);const{blockLen:e,state:n}=this,o=t.length;for(let r=0;r<o;){const i=Math.min(e-this.pos,o-r);for(let a=0;a<i;a++)n[this.pos++]^=t[r++];this.pos===e&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:e,pos:n,blockLen:o}=this;t[n]^=e,(e&128)!==0&&n===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){x.aexists(this,!1),x.abytes(t),this.finish();const e=this.state,{blockLen:n}=this;for(let o=0,r=t.length;o<r;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,r-o);t.set(e.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return x.anumber(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(x.aoutput(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,x.clean(this.state)}_cloneInto(t){const{blockLen:e,suffix:n,outputLen:o,rounds:r,enableXOF:i}=this;return t||(t=new ie(e,n,o,i,r)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=r,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}}const ht=(s,t,e,n={})=>x.createHasher(()=>new ie(t,s,e),n),dt=ht(1,136,32),fe=64,_=20,oe=4,Se=2,gt=0,ft=1,K=[64,64],pt=s=>Array.from(s).map(t=>t.toString(16).padStart(2,"0")).join("");function ae(s){return st(x.sha256(s))}function _e(s){return(1<<s)-1}function mt(s){let t=1;for(;t*t<s+1;)t++;return Math.max(t,2)}function Pt(s){const t=oe,e=s*_e(t);return{d:t,n:s,checksum_radix:mt(e)}}function Q(s,t){const e=[];let n=t;for(;n>0;)e.push(n&255),n>>>=8;const o=new Uint8Array(s.length+e.length);o.set(s);for(let r=0;r<e.length;r++)o[s.length+r]=e[r];return ae(o)}function Z(s,t){let e=s;for(let n=0;n<t;n++)e=ae(e);return e}function bt(s,t){const e=_e(t.d),n=t.checksum_radix-1,o=Math.floor(t.n*e/t.checksum_radix),r=[];for(let u=0;u<t.n;u++){const P=Q(s,u+Se),w=Z(P,e);r.push(Array.from(w))}const i=Q(s,gt),a=Z(i,n),c=Q(s,ft),l=Z(c,o);return{config:t,message_terminals:r,checksum_major_terminal:Array.from(l),checksum_minor_terminal:Array.from(a)}}async function Ce(s){try{if(s.length!==fe)throw new Error(`WOTS seed must be exactly ${fe} bytes, got ${s.length}`);const t=[];for(let e=0;e<K.length;e++){const n=K[e],o=Pt(n),r=new Uint8Array(s.length+1);r.set(s),r[s.length]=e;const i=ae(r);try{const a=bt(i,o);if(a.config.d!==oe)throw new Error(`Block ${e}: expected d=${oe}, got d=${a.config.d}`);if(a.config.n!==n)throw new Error(`Block ${e}: expected n=${n}, got n=${a.config.n}`);if(a.message_terminals.length!==n)throw new Error(`Block ${e}: expected ${n} message terminals, got ${a.message_terminals.length}`);for(let c=0;c<a.message_terminals.length;c++)if(a.message_terminals[c].length!==_)throw new Error(`Block ${e} terminal ${c}: expected ${_} bytes, got ${a.message_terminals[c].length}`);if(a.checksum_minor_terminal.length!==_)throw new Error(`Block ${e} checksum_minor: expected ${_} bytes`);if(a.checksum_major_terminal.length!==_)throw new Error(`Block ${e} checksum_major: expected ${_} bytes`);t.push(a)}finally{r.fill(0),i.fill(0)}}if(t.length!==K.length)throw new Error(`Expected ${K.length} blocks, got ${t.length}`);return t}finally{s.fill(0)}}function J(s,t,e){if(s.length!==_)throw new Error(`Block ${t} ${e}: expected ${_} bytes, got ${s.length}`);for(let n=0;n<s.length;n++){const o=s[n];if(!Number.isInteger(o)||o<0||o>255)throw new Error(`Block ${t} ${e}[${n}]: invalid byte value ${o}`)}}function Ie(s){if(s.length===0)throw new Error("Public keys array must not be empty");for(let r=0;r<s.length;r++){const i=s[r];J(i.checksum_minor_terminal,r,"checksum_minor_terminal"),J(i.checksum_major_terminal,r,"checksum_major_terminal");for(let a=0;a<i.message_terminals.length;a++)J(i.message_terminals[a],r,`message_terminal[${a}]`)}let t=0;for(const r of s)t+=Se+r.message_terminals.length;const e=new Uint8Array(t*_);let n=0;for(const r of s){e.set(r.checksum_minor_terminal,n),n+=_,e.set(r.checksum_major_terminal,n),n+=_;for(const i of r.message_terminals)e.set(i,n),n+=_}const o=dt(e);return`0x${pt(o)}`}async function xt(s,t){const e=[],n=[],o=[],r=[];try{for(let i=0;i<t;i++){const a=await D.expandWotsSeed(s,i);try{const l=await Ce(a);e.push(l),n.push(Ie(l))}finally{a.fill(0)}const c=await D.expandHashlockSecret(s,i);try{const l=h.uint8ArrayToHex(c);o.push(l),r.push(N.computeHashlock(h.ensureHexPrefix(l)).slice(2))}finally{c.fill(0)}}}finally{s.fill(0)}return{perVaultWotsKeys:e,wotsPkHashes:n,htlcSecretHexes:o,hashlocks:r}}const He=0,ee="00".repeat(32);function wt(s,t){const e={bitcoin:"bc",testnet:"tb",signet:"tb",regtest:"bcrt"};try{const n=me.address.fromBech32(s);return n.prefix===e[t]&&n.version===0&&n.data.length===20}catch{return!1}}function yt(s,t,e,n){const o=e==null?void 0:e[`${s}:${t}`];return o?Promise.resolve({txid:s,vout:t,value:o.value,scriptPubKey:o.scriptPubKey}):ne.getUtxoInfo(s,t,n)}const pe=12e4;class kt{constructor(t){T(this,"config");this.config=t}async preparePegin(t){if(t.amounts.length===0)throw new Error("amounts must contain at least one entry");const e=await this.config.btcWallet.getPublicKeyHex(),n=M(e);if(!h.isAddressFromPublicKey(t.changeAddress,e,this.config.btcNetwork))throw new Error(`Pre-PegIn changeAddress "${t.changeAddress}" is not derived from the connected wallet's public key. Refusing to build a tx that would send change to an address the signing key doesn't control.`);const o=await this.prepareSizing(n,t),r=o.selectedUTXOs.map(p=>({txid:h.hexToUint8Array(p.txid),vout:p.vout})),i=await se.deriveVaultRoot(this.config.btcWallet,{depositorBtcPubkey:h.hexToUint8Array(n),fundingOutpoints:r});let a,c;try{const p=await D.expandAuthAnchor(i);try{a=h.uint8ArrayToHex(p),c=h.uint8ArrayToHex(x.sha256(p))}finally{p.fill(0)}}catch(p){throw i.fill(0),p}const l=await xt(i,t.amounts.length),{perVaultWotsKeys:u,wotsPkHashes:P,htlcSecretHexes:w,hashlocks:y}=l,g=await this.preparePeginCommit({depositorBtcPubkeyRaw:e,depositorBtcPubkey:n,hashlocks:y,authAnchorHash:c,sizing:o,params:t});for(let p=0;p<g.perVault.length;p++)if(g.perVault[p].htlcVout!==p)throw new Error(`Internal invariant violation: htlcVout/index mismatch at vault ${p} (expected ${p}, got ${g.perVault[p].htlcVout})`);N.assertAuthAnchorOpReturn(g.fundedPrePeginTxHex,t.amounts.length,c);const{depositTerms:A,...B}=g;return{transaction:{...B,selectedUTXOs:o.selectedUTXOs,fee:o.fee,changeAmount:o.changeAmount},depositorBtcPubkey:n,derivedSecrets:{perVaultWotsKeys:u,wotsPkHashes:P,htlcSecretHexes:w,authAnchorHex:a},depositTerms:A}}async prepareSizing(t,e){const n=e.amounts.map(()=>ee),o=e.vaultKeeperBtcPubkeys.length,r=await $.buildPrePeginPsbt({vaultCoreVersion:e.vaultCoreVersion,depositorPubkey:t,vaultProviderPubkey:h.stripHexPrefix(e.vaultProviderBtcPubkey),vaultKeeperPubkeys:e.vaultKeeperBtcPubkeys.map(h.stripHexPrefix),universalChallengerPubkeys:e.universalChallengerBtcPubkeys.map(h.stripHexPrefix),hashlocks:n,timelockRefund:e.timelockRefund,pegInAmounts:e.amounts,feeRate:e.protocolFeeRate,minPeginFeeRate:e.minPeginFeeRate,numLocalChallengers:o,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:this.config.btcNetwork,authAnchorHash:ee}),i=H.selectUtxosForPegin([...e.availableUTXOs],r.totalOutputValue,e.mempoolFeeRate,le.peginOutputCount(r.htlcValues.length,!0));return{selectedUTXOs:i.selectedUTXOs,fee:i.fee,changeAmount:i.changeAmount}}async preparePeginCommit(t){const{depositorBtcPubkeyRaw:e,depositorBtcPubkey:n,hashlocks:o,authAnchorHash:r,sizing:i,params:a}=t,c=ee.toLowerCase();for(let f=0;f<o.length;f++)if(o[f].toLowerCase()===c)throw new Error(`preparePeginCommit refusing to build with sizing-pass placeholder hashlock at vault ${f} — internal substitution bug`);if(r.toLowerCase()===c)throw new Error("preparePeginCommit refusing to build with sizing-pass placeholder auth-anchor hash — internal substitution bug");const l=h.stripHexPrefix(a.vaultProviderBtcPubkey),u=a.vaultKeeperBtcPubkeys.map(h.stripHexPrefix),P=a.universalChallengerBtcPubkeys.map(h.stripHexPrefix),w=u.length,y={vaultCoreVersion:a.vaultCoreVersion,depositorPubkey:n,vaultProviderPubkey:l,vaultKeeperPubkeys:u,universalChallengerPubkeys:P,hashlocks:o,timelockRefund:a.timelockRefund,pegInAmounts:a.amounts,feeRate:a.protocolFeeRate,minPeginFeeRate:a.minPeginFeeRate,numLocalChallengers:w,councilQuorum:a.councilQuorum,councilSize:a.councilSize,network:this.config.btcNetwork,authAnchorHash:r},g=await $.buildPrePeginPsbt(y),A=h.getNetwork(this.config.btcNetwork),B=le.fundPeginTransaction({unfundedTxHex:g.psbtHex,selectedUTXOs:i.selectedUTXOs,changeAddress:a.changeAddress,changeAmount:i.changeAmount,network:A}),p=i.selectedUTXOs.reduce((f,v)=>f+BigInt(v.value),0n)-g.totalOutputValue-i.changeAmount;if(p!==i.fee)throw new Error(`Pre-PegIn funded fee ${p} does not match the sizing-pass fee ${i.fee}; refusing to publish a deposit-terms fee bound the funded transaction does not pay.`);const S=h.stripHexPrefix(H.calculateBtcTxHash(B)),m=[],b=[],E=[];for(let f=0;f<o.length;f++){const v=await $.buildPeginTxFromFundedPrePegin({prePeginParams:y,timelockPegin:a.timelockPegin,fundedPrePeginTxHex:B,htlcVout:f}),I=await Y.buildPeginInputPsbt({vaultCoreVersion:a.vaultCoreVersion,peginTxHex:v.txHex,fundedPrePeginTxHex:B,depositorPubkey:n,vaultProviderPubkey:l,vaultKeeperPubkeys:u,universalChallengerPubkeys:P,hashlock:o[f],timelockRefund:a.timelockRefund,network:this.config.btcNetwork});m.push(v),b.push(I.psbtHex),E.push(Ve.createTaprootScriptPathSignOptions(e,1))}const d=Pe({vaultCoreVersion:a.vaultCoreVersion,protocolFeeRate:a.protocolFeeRate,timelockPegin:a.timelockPegin,timelockAssert:a.timelockAssert,timelockRefund:a.timelockRefund,prepeginTxid:S,prepeginMaxFee:i.fee,vaultProviderBtcPubkey:l,vaultKeeperBtcPubkeys:u,universalChallengerBtcPubkeys:P,maxAcceptableCommissionBps:G(a.commissionBps),peginAmounts:a.amounts,depositorClaimValue:g.depositorClaimValue,peginMaxFee:g.minPeginFee});N.supportsDepositApproval(this.config.btcWallet)&&await this.config.btcWallet.approveDepositTerms(d);const k=await N.signPsbtsWithFallback(this.config.btcWallet,b,E),C=[];for(let f=0;f<k.length;f++){$.assertPsbtUnsignedTxMatches({requestedPsbtHex:b[f],returnedPsbtHex:k[f]});const v=Y.extractPeginInputSignature(k[f],n);$.assertScriptPathSchnorrSignature({requestedPsbtHex:b[f],signatureHex:v,signerXOnlyPubkeyHex:n,inputIndex:0});const I=Y.finalizePeginInputPsbt(k[f]);C.push({htlcVout:f,htlcValue:g.htlcValues[f],peginTxHex:I,peginTxid:m[f].txid,peginInputSignature:v,vaultScriptPubKey:m[f].vaultScriptPubKey})}return{fundedPrePeginTxHex:B,prePeginTxid:S,perVault:C,depositTerms:d}}async signAndBroadcast(t){const{fundedPrePeginTxHex:e,depositorBtcPubkey:n}=t,o=e.startsWith("0x")?e.slice(2):e,r=W.Transaction.fromHex(o);if(r.ins.length===0)throw new Error("Transaction has no inputs");const i=new W.Psbt;i.setVersion(r.version),i.setLocktime(r.locktime);const a=te.Buffer.from(M(n),"hex"),c=this.config.mempoolApiUrl,l=r.ins.map(m=>{const b=te.Buffer.from(m.hash).reverse().toString("hex"),E=m.index;return yt(b,E,t.localPrevouts,c).then(d=>({input:m,utxoData:d,txid:b,vout:E}))}),u=await Promise.all(l),P=u.reduce((m,b)=>m+BigInt(b.utxoData.value),0n),w=r.outs.reduce((m,b)=>m+BigInt(b.value),0n);if(P<w)throw new Error(`UTXO value mismatch: total input value (${P} sat) is less than total output value (${w} sat). This may indicate the mempool API returned manipulated UTXO data.`);const y=P-w;if(y>ce.MAX_REASONABLE_FEE_SATS)throw new Error(`Implied transaction fee (${y} sat) exceeds maximum reasonable fee (${ce.MAX_REASONABLE_FEE_SATS} sat). This may indicate manipulated UTXO data.`);for(const{input:m,utxoData:b,txid:E,vout:d}of u){const k=H.getPsbtInputFields({value:b.value,scriptPubKey:b.scriptPubKey},a);i.addInput({hash:m.hash,index:m.index,sequence:m.sequence,...k})}for(const m of r.outs)i.addOutput({script:m.script,value:m.value});await be({wallet:this.config.btcWallet,depositTerms:t.depositTerms,fundedPrePeginTxHex:e,depositorBtcPubkey:n});const g=i.toHex(),A=await this.config.btcWallet.signPsbt(g);$.assertPsbtUnsignedTxMatches({requestedPsbtHex:g,returnedPsbtHex:A});const B=W.Psbt.fromHex(A);try{B.finalizeAllInputs()}catch(m){if(!B.data.inputs.every(E=>E.finalScriptWitness||E.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${m}`)}const p=B.extractTransaction().toHex();return await ne.pushTx(p,c)}async registerPeginOnChain(t){const{unsignedPrePeginTx:e,depositorSignedPeginTx:n,vaultProvider:o,hashlock:r,htlcVout:i,depositorPayoutBtcAddress:a,depositorWotsPkHash:c,popSignature:l}=t;if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const u=this.config.ethWallet.account.address;if(!V.isAddressEqual(l.depositorEthAddress,u))throw new Error(`Proof of possession was signed for ${l.depositorEthAddress} but the Ethereum wallet is currently connected to ${u}. Reconnect the original account or call signProofOfPossession() again.`);const P=await this.assertPopMatchesBtcWallet(l),w=l.btcPopSignature,y=h.ensureHexPrefix(l.depositorBtcPubkey),g=h.ensureHexPrefix(e),A=h.ensureHexPrefix(n),B=a??await this.config.btcWallet.getAddress(),p=this.resolvePayoutScriptPubKey(P,B),S=H.calculateBtcTxHash(A),m=await D.deriveVaultId(h.stripHexPrefix(S),h.stripHexPrefix(u)),b=h.ensureHexPrefix(m);if(await this.checkVaultExists(b))throw new Error(`Vault already exists (ID: ${b}, peginTxHash: ${S}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`);const d=this.config.publicClient;let k;try{k=await d.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:R.BTCVaultRegistryABI,functionName:"getPegInFee",args:[o]})}catch(F){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",{cause:F})}const C=await this.resolveMaxAcceptableCommissionBps(o,t.quotedCommissionBps),f=V.encodeFunctionData({abi:R.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[u,y,w,g,A,o,C,r,i,p,c]});let v;try{v=await d.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:f,value:k,account:this.config.ethWallet.account.address})}catch(F){O.handleContractError(F)}let I;try{I=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:f,value:k,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:v})}catch(F){O.handleContractError(F)}const j=await H.waitForTransactionReceiptSmartAware({publicClient:d,walletAddress:this.config.ethWallet.account.address,hash:I,timeout:pe});return j.status==="reverted"&&O.handleContractError(new Error(`Transaction reverted. Hash: ${j.transactionHash}. Check the transaction on block explorer for details.`)),{ethTxHash:j.transactionHash,vaultId:b,peginTxHash:S}}async registerPeginBatchOnChain(t){const{vaultProvider:e,unsignedPrePeginTx:n,requests:o,popSignature:r}=t;if(o.length===0)throw new Error("Batch pegin requires at least one request");if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const i=this.config.ethWallet.account.address;if(!V.isAddressEqual(r.depositorEthAddress,i))throw new Error(`Proof of possession was signed for ${r.depositorEthAddress} but the Ethereum wallet is currently connected to ${i}. Reconnect the original account or call signProofOfPossession() again.`);const a=await this.assertPopMatchesBtcWallet(r),c=r.btcPopSignature,l=o.map(d=>this.resolvePayoutScriptPubKey(a,d.depositorPayoutBtcAddress)),u=[];for(const d of o){const k=h.ensureHexPrefix(d.depositorSignedPeginTx),C=H.calculateBtcTxHash(k),f=await D.deriveVaultId(h.stripHexPrefix(C),h.stripHexPrefix(i)),v=h.ensureHexPrefix(f);if(await this.checkVaultExists(v))throw new Error(`Vault already exists (ID: ${v}, peginTxHash: ${C}). To create a new vault, use different UTXOs or a different amount.`);u.push({vaultId:v,peginTxHash:C})}const P=this.config.publicClient;let w;try{w=await P.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:R.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}catch(d){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",{cause:d})}const y=w*BigInt(o.length),g=await this.resolveMaxAcceptableCommissionBps(e,t.quotedCommissionBps),A=h.ensureHexPrefix(r.depositorBtcPubkey),B=h.ensureHexPrefix(n),p=o.map((d,k)=>({depositorBtcPubKey:A,btcPopSignature:c,unsignedPrePeginTx:B,depositorSignedPeginTx:h.ensureHexPrefix(d.depositorSignedPeginTx),hashlock:d.hashlock,htlcVout:d.htlcVout,referralCode:He,depositorPayoutBtcAddress:l[k],depositorWotsPkHash:d.depositorWotsPkHash})),S=V.encodeFunctionData({abi:R.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[i,e,g,p]});let m;try{m=await P.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:S,value:y,account:this.config.ethWallet.account.address})}catch(d){O.handleContractError(d)}let b;try{b=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:S,value:y,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:m})}catch(d){O.handleContractError(d)}const E=await H.waitForTransactionReceiptSmartAware({publicClient:P,walletAddress:this.config.ethWallet.account.address,hash:b,timeout:pe});return E.status==="reverted"&&O.handleContractError(new Error(`Batch transaction reverted. Hash: ${E.transactionHash}. Check the transaction on block explorer for details.`)),{ethTxHash:E.transactionHash,vaults:u}}async resolveMaxAcceptableCommissionBps(t,e){if(e===void 0&&N.supportsDepositApproval(this.config.btcWallet))throw new Error("quotedCommissionBps is required when the wallet approved deposit terms: the registration ceiling must anchor to the approved quote.");let n;try{n=await new ne.ViemVaultRegistryReader(this.config.publicClient,this.config.vaultContracts.btcVaultRegistry).getVaultProviderCommission(t)}catch(o){throw new Error("Failed to query vault provider commission from the contract. Please check your network connection and that the contract address is correct.",{cause:o})}if(e!==void 0){if(n>e+z)throw new Error(`Vault provider commission changed since quote: quoted ${e} bps, chain currently reports ${n} bps (allowed drift ${z} bps). Please refresh to see the new commission and try again.`);return G(e)}return G(n)}async checkVaultExists(t){return(await this.config.publicClient.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:R.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]})).depositor!==V.zeroAddress}resolvePayoutScriptPubKey(t,e){if(!h.isAddressFromPublicKey(e,t,this.config.btcNetwork))throw h.stripHexPrefix(t).length===h.X_ONLY_PUBKEY_HEX_LEN&&wt(e,this.config.btcNetwork)?new Error(`BTC payout address "${e}" is a P2WPKH (Native SegWit) address, but the connected wallet only exposes an x-only public key. P2WPKH validation requires a compressed key with known y-parity. Use a P2TR (Taproot) payout address instead.`):new Error(`BTC payout address "${e}" is not derived from the connected wallet's public key. The payout sink must be controlled by the same key that signs the pegin; refusing to register a mismatched address.`);const n=h.getNetwork(this.config.btcNetwork);try{return`0x${me.address.toOutputScript(e,n).toString("hex")}`}catch{throw new Error(`Invalid BTC payout address: "${e}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`)}}async signProofOfPossession(){if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const t=this.config.ethWallet.account.address,e=M(await this.config.btcWallet.getPublicKeyHex()),n=this.config.vaultContracts.btcVaultRegistry,o=`${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${n.toLowerCase()}`,r=await this.config.btcWallet.signMessage(o,"bip322-simple");return{btcPopSignature:ze(r),depositorEthAddress:t,depositorBtcPubkey:e}}async assertPopMatchesBtcWallet(t){const e=await this.config.btcWallet.getPublicKeyHex(),n=M(e),o=M(t.depositorBtcPubkey);if(n!==o)throw new Error(`Proof of possession was signed with BTC pubkey ${o} but the BTC wallet is currently connected to ${n}. Reconnect the original wallet or call signProofOfPossession() again.`);return e}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}const Tt=80,Bt=250,Et=300,vt=22,Re="ab";function At(s,t){const e=Re.repeat(Et),n=h.stripHexPrefix(s).toLowerCase(),o=t.toString(16).padStart(8,"0"),r=`${n}${o}`,i=e.slice(r.length);return`0x${r}${i}`}function St(s,t){const e=n=>`0x${Re.repeat(n)}`;return{depositorBtcPubKey:e(32),btcPopSignature:e(Tt),unsignedPrePeginTx:e(Bt),depositorSignedPeginTx:At(s,t),hashlock:e(32),htlcVout:t,referralCode:He,depositorPayoutBtcAddress:e(vt),depositorWotsPkHash:e(32)}}async function _t(s){const{publicClient:t,btcVaultRegistry:e,depositorEthAddress:n,vaultProvider:o,batchSize:r}=s;if(r<=0)throw new Error(`estimateSubmitPeginRequestBatchGas requires batchSize >= 1 (received ${r})`);const a=await t.readContract({address:e,abi:R.BTCVaultRegistryABI,functionName:"getPegInFee",args:[o]})*BigInt(r),c=Array.from({length:r},(u,P)=>St(n,P)),l=V.encodeFunctionData({abi:R.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[n,o,re,c]});return t.estimateGas({to:e,data:l,value:a,account:n})}exports.COMMISSION_BPS_HEADROOM=z;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=re;exports.PeginManager=kt;exports.buildDepositTerms=Pe;exports.capMaxAcceptableCommissionBps=G;exports.computeWotsBlockPublicKeysHash=Ie;exports.deriveWotsBlocksFromSeed=Ce;exports.ensurePrePeginTermsApproval=be;exports.estimateSubmitPeginRequestBatchGas=_t;
|
|
2
|
-
//# sourceMappingURL=PeginManager-
|
|
1
|
+
"use strict";var $e=Object.defineProperty;var Ve=(s,t,e)=>t in s?$e(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e;var T=(s,t,e)=>Ve(s,typeof t!="symbol"?t+"":t,e);const x=require("./sha2-DsrLC4NM.cjs"),W=require("bitcoinjs-lib"),te=require("buffer"),V=require("viem"),R=require("./BTCVaultRegistry.abi-z7d_eP22.cjs"),O=require("./errors-CGcNP0rV.cjs"),D=require("@babylonlabs-io/babylon-tbv-rust-wasm"),$=require("./verifyScriptPathSchnorrSignature-DPAd_qke.cjs"),Y=require("./peginInput-Ci921gTl.cjs"),h=require("./bitcoin-m84N5a8o.cjs"),Me=require("./signing-Bnsro0hE.cjs"),ce=require("./validation-CDbOaDj7.cjs"),se=require("./parseFundingOutpoints-CIO9Ok1L.cjs"),N=require("./signPsbtsWithFallback-PTgWxsG3.cjs"),H=require("./waitForTransactionReceiptSmartAware-AgZ-3WV_.cjs"),le=require("./fundPeginTransaction-BLD8FRL9.cjs"),L=require("./constants-DU5CGcqO.cjs"),ne=require("./mempoolApi-CXfr-L6x.cjs");function Fe(s){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const e in s)if(e!=="default"){const n=Object.getOwnPropertyDescriptor(s,e);Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>s[e]})}}return t.default=s,Object.freeze(t)}const me=Fe(W),X=BigInt(2**32-1),ue=BigInt(32);function Ue(s,t=!1){return t?{h:Number(s&X),l:Number(s>>ue&X)}:{h:Number(s>>ue&X)|0,l:Number(s&X)|0}}function Ne(s,t=!1){const e=s.length;let n=new Uint32Array(e),o=new Uint32Array(e);for(let r=0;r<e;r++){const{h:i,l:a}=Ue(s[r],t);[n[r],o[r]]=[i,a]}return[n,o]}const We=(s,t,e)=>s<<e|t>>>32-e,De=(s,t,e)=>t<<e|s>>>32-e,Le=(s,t,e)=>t<<e-32|s>>>64-e,Xe=(s,t,e)=>s<<e-32|t>>>64-e,qe=64;function Pe(s){const t=s.prepeginTxid.toLowerCase();if(!/^[0-9a-f]+$/.test(t)||t.length!==qe)throw new Error(`buildDepositTerms: prepeginTxid must be 64 hex chars, got "${s.prepeginTxid}"`);if(s.peginAmounts.length===0)throw new Error("buildDepositTerms: at least one pegin amount is required");if(s.timelockPegin<=0||s.timelockAssert<=0||s.timelockRefund<=0)throw new Error("buildDepositTerms: timelocks must be positive");if(!Number.isInteger(s.maxAcceptableCommissionBps)||s.maxAcceptableCommissionBps<0||s.maxAcceptableCommissionBps>=L.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`buildDepositTerms: maxAcceptableCommissionBps must be an integer in [0, ${L.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${s.maxAcceptableCommissionBps}`);const e=BigInt(L.BPS_DENOMINATOR),n=s.peginAmounts.map((o,r)=>({htlcVout:r,vaultProviderBtcPubkey:s.vaultProviderBtcPubkey,peginAmount:o,commissionFee:o*BigInt(s.maxAcceptableCommissionBps)/e,depositorClaimValue:s.depositorClaimValue,peginMaxFee:s.peginMaxFee}));return{vaultCoreVersion:s.vaultCoreVersion,protocolFeeRate:s.protocolFeeRate,timelockPegin:s.timelockPegin,timelockAssert:s.timelockAssert,timelockRefund:s.timelockRefund,prepeginTxid:t,prepeginMaxFee:s.prepeginMaxFee,vaultKeeperBtcPubkeys:[...s.vaultKeeperBtcPubkeys],universalChallengerBtcPubkeys:[...s.universalChallengerBtcPubkeys],vaults:n}}const z=25,re=9999;function G(s){if(!Number.isInteger(s)||s<0||s>=L.MAX_VP_COMMISSION_BPS_EXCLUSIVE)throw new Error(`Quoted commissionBps must be an integer in [0, ${L.MAX_VP_COMMISSION_BPS_EXCLUSIVE}), got ${s}`);return Math.min(s+z,re)}const Ke=/^0x[0-9a-f]+$/i,Ge=/^[0-9a-f]+$/i,ze=/^[A-Za-z0-9+/]+={0,2}$/;function M(s){if(typeof s!="string"||s.length===0)throw new Error("BTC wallet returned empty public key");return h.processPublicKeyToXOnly(s).toLowerCase()}function je(s){if(typeof s!="string"||s.length===0)throw new Error("BTC wallet returned empty BIP-322 signature");if(s.startsWith("0x")||s.startsWith("0X")){if(!Ke.test(s)||s.length<4||s.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return s.toLowerCase()}if(Ge.test(s)){if(s.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return`0x${s.toLowerCase()}`}if(!ze.test(s)||s.length%4!==0)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");const t=te.Buffer.from(s,"base64");if(t.length===0||t.toString("base64")!==s)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");return`0x${t.toString("hex")}`}async function be(s){const{wallet:t,depositTerms:e,fundedPrePeginTxHex:n,depositorBtcPubkey:o}=s,r=typeof t.approveDepositTerms=="function"?t.approveDepositTerms:void 0;if(!r&&!e)return;const i=n.startsWith("0x")?n.slice(2):n,c=W.Transaction.fromHex(i).getId();if(e&&e.prepeginTxid.replace(/^0x/,"").toLowerCase()!==c)throw new Error(`Deposit terms do not match the transaction being broadcast: terms are for prepeginTxid ${e.prepeginTxid}, but this transaction is ${c}.`);if(!r)return;if(!e)throw new Error("This wallet requires approved deposit terms before signing the Pre-PegIn transaction, but none were provided. Pass PreparePeginResult.depositTerms (fresh flows) or a resume rebuild.");if(typeof t.deriveContextHash!="function")throw new Error("A deposit-approval wallet must also implement deriveContextHash, but this one does not.");const l=se.parseFundingOutpointsFromTx(n);(await se.deriveVaultRoot({deriveContextHash:t.deriveContextHash.bind(t)},{depositorBtcPubkey:h.hexToUint8Array(M(o)),fundingOutpoints:l})).fill(0),await r(e)}const Ye=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),xe=Uint8Array.from(new Array(16).fill(0).map((s,t)=>t)),Qe=xe.map(s=>(9*s+5)%16),we=(()=>{const e=[[xe],[Qe]];for(let n=0;n<4;n++)for(let o of e)o.push(o[n].map(r=>Ye[r]));return e})(),ye=we[0],ke=we[1],Te=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map(s=>Uint8Array.from(s)),Ze=ye.map((s,t)=>s.map(e=>Te[t][e])),Je=ke.map((s,t)=>s.map(e=>Te[t][e])),et=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),tt=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function he(s,t,e,n){return s===0?t^e^n:s===1?t&e|~t&n:s===2?(t|~e)^n:s===3?t&n|e&~n:t^(e|~n)}const q=new Uint32Array(16);class st extends x.HashMD{constructor(){super(64,20,8,!0);T(this,"h0",1732584193);T(this,"h1",-271733879);T(this,"h2",-1732584194);T(this,"h3",271733878);T(this,"h4",-1009589776)}get(){const{h0:e,h1:n,h2:o,h3:r,h4:i}=this;return[e,n,o,r,i]}set(e,n,o,r,i){this.h0=e|0,this.h1=n|0,this.h2=o|0,this.h3=r|0,this.h4=i|0}process(e,n){for(let g=0;g<16;g++,n+=4)q[g]=e.getUint32(n,!0);let o=this.h0|0,r=o,i=this.h1|0,a=i,c=this.h2|0,l=c,u=this.h3|0,P=u,w=this.h4|0,y=w;for(let g=0;g<5;g++){const A=4-g,B=et[g],p=tt[g],S=ye[g],m=ke[g],b=Ze[g],E=Je[g];for(let d=0;d<16;d++){const k=x.rotl(o+he(g,i,c,u)+q[S[d]]+B,b[d])+w|0;o=w,w=u,u=x.rotl(c,10)|0,c=i,i=k}for(let d=0;d<16;d++){const k=x.rotl(r+he(A,a,l,P)+q[m[d]]+p,E[d])+y|0;r=y,y=P,P=x.rotl(l,10)|0,l=a,a=k}}this.set(this.h1+c+P|0,this.h2+u+y|0,this.h3+w+r|0,this.h4+o+a|0,this.h0+i+l|0)}roundClean(){x.clean(q)}destroy(){this.destroyed=!0,x.clean(this.buffer),this.set(0,0,0,0,0)}}const nt=x.createHasher(()=>new st),ot=BigInt(0),U=BigInt(1),rt=BigInt(2),it=BigInt(7),at=BigInt(256),ct=BigInt(113),Be=[],Ee=[],ve=[];for(let s=0,t=U,e=1,n=0;s<24;s++){[e,n]=[n,(2*e+3*n)%5],Be.push(2*(5*n+e)),Ee.push((s+1)*(s+2)/2%64);let o=ot;for(let r=0;r<7;r++)t=(t<<U^(t>>it)*ct)%at,t&rt&&(o^=U<<(U<<BigInt(r))-U);ve.push(o)}const Ae=Ne(ve,!0),lt=Ae[0],ut=Ae[1],de=(s,t,e)=>e>32?Le(s,t,e):We(s,t,e),ge=(s,t,e)=>e>32?Xe(s,t,e):De(s,t,e);function ht(s,t=24){const e=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let i=0;i<10;i++)e[i]=s[i]^s[i+10]^s[i+20]^s[i+30]^s[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,l=e[c],u=e[c+1],P=de(l,u,1)^e[a],w=ge(l,u,1)^e[a+1];for(let y=0;y<50;y+=10)s[i+y]^=P,s[i+y+1]^=w}let o=s[2],r=s[3];for(let i=0;i<24;i++){const a=Ee[i],c=de(o,r,a),l=ge(o,r,a),u=Be[i];o=s[u],r=s[u+1],s[u]=c,s[u+1]=l}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)e[a]=s[i+a];for(let a=0;a<10;a++)s[i+a]^=~e[(a+2)%10]&e[(a+4)%10]}s[0]^=lt[n],s[1]^=ut[n]}x.clean(e)}class ie{constructor(t,e,n,o=!1,r=24){T(this,"state");T(this,"pos",0);T(this,"posOut",0);T(this,"finished",!1);T(this,"state32");T(this,"destroyed",!1);T(this,"blockLen");T(this,"suffix");T(this,"outputLen");T(this,"enableXOF",!1);T(this,"rounds");if(this.blockLen=t,this.suffix=e,this.outputLen=n,this.enableXOF=o,this.rounds=r,x.anumber(n,"outputLen"),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=x.u32(this.state)}clone(){return this._cloneInto()}keccak(){x.swap32IfBE(this.state32),ht(this.state32,this.rounds),x.swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(t){x.aexists(this),x.abytes(t);const{blockLen:e,state:n}=this,o=t.length;for(let r=0;r<o;){const i=Math.min(e-this.pos,o-r);for(let a=0;a<i;a++)n[this.pos++]^=t[r++];this.pos===e&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:e,pos:n,blockLen:o}=this;t[n]^=e,(e&128)!==0&&n===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){x.aexists(this,!1),x.abytes(t),this.finish();const e=this.state,{blockLen:n}=this;for(let o=0,r=t.length;o<r;){this.posOut>=n&&this.keccak();const i=Math.min(n-this.posOut,r-o);t.set(e.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return x.anumber(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(x.aoutput(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,x.clean(this.state)}_cloneInto(t){const{blockLen:e,suffix:n,outputLen:o,rounds:r,enableXOF:i}=this;return t||(t=new ie(e,n,o,i,r)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=r,t.suffix=n,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}}const dt=(s,t,e,n={})=>x.createHasher(()=>new ie(t,s,e),n),gt=dt(1,136,32),fe=64,_=20,oe=4,Se=2,ft=0,pt=1,K=[64,64],mt=s=>Array.from(s).map(t=>t.toString(16).padStart(2,"0")).join("");function ae(s){return nt(x.sha256(s))}function _e(s){return(1<<s)-1}function Pt(s){let t=1;for(;t*t<s+1;)t++;return Math.max(t,2)}function bt(s){const t=oe,e=s*_e(t);return{d:t,n:s,checksum_radix:Pt(e)}}function Q(s,t){const e=[];let n=t;for(;n>0;)e.push(n&255),n>>>=8;const o=new Uint8Array(s.length+e.length);o.set(s);for(let r=0;r<e.length;r++)o[s.length+r]=e[r];return ae(o)}function Z(s,t){let e=s;for(let n=0;n<t;n++)e=ae(e);return e}function xt(s,t){const e=_e(t.d),n=t.checksum_radix-1,o=Math.floor(t.n*e/t.checksum_radix),r=[];for(let u=0;u<t.n;u++){const P=Q(s,u+Se),w=Z(P,e);r.push(Array.from(w))}const i=Q(s,ft),a=Z(i,n),c=Q(s,pt),l=Z(c,o);return{config:t,message_terminals:r,checksum_major_terminal:Array.from(l),checksum_minor_terminal:Array.from(a)}}async function Ce(s){try{if(s.length!==fe)throw new Error(`WOTS seed must be exactly ${fe} bytes, got ${s.length}`);const t=[];for(let e=0;e<K.length;e++){const n=K[e],o=bt(n),r=new Uint8Array(s.length+1);r.set(s),r[s.length]=e;const i=ae(r);try{const a=xt(i,o);if(a.config.d!==oe)throw new Error(`Block ${e}: expected d=${oe}, got d=${a.config.d}`);if(a.config.n!==n)throw new Error(`Block ${e}: expected n=${n}, got n=${a.config.n}`);if(a.message_terminals.length!==n)throw new Error(`Block ${e}: expected ${n} message terminals, got ${a.message_terminals.length}`);for(let c=0;c<a.message_terminals.length;c++)if(a.message_terminals[c].length!==_)throw new Error(`Block ${e} terminal ${c}: expected ${_} bytes, got ${a.message_terminals[c].length}`);if(a.checksum_minor_terminal.length!==_)throw new Error(`Block ${e} checksum_minor: expected ${_} bytes`);if(a.checksum_major_terminal.length!==_)throw new Error(`Block ${e} checksum_major: expected ${_} bytes`);t.push(a)}finally{r.fill(0),i.fill(0)}}if(t.length!==K.length)throw new Error(`Expected ${K.length} blocks, got ${t.length}`);return t}finally{s.fill(0)}}function J(s,t,e){if(s.length!==_)throw new Error(`Block ${t} ${e}: expected ${_} bytes, got ${s.length}`);for(let n=0;n<s.length;n++){const o=s[n];if(!Number.isInteger(o)||o<0||o>255)throw new Error(`Block ${t} ${e}[${n}]: invalid byte value ${o}`)}}function Ie(s){if(s.length===0)throw new Error("Public keys array must not be empty");for(let r=0;r<s.length;r++){const i=s[r];J(i.checksum_minor_terminal,r,"checksum_minor_terminal"),J(i.checksum_major_terminal,r,"checksum_major_terminal");for(let a=0;a<i.message_terminals.length;a++)J(i.message_terminals[a],r,`message_terminal[${a}]`)}let t=0;for(const r of s)t+=Se+r.message_terminals.length;const e=new Uint8Array(t*_);let n=0;for(const r of s){e.set(r.checksum_minor_terminal,n),n+=_,e.set(r.checksum_major_terminal,n),n+=_;for(const i of r.message_terminals)e.set(i,n),n+=_}const o=gt(e);return`0x${mt(o)}`}async function He(s,t){const e=[],n=[],o=[],r=[];try{for(let i=0;i<t;i++){const a=await D.expandWotsSeed(s,i);try{const l=await Ce(a);e.push(l),n.push(Ie(l))}finally{a.fill(0)}const c=await D.expandHashlockSecret(s,i);try{const l=h.uint8ArrayToHex(c);o.push(l),r.push(N.computeHashlock(h.ensureHexPrefix(l)).slice(2))}finally{c.fill(0)}}}finally{s.fill(0)}return{perVaultWotsKeys:e,wotsPkHashes:n,htlcSecretHexes:o,hashlocks:r}}const Re=0,ee="00".repeat(32);function wt(s,t){const e={bitcoin:"bc",testnet:"tb",signet:"tb",regtest:"bcrt"};try{const n=me.address.fromBech32(s);return n.prefix===e[t]&&n.version===0&&n.data.length===20}catch{return!1}}function yt(s,t,e,n){const o=e==null?void 0:e[`${s}:${t}`];return o?Promise.resolve({txid:s,vout:t,value:o.value,scriptPubKey:o.scriptPubKey}):ne.getUtxoInfo(s,t,n)}const pe=12e4;class kt{constructor(t){T(this,"config");this.config=t}async preparePegin(t){if(t.amounts.length===0)throw new Error("amounts must contain at least one entry");const e=await this.config.btcWallet.getPublicKeyHex(),n=M(e);if(!h.isAddressFromPublicKey(t.changeAddress,e,this.config.btcNetwork))throw new Error(`Pre-PegIn changeAddress "${t.changeAddress}" is not derived from the connected wallet's public key. Refusing to build a tx that would send change to an address the signing key doesn't control.`);const o=await this.prepareSizing(n,t),r=o.selectedUTXOs.map(p=>({txid:h.hexToUint8Array(p.txid),vout:p.vout})),i=await se.deriveVaultRoot(this.config.btcWallet,{depositorBtcPubkey:h.hexToUint8Array(n),fundingOutpoints:r});let a,c;try{const p=await D.expandAuthAnchor(i);try{a=h.uint8ArrayToHex(p),c=h.uint8ArrayToHex(x.sha256(p))}finally{p.fill(0)}}catch(p){throw i.fill(0),p}const l=await He(i,t.amounts.length),{perVaultWotsKeys:u,wotsPkHashes:P,htlcSecretHexes:w,hashlocks:y}=l,g=await this.preparePeginCommit({depositorBtcPubkeyRaw:e,depositorBtcPubkey:n,hashlocks:y,authAnchorHash:c,sizing:o,params:t});for(let p=0;p<g.perVault.length;p++)if(g.perVault[p].htlcVout!==p)throw new Error(`Internal invariant violation: htlcVout/index mismatch at vault ${p} (expected ${p}, got ${g.perVault[p].htlcVout})`);N.assertAuthAnchorOpReturn(g.fundedPrePeginTxHex,t.amounts.length,c);const{depositTerms:A,...B}=g;return{transaction:{...B,selectedUTXOs:o.selectedUTXOs,fee:o.fee,changeAmount:o.changeAmount},depositorBtcPubkey:n,derivedSecrets:{perVaultWotsKeys:u,wotsPkHashes:P,htlcSecretHexes:w,authAnchorHex:a},depositTerms:A}}async prepareSizing(t,e){const n=e.amounts.map(()=>ee),o=e.vaultKeeperBtcPubkeys.length,r=await $.buildPrePeginPsbt({vaultCoreVersion:e.vaultCoreVersion,depositorPubkey:t,vaultProviderPubkey:h.stripHexPrefix(e.vaultProviderBtcPubkey),vaultKeeperPubkeys:e.vaultKeeperBtcPubkeys.map(h.stripHexPrefix),universalChallengerPubkeys:e.universalChallengerBtcPubkeys.map(h.stripHexPrefix),hashlocks:n,timelockRefund:e.timelockRefund,pegInAmounts:e.amounts,feeRate:e.protocolFeeRate,minPeginFeeRate:e.minPeginFeeRate,numLocalChallengers:o,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:this.config.btcNetwork,authAnchorHash:ee}),i=H.selectUtxosForPegin([...e.availableUTXOs],r.totalOutputValue,e.mempoolFeeRate,le.peginOutputCount(r.htlcValues.length,!0));return{selectedUTXOs:i.selectedUTXOs,fee:i.fee,changeAmount:i.changeAmount}}async preparePeginCommit(t){const{depositorBtcPubkeyRaw:e,depositorBtcPubkey:n,hashlocks:o,authAnchorHash:r,sizing:i,params:a}=t,c=ee.toLowerCase();for(let f=0;f<o.length;f++)if(o[f].toLowerCase()===c)throw new Error(`preparePeginCommit refusing to build with sizing-pass placeholder hashlock at vault ${f} — internal substitution bug`);if(r.toLowerCase()===c)throw new Error("preparePeginCommit refusing to build with sizing-pass placeholder auth-anchor hash — internal substitution bug");const l=h.stripHexPrefix(a.vaultProviderBtcPubkey),u=a.vaultKeeperBtcPubkeys.map(h.stripHexPrefix),P=a.universalChallengerBtcPubkeys.map(h.stripHexPrefix),w=u.length,y={vaultCoreVersion:a.vaultCoreVersion,depositorPubkey:n,vaultProviderPubkey:l,vaultKeeperPubkeys:u,universalChallengerPubkeys:P,hashlocks:o,timelockRefund:a.timelockRefund,pegInAmounts:a.amounts,feeRate:a.protocolFeeRate,minPeginFeeRate:a.minPeginFeeRate,numLocalChallengers:w,councilQuorum:a.councilQuorum,councilSize:a.councilSize,network:this.config.btcNetwork,authAnchorHash:r},g=await $.buildPrePeginPsbt(y),A=h.getNetwork(this.config.btcNetwork),B=le.fundPeginTransaction({unfundedTxHex:g.psbtHex,selectedUTXOs:i.selectedUTXOs,changeAddress:a.changeAddress,changeAmount:i.changeAmount,network:A}),p=i.selectedUTXOs.reduce((f,v)=>f+BigInt(v.value),0n)-g.totalOutputValue-i.changeAmount;if(p!==i.fee)throw new Error(`Pre-PegIn funded fee ${p} does not match the sizing-pass fee ${i.fee}; refusing to publish a deposit-terms fee bound the funded transaction does not pay.`);const S=h.stripHexPrefix(H.calculateBtcTxHash(B)),m=[],b=[],E=[];for(let f=0;f<o.length;f++){const v=await $.buildPeginTxFromFundedPrePegin({prePeginParams:y,timelockPegin:a.timelockPegin,fundedPrePeginTxHex:B,htlcVout:f}),I=await Y.buildPeginInputPsbt({vaultCoreVersion:a.vaultCoreVersion,peginTxHex:v.txHex,fundedPrePeginTxHex:B,depositorPubkey:n,vaultProviderPubkey:l,vaultKeeperPubkeys:u,universalChallengerPubkeys:P,hashlock:o[f],timelockRefund:a.timelockRefund,network:this.config.btcNetwork});m.push(v),b.push(I.psbtHex),E.push(Me.createTaprootScriptPathSignOptions(e,1))}const d=Pe({vaultCoreVersion:a.vaultCoreVersion,protocolFeeRate:a.protocolFeeRate,timelockPegin:a.timelockPegin,timelockAssert:a.timelockAssert,timelockRefund:a.timelockRefund,prepeginTxid:S,prepeginMaxFee:i.fee,vaultProviderBtcPubkey:l,vaultKeeperBtcPubkeys:u,universalChallengerBtcPubkeys:P,maxAcceptableCommissionBps:G(a.commissionBps),peginAmounts:a.amounts,depositorClaimValue:g.depositorClaimValue,peginMaxFee:g.minPeginFee});N.supportsDepositApproval(this.config.btcWallet)&&await this.config.btcWallet.approveDepositTerms(d);const k=await N.signPsbtsWithFallback(this.config.btcWallet,b,E),C=[];for(let f=0;f<k.length;f++){$.assertPsbtUnsignedTxMatches({requestedPsbtHex:b[f],returnedPsbtHex:k[f]});const v=Y.extractPeginInputSignature(k[f],n);$.assertScriptPathSchnorrSignature({requestedPsbtHex:b[f],signatureHex:v,signerXOnlyPubkeyHex:n,inputIndex:0});const I=Y.finalizePeginInputPsbt(k[f]);C.push({htlcVout:f,htlcValue:g.htlcValues[f],peginTxHex:I,peginTxid:m[f].txid,peginInputSignature:v,vaultScriptPubKey:m[f].vaultScriptPubKey})}return{fundedPrePeginTxHex:B,prePeginTxid:S,perVault:C,depositTerms:d}}async signAndBroadcast(t){const{fundedPrePeginTxHex:e,depositorBtcPubkey:n}=t,o=e.startsWith("0x")?e.slice(2):e,r=W.Transaction.fromHex(o);if(r.ins.length===0)throw new Error("Transaction has no inputs");const i=new W.Psbt;i.setVersion(r.version),i.setLocktime(r.locktime);const a=te.Buffer.from(M(n),"hex"),c=this.config.mempoolApiUrl,l=r.ins.map(m=>{const b=te.Buffer.from(m.hash).reverse().toString("hex"),E=m.index;return yt(b,E,t.localPrevouts,c).then(d=>({input:m,utxoData:d,txid:b,vout:E}))}),u=await Promise.all(l),P=u.reduce((m,b)=>m+BigInt(b.utxoData.value),0n),w=r.outs.reduce((m,b)=>m+BigInt(b.value),0n);if(P<w)throw new Error(`UTXO value mismatch: total input value (${P} sat) is less than total output value (${w} sat). This may indicate the mempool API returned manipulated UTXO data.`);const y=P-w;if(y>ce.MAX_REASONABLE_FEE_SATS)throw new Error(`Implied transaction fee (${y} sat) exceeds maximum reasonable fee (${ce.MAX_REASONABLE_FEE_SATS} sat). This may indicate manipulated UTXO data.`);for(const{input:m,utxoData:b,txid:E,vout:d}of u){const k=H.getPsbtInputFields({value:b.value,scriptPubKey:b.scriptPubKey},a);i.addInput({hash:m.hash,index:m.index,sequence:m.sequence,...k})}for(const m of r.outs)i.addOutput({script:m.script,value:m.value});await be({wallet:this.config.btcWallet,depositTerms:t.depositTerms,fundedPrePeginTxHex:e,depositorBtcPubkey:n});const g=i.toHex(),A=await this.config.btcWallet.signPsbt(g);$.assertPsbtUnsignedTxMatches({requestedPsbtHex:g,returnedPsbtHex:A});const B=W.Psbt.fromHex(A);try{B.finalizeAllInputs()}catch(m){if(!B.data.inputs.every(E=>E.finalScriptWitness||E.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${m}`)}const p=B.extractTransaction().toHex();return await ne.pushTx(p,c)}async registerPeginOnChain(t){const{unsignedPrePeginTx:e,depositorSignedPeginTx:n,vaultProvider:o,hashlock:r,htlcVout:i,depositorPayoutBtcAddress:a,depositorWotsPkHash:c,popSignature:l}=t;if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const u=this.config.ethWallet.account.address;if(!V.isAddressEqual(l.depositorEthAddress,u))throw new Error(`Proof of possession was signed for ${l.depositorEthAddress} but the Ethereum wallet is currently connected to ${u}. Reconnect the original account or call signProofOfPossession() again.`);const P=await this.assertPopMatchesBtcWallet(l),w=l.btcPopSignature,y=h.ensureHexPrefix(l.depositorBtcPubkey),g=h.ensureHexPrefix(e),A=h.ensureHexPrefix(n),B=a??await this.config.btcWallet.getAddress(),p=this.resolvePayoutScriptPubKey(P,B),S=H.calculateBtcTxHash(A),m=await D.deriveVaultId(h.stripHexPrefix(S),h.stripHexPrefix(u)),b=h.ensureHexPrefix(m);if(await this.checkVaultExists(b))throw new Error(`Vault already exists (ID: ${b}, peginTxHash: ${S}). Vault IDs are derived from the pegin transaction hash and depositor address. To create a new vault, use different UTXOs or a different amount to generate a unique transaction.`);const d=this.config.publicClient;let k;try{k=await d.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:R.BTCVaultRegistryABI,functionName:"getPegInFee",args:[o]})}catch(F){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",{cause:F})}const C=await this.resolveMaxAcceptableCommissionBps(o,t.quotedCommissionBps),f=V.encodeFunctionData({abi:R.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[u,y,w,g,A,o,C,r,i,p,c]});let v;try{v=await d.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:f,value:k,account:this.config.ethWallet.account.address})}catch(F){O.handleContractError(F)}let I;try{I=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:f,value:k,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:v})}catch(F){O.handleContractError(F)}const j=await H.waitForTransactionReceiptSmartAware({publicClient:d,walletAddress:this.config.ethWallet.account.address,hash:I,timeout:pe});return j.status==="reverted"&&O.handleContractError(new Error(`Transaction reverted. Hash: ${j.transactionHash}. Check the transaction on block explorer for details.`)),{ethTxHash:j.transactionHash,vaultId:b,peginTxHash:S}}async registerPeginBatchOnChain(t){const{vaultProvider:e,unsignedPrePeginTx:n,requests:o,popSignature:r}=t;if(o.length===0)throw new Error("Batch pegin requires at least one request");if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const i=this.config.ethWallet.account.address;if(!V.isAddressEqual(r.depositorEthAddress,i))throw new Error(`Proof of possession was signed for ${r.depositorEthAddress} but the Ethereum wallet is currently connected to ${i}. Reconnect the original account or call signProofOfPossession() again.`);const a=await this.assertPopMatchesBtcWallet(r),c=r.btcPopSignature,l=o.map(d=>this.resolvePayoutScriptPubKey(a,d.depositorPayoutBtcAddress)),u=[];for(const d of o){const k=h.ensureHexPrefix(d.depositorSignedPeginTx),C=H.calculateBtcTxHash(k),f=await D.deriveVaultId(h.stripHexPrefix(C),h.stripHexPrefix(i)),v=h.ensureHexPrefix(f);if(await this.checkVaultExists(v))throw new Error(`Vault already exists (ID: ${v}, peginTxHash: ${C}). To create a new vault, use different UTXOs or a different amount.`);u.push({vaultId:v,peginTxHash:C})}const P=this.config.publicClient;let w;try{w=await P.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:R.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}catch(d){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",{cause:d})}const y=w*BigInt(o.length),g=await this.resolveMaxAcceptableCommissionBps(e,t.quotedCommissionBps),A=h.ensureHexPrefix(r.depositorBtcPubkey),B=h.ensureHexPrefix(n),p=o.map((d,k)=>({depositorBtcPubKey:A,btcPopSignature:c,unsignedPrePeginTx:B,depositorSignedPeginTx:h.ensureHexPrefix(d.depositorSignedPeginTx),hashlock:d.hashlock,htlcVout:d.htlcVout,referralCode:Re,depositorPayoutBtcAddress:l[k],depositorWotsPkHash:d.depositorWotsPkHash})),S=V.encodeFunctionData({abi:R.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[i,e,g,p]});let m;try{m=await P.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:S,value:y,account:this.config.ethWallet.account.address})}catch(d){O.handleContractError(d)}let b;try{b=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:S,value:y,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:m})}catch(d){O.handleContractError(d)}const E=await H.waitForTransactionReceiptSmartAware({publicClient:P,walletAddress:this.config.ethWallet.account.address,hash:b,timeout:pe});return E.status==="reverted"&&O.handleContractError(new Error(`Batch transaction reverted. Hash: ${E.transactionHash}. Check the transaction on block explorer for details.`)),{ethTxHash:E.transactionHash,vaults:u}}async resolveMaxAcceptableCommissionBps(t,e){if(e===void 0&&N.supportsDepositApproval(this.config.btcWallet))throw new Error("quotedCommissionBps is required when the wallet approved deposit terms: the registration ceiling must anchor to the approved quote.");let n;try{n=await new ne.ViemVaultRegistryReader(this.config.publicClient,this.config.vaultContracts.btcVaultRegistry).getVaultProviderCommission(t)}catch(o){throw new Error("Failed to query vault provider commission from the contract. Please check your network connection and that the contract address is correct.",{cause:o})}if(e!==void 0){if(n>e+z)throw new Error(`Vault provider commission changed since quote: quoted ${e} bps, chain currently reports ${n} bps (allowed drift ${z} bps). Please refresh to see the new commission and try again.`);return G(e)}return G(n)}async checkVaultExists(t){return(await this.config.publicClient.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:R.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]})).depositor!==V.zeroAddress}resolvePayoutScriptPubKey(t,e){if(!h.isAddressFromPublicKey(e,t,this.config.btcNetwork))throw h.stripHexPrefix(t).length===h.X_ONLY_PUBKEY_HEX_LEN&&wt(e,this.config.btcNetwork)?new Error(`BTC payout address "${e}" is a P2WPKH (Native SegWit) address, but the connected wallet only exposes an x-only public key. P2WPKH validation requires a compressed key with known y-parity. Use a P2TR (Taproot) payout address instead.`):new Error(`BTC payout address "${e}" is not derived from the connected wallet's public key. The payout sink must be controlled by the same key that signs the pegin; refusing to register a mismatched address.`);const n=h.getNetwork(this.config.btcNetwork);try{return`0x${me.address.toOutputScript(e,n).toString("hex")}`}catch{throw new Error(`Invalid BTC payout address: "${e}". Please provide a valid Bitcoin address for the ${this.config.btcNetwork} network.`)}}async signProofOfPossession(){if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const t=this.config.ethWallet.account.address,e=M(await this.config.btcWallet.getPublicKeyHex()),n=this.config.vaultContracts.btcVaultRegistry,o=`${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${n.toLowerCase()}`,r=await this.config.btcWallet.signMessage(o,"bip322-simple");return{btcPopSignature:je(r),depositorEthAddress:t,depositorBtcPubkey:e}}async assertPopMatchesBtcWallet(t){const e=await this.config.btcWallet.getPublicKeyHex(),n=M(e),o=M(t.depositorBtcPubkey);if(n!==o)throw new Error(`Proof of possession was signed with BTC pubkey ${o} but the BTC wallet is currently connected to ${n}. Reconnect the original wallet or call signProofOfPossession() again.`);return e}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}const Tt=80,Bt=250,Et=300,vt=22,Oe="ab";function At(s,t){const e=Oe.repeat(Et),n=h.stripHexPrefix(s).toLowerCase(),o=t.toString(16).padStart(8,"0"),r=`${n}${o}`,i=e.slice(r.length);return`0x${r}${i}`}function St(s,t){const e=n=>`0x${Oe.repeat(n)}`;return{depositorBtcPubKey:e(32),btcPopSignature:e(Tt),unsignedPrePeginTx:e(Bt),depositorSignedPeginTx:At(s,t),hashlock:e(32),htlcVout:t,referralCode:Re,depositorPayoutBtcAddress:e(vt),depositorWotsPkHash:e(32)}}async function _t(s){const{publicClient:t,btcVaultRegistry:e,depositorEthAddress:n,vaultProvider:o,batchSize:r}=s;if(r<=0)throw new Error(`estimateSubmitPeginRequestBatchGas requires batchSize >= 1 (received ${r})`);const a=await t.readContract({address:e,abi:R.BTCVaultRegistryABI,functionName:"getPegInFee",args:[o]})*BigInt(r),c=Array.from({length:r},(u,P)=>St(n,P)),l=V.encodeFunctionData({abi:R.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[n,o,re,c]});return t.estimateGas({to:e,data:l,value:a,account:n})}exports.COMMISSION_BPS_HEADROOM=z;exports.MAX_ACCEPTABLE_COMMISSION_BPS_CAP=re;exports.PeginManager=kt;exports.buildDepositTerms=Pe;exports.capMaxAcceptableCommissionBps=G;exports.computeWotsBlockPublicKeysHash=Ie;exports.deriveWotsBlocksFromSeed=Ce;exports.ensurePrePeginTermsApproval=be;exports.estimateSubmitPeginRequestBatchGas=_t;exports.expandPerVaultSecrets=He;
|
|
2
|
+
//# sourceMappingURL=PeginManager-p-ajwSxG.cjs.map
|