@babylonlabs-io/ts-sdk 0.36.1 → 0.36.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. package/dist/PeginManager-BPXVXu8t.cjs +2 -0
  2. package/dist/{PeginManager-cPQuJTB9.cjs.map → PeginManager-BPXVXu8t.cjs.map} +1 -1
  3. package/dist/{PeginManager-DF1oinIQ.js → PeginManager-CB-dVkT2.js} +387 -369
  4. package/dist/{PeginManager-DF1oinIQ.js.map → PeginManager-CB-dVkT2.js.map} +1 -1
  5. package/dist/{buildAndBroadcastRefund-D4YqqClN.js → buildAndBroadcastRefund-C2VqXiOx.js} +241 -220
  6. package/dist/buildAndBroadcastRefund-C2VqXiOx.js.map +1 -0
  7. package/dist/buildAndBroadcastRefund-CBIfcF47.cjs +2 -0
  8. package/dist/buildAndBroadcastRefund-CBIfcF47.cjs.map +1 -0
  9. package/dist/index.cjs +1 -1
  10. package/dist/index.js +2 -2
  11. package/dist/tbv/core/index.cjs +1 -1
  12. package/dist/tbv/core/index.js +2 -2
  13. package/dist/tbv/core/managers/PeginManager.d.ts +22 -4
  14. package/dist/tbv/core/managers/PeginManager.d.ts.map +1 -1
  15. package/dist/tbv/core/managers/index.cjs +1 -1
  16. package/dist/tbv/core/managers/index.js +1 -1
  17. package/dist/tbv/core/services/deposit/signDepositorGraph.d.ts.map +1 -1
  18. package/dist/tbv/core/services/index.cjs +1 -1
  19. package/dist/tbv/core/services/index.js +1 -1
  20. package/dist/tbv/core/vault-secrets/index.d.ts +1 -0
  21. package/dist/tbv/core/vault-secrets/index.d.ts.map +1 -1
  22. package/dist/tbv/index.cjs +1 -1
  23. package/dist/tbv/index.js +2 -2
  24. package/package.json +1 -1
  25. package/dist/PeginManager-cPQuJTB9.cjs +0 -2
  26. package/dist/buildAndBroadcastRefund-D4YqqClN.js.map +0 -1
  27. package/dist/buildAndBroadcastRefund-DSELaUiR.cjs +0 -2
  28. package/dist/buildAndBroadcastRefund-DSELaUiR.cjs.map +0 -1
@@ -0,0 +1,2 @@
1
+ "use strict";var Ut=Object.defineProperty;var Vt=(n,t,e)=>t in n?Ut(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var T=(n,t,e)=>Vt(n,typeof t!="symbol"?t+"":t,e);const P=require("./sha2-DsrLC4NM.cjs"),K=require("bitcoinjs-lib"),Y=require("buffer"),C=require("viem"),$=require("./BTCVaultRegistry.abi-ZdPpION2.cjs"),H=require("./errors-BP73_stm.cjs"),L=require("@babylonlabs-io/babylon-tbv-rust-wasm"),R=require("./peginInput-tbw9BpZy.cjs"),u=require("./bitcoin-B3aqjuMP.cjs"),Nt=require("./signing-Bnsro0hE.cjs"),st=require("./validation-u8W7Lp2x.cjs"),Lt=require("./PayoutManager-BhJoQZsG.cjs"),S=require("./waitForTransactionReceiptSmartAware-D9ykVriz.cjs"),ot=require("./fundPeginTransaction-DaWoYCgO.cjs"),pt=require("./mempoolApi-YNkKjQCU.cjs");function Wt(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const r=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,r.get?r:{enumerable:!0,get:()=>n[e]})}}return t.default=n,Object.freeze(t)}const mt=Wt(K),W=BigInt(2**32-1),it=BigInt(32);function Ft(n,t=!1){return t?{h:Number(n&W),l:Number(n>>it&W)}:{h:Number(n>>it&W)|0,l:Number(n&W)|0}}function Mt(n,t=!1){const e=n.length;let r=new Uint32Array(e),s=new Uint32Array(e);for(let o=0;o<e;o++){const{h:i,l:a}=Ft(n[o],t);[r[o],s[o]]=[i,a]}return[r,s]}const Xt=(n,t,e)=>n<<e|t>>>32-e,Kt=(n,t,e)=>t<<e|n>>>32-e,Dt=(n,t,e)=>t<<e-32|n>>>64-e,qt=(n,t,e)=>n<<e-32|t>>>64-e,zt=106,jt=32,at=34;function Gt(n,t,e){const r=u.stripHexPrefix(n),s=mt.Transaction.fromHex(r);if(s.outs.length<=t)throw new Error(`Pre-PegIn auth-anchor OP_RETURN missing: tx has ${s.outs.length} outputs, expected at least ${t+1} (vault outputs + OP_RETURN)`);const o=s.outs[t],i=o.script;if(i.length!==at||i[0]!==zt||i[1]!==jt)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${t} has unexpected script encoding (got ${i.length}-byte script with prefix 0x${i.slice(0,Math.min(2,i.length)).toString("hex")}; expected ${at}-byte OP_RETURN + PUSH32 layout)`);const a=i.slice(2).toString("hex").toLowerCase();if(a!==e.toLowerCase())throw new Error(`Pre-PegIn auth-anchor OP_RETURN payload mismatch at vout ${t}: tx pushes ${a}, expected ${e}`);if(o.value!==0)throw new Error(`Pre-PegIn auth-anchor OP_RETURN at vout ${t} has non-zero value ${o.value}; OP_RETURN outputs must be 0-value`)}const N=32,j=32,J=36,Pt=32,D=4,Zt=D+N+D+Pt;function tt(n,t,e){n[t]=e>>>24&255,n[t+1]=e>>>16&255,n[t+2]=e>>>8&255,n[t+3]=e&255}function Qt(n){if(n.txid.length!==j)throw new Error(`outpoint.txid must be exactly ${j} bytes, got ${n.txid.length}`);if(!Number.isInteger(n.vout)||n.vout<0||n.vout>4294967295)throw new Error(`outpoint.vout must be a u32, got ${n.vout}`);const t=new Uint8Array(J);return t.set(n.txid,0),tt(t,j,n.vout),t}function ct(n,t){const e=Math.min(n.length,t.length);for(let r=0;r<e;r++)if(n[r]!==t[r])return n[r]-t[r];return n.length-t.length}function xt(n){if(n.length===0)throw new Error("buildFundingOutpointsCommitment: outpoints must be non-empty");const t=n.map(Qt);t.sort(ct);for(let r=1;r<t.length;r++)if(ct(t[r-1],t[r])===0)throw new Error("buildFundingOutpointsCommitment: duplicate outpoint detected");const e=new Uint8Array(t.length*J);for(let r=0;r<t.length;r++)e.set(t[r],r*J);return P.sha256(e)}function wt(n){if(n.depositorBtcPubkey.length!==N)throw new Error(`vaultContext: depositorBtcPubkey must be exactly ${N} bytes, got ${n.depositorBtcPubkey.length}`);const t=xt(n.fundingOutpoints),e=new Uint8Array(Zt);let r=0;return tt(e,r,N),r+=D,e.set(n.depositorBtcPubkey,r),r+=N,tt(e,r,Pt),r+=D,e.set(t,r),e}const bt="babylon-btc-vault",yt=32,lt=yt*2,Yt=/^[0-9a-f]+$/;async function kt(n,t){const e=wt(t),r=u.uint8ArrayToHex(e),s=await n.deriveContextHash(bt,r);if(typeof s!="string")throw new Error(`deriveVaultRoot: wallet must return a string, got ${typeof s}`);if(s.length!==lt)throw new Error(`deriveVaultRoot: wallet must return a ${lt}-character hex string (${yt} bytes), got length ${s.length}`);if(!Yt.test(s))throw new Error("deriveVaultRoot: wallet must return lowercase hex per derive-context-hash.md §2.1; got value with non-lowercase or non-hex characters");return u.hexToUint8Array(s)}const Jt=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Et=Uint8Array.from(new Array(16).fill(0).map((n,t)=>t)),te=Et.map(n=>(9*n+5)%16),Tt=(()=>{const e=[[Et],[te]];for(let r=0;r<4;r++)for(let s of e)s.push(s[r].map(o=>Jt[o]));return e})(),_t=Tt[0],Bt=Tt[1],vt=[[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(n=>Uint8Array.from(n)),ee=_t.map((n,t)=>n.map(e=>vt[t][e])),ne=Bt.map((n,t)=>n.map(e=>vt[t][e])),re=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),se=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function ut(n,t,e,r){return n===0?t^e^r:n===1?t&e|~t&r:n===2?(t|~e)^r:n===3?t&r|e&~r:t^(e|~r)}const F=new Uint32Array(16);class oe extends P.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:r,h2:s,h3:o,h4:i}=this;return[e,r,s,o,i]}set(e,r,s,o,i){this.h0=e|0,this.h1=r|0,this.h2=s|0,this.h3=o|0,this.h4=i|0}process(e,r){for(let g=0;g<16;g++,r+=4)F[g]=e.getUint32(r,!0);let s=this.h0|0,o=s,i=this.h1|0,a=i,c=this.h2|0,h=c,l=this.h3|0,x=l,w=this.h4|0,b=w;for(let g=0;g<5;g++){const f=4-g,_=re[g],A=se[g],p=_t[g],k=Bt[g],E=ee[g],m=ne[g];for(let y=0;y<16;y++){const d=P.rotl(s+ut(g,i,c,l)+F[p[y]]+_,E[y])+w|0;s=w,w=l,l=P.rotl(c,10)|0,c=i,i=d}for(let y=0;y<16;y++){const d=P.rotl(o+ut(f,a,h,x)+F[k[y]]+A,m[y])+b|0;o=b,b=x,x=P.rotl(h,10)|0,h=a,a=d}}this.set(this.h1+c+x|0,this.h2+l+b|0,this.h3+w+o|0,this.h4+s+a|0,this.h0+i+h|0)}roundClean(){P.clean(F)}destroy(){this.destroyed=!0,P.clean(this.buffer),this.set(0,0,0,0,0)}}const ie=P.createHasher(()=>new oe),ae=BigInt(0),U=BigInt(1),ce=BigInt(2),le=BigInt(7),ue=BigInt(256),he=BigInt(113),At=[],It=[],St=[];for(let n=0,t=U,e=1,r=0;n<24;n++){[e,r]=[r,(2*e+3*r)%5],At.push(2*(5*r+e)),It.push((n+1)*(n+2)/2%64);let s=ae;for(let o=0;o<7;o++)t=(t<<U^(t>>le)*he)%ue,t&ce&&(s^=U<<(U<<BigInt(o))-U);St.push(s)}const Ht=Mt(St,!0),de=Ht[0],ge=Ht[1],ht=(n,t,e)=>e>32?Dt(n,t,e):Xt(n,t,e),dt=(n,t,e)=>e>32?qt(n,t,e):Kt(n,t,e);function fe(n,t=24){const e=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)e[i]=n[i]^n[i+10]^n[i+20]^n[i+30]^n[i+40];for(let i=0;i<10;i+=2){const a=(i+8)%10,c=(i+2)%10,h=e[c],l=e[c+1],x=ht(h,l,1)^e[a],w=dt(h,l,1)^e[a+1];for(let b=0;b<50;b+=10)n[i+b]^=x,n[i+b+1]^=w}let s=n[2],o=n[3];for(let i=0;i<24;i++){const a=It[i],c=ht(s,o,a),h=dt(s,o,a),l=At[i];s=n[l],o=n[l+1],n[l]=c,n[l+1]=h}for(let i=0;i<50;i+=10){for(let a=0;a<10;a++)e[a]=n[i+a];for(let a=0;a<10;a++)n[i+a]^=~e[(a+2)%10]&e[(a+4)%10]}n[0]^=de[r],n[1]^=ge[r]}P.clean(e)}class nt{constructor(t,e,r,s=!1,o=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=r,this.enableXOF=s,this.rounds=o,P.anumber(r,"outputLen"),!(0<t&&t<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=P.u32(this.state)}clone(){return this._cloneInto()}keccak(){P.swap32IfBE(this.state32),fe(this.state32,this.rounds),P.swap32IfBE(this.state32),this.posOut=0,this.pos=0}update(t){P.aexists(this),P.abytes(t);const{blockLen:e,state:r}=this,s=t.length;for(let o=0;o<s;){const i=Math.min(e-this.pos,s-o);for(let a=0;a<i;a++)r[this.pos++]^=t[o++];this.pos===e&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:e,pos:r,blockLen:s}=this;t[r]^=e,(e&128)!==0&&r===s-1&&this.keccak(),t[s-1]^=128,this.keccak()}writeInto(t){P.aexists(this,!1),P.abytes(t),this.finish();const e=this.state,{blockLen:r}=this;for(let s=0,o=t.length;s<o;){this.posOut>=r&&this.keccak();const i=Math.min(r-this.posOut,o-s);t.set(e.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=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 P.anumber(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(P.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,P.clean(this.state)}_cloneInto(t){const{blockLen:e,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return t||(t=new nt(e,r,s,i,o)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=o,t.suffix=r,t.outputLen=s,t.enableXOF=i,t.destroyed=this.destroyed,t}}const pe=(n,t,e,r={})=>P.createHasher(()=>new nt(t,n,e),r),me=pe(1,136,32),gt=64,B=20,et=4,Rt=2,Pe=0,xe=1,M=[64,64],we=n=>Array.from(n).map(t=>t.toString(16).padStart(2,"0")).join("");function rt(n){return ie(P.sha256(n))}function Ot(n){return(1<<n)-1}function be(n){let t=1;for(;t*t<n+1;)t++;return Math.max(t,2)}function ye(n){const t=et,e=n*Ot(t);return{d:t,n,checksum_radix:be(e)}}function G(n,t){const e=[];let r=t;for(;r>0;)e.push(r&255),r>>>=8;const s=new Uint8Array(n.length+e.length);s.set(n);for(let o=0;o<e.length;o++)s[n.length+o]=e[o];return rt(s)}function Z(n,t){let e=n;for(let r=0;r<t;r++)e=rt(e);return e}function ke(n,t){const e=Ot(t.d),r=t.checksum_radix-1,s=Math.floor(t.n*e/t.checksum_radix),o=[];for(let l=0;l<t.n;l++){const x=G(n,l+Rt),w=Z(x,e);o.push(Array.from(w))}const i=G(n,Pe),a=Z(i,r),c=G(n,xe),h=Z(c,s);return{config:t,message_terminals:o,checksum_major_terminal:Array.from(h),checksum_minor_terminal:Array.from(a)}}async function Ct(n){try{if(n.length!==gt)throw new Error(`WOTS seed must be exactly ${gt} bytes, got ${n.length}`);const t=[];for(let e=0;e<M.length;e++){const r=M[e],s=ye(r),o=new Uint8Array(n.length+1);o.set(n),o[n.length]=e;const i=rt(o);try{const a=ke(i,s);if(a.config.d!==et)throw new Error(`Block ${e}: expected d=${et}, got d=${a.config.d}`);if(a.config.n!==r)throw new Error(`Block ${e}: expected n=${r}, got n=${a.config.n}`);if(a.message_terminals.length!==r)throw new Error(`Block ${e}: expected ${r} message terminals, got ${a.message_terminals.length}`);for(let c=0;c<a.message_terminals.length;c++)if(a.message_terminals[c].length!==B)throw new Error(`Block ${e} terminal ${c}: expected ${B} bytes, got ${a.message_terminals[c].length}`);if(a.checksum_minor_terminal.length!==B)throw new Error(`Block ${e} checksum_minor: expected ${B} bytes`);if(a.checksum_major_terminal.length!==B)throw new Error(`Block ${e} checksum_major: expected ${B} bytes`);t.push(a)}finally{o.fill(0),i.fill(0)}}if(t.length!==M.length)throw new Error(`Expected ${M.length} blocks, got ${t.length}`);return t}finally{n.fill(0)}}function Q(n,t,e){if(n.length!==B)throw new Error(`Block ${t} ${e}: expected ${B} bytes, got ${n.length}`);for(let r=0;r<n.length;r++){const s=n[r];if(!Number.isInteger(s)||s<0||s>255)throw new Error(`Block ${t} ${e}[${r}]: invalid byte value ${s}`)}}function $t(n){if(n.length===0)throw new Error("Public keys array must not be empty");for(let o=0;o<n.length;o++){const i=n[o];Q(i.checksum_minor_terminal,o,"checksum_minor_terminal"),Q(i.checksum_major_terminal,o,"checksum_major_terminal");for(let a=0;a<i.message_terminals.length;a++)Q(i.message_terminals[a],o,`message_terminal[${a}]`)}let t=0;for(const o of n)t+=Rt+o.message_terminals.length;const e=new Uint8Array(t*B);let r=0;for(const o of n){e.set(o.checksum_minor_terminal,r),r+=B,e.set(o.checksum_major_terminal,r),r+=B;for(const i of o.message_terminals)e.set(i,r),r+=B}const s=me(e);return`0x${we(s)}`}async function Ee(n,t){const e=[],r=[],s=[],o=[];try{for(let i=0;i<t;i++){const a=await L.expandWotsSeed(n,i);try{const h=await Ct(a);e.push(h),r.push($t(h))}finally{a.fill(0)}const c=await L.expandHashlockSecret(n,i);try{const h=u.uint8ArrayToHex(c);s.push(h),o.push(Lt.computeHashlock(u.ensureHexPrefix(h)).slice(2))}finally{c.fill(0)}}}finally{n.fill(0)}return{perVaultWotsKeys:e,wotsPkHashes:r,htlcSecretHexes:s,hashlocks:o}}const Te=/^0x[0-9a-f]+$/i,_e=/^[0-9a-f]+$/i,Be=/^[A-Za-z0-9+/]+={0,2}$/;function V(n){if(typeof n!="string"||n.length===0)throw new Error("BTC wallet returned empty public key");return u.processPublicKeyToXOnly(n).toLowerCase()}function ve(n){if(typeof n!="string"||n.length===0)throw new Error("BTC wallet returned empty BIP-322 signature");if(n.startsWith("0x")||n.startsWith("0X")){if(!Te.test(n)||n.length<4||n.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return n.toLowerCase()}if(_e.test(n)){if(n.length%2!==0)throw new Error("BTC wallet returned malformed hex BIP-322 signature");return`0x${n.toLowerCase()}`}if(!Be.test(n)||n.length%4!==0)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");const t=Y.Buffer.from(n,"base64");if(t.length===0||t.toString("base64")!==n)throw new Error("BTC wallet returned malformed base64 BIP-322 signature");return`0x${t.toString("hex")}`}async function Ae(n,t,e){if(typeof n.signPsbts=="function"){const s=await n.signPsbts(t,e);if(s.length!==t.length)throw new Error(`Expected ${t.length} signed PSBTs but received ${s.length}`);return s}const r=[];for(let s=0;s<t.length;s++){const o=await n.signPsbt(t[s],e[s]);r.push(o)}return r}const Ie=0,X="00".repeat(32);function Se(n,t,e,r){const s=e==null?void 0:e[`${n}:${t}`];return s?Promise.resolve({txid:n,vout:t,value:s.value,scriptPubKey:s.scriptPubKey}):pt.getUtxoInfo(n,t,r)}const ft=12e4;class He{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(),r=V(e);if(!u.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 s=await this.prepareSizing(r,t),o=s.selectedUTXOs.map(f=>({txid:u.hexToUint8Array(f.txid),vout:f.vout})),i=await kt(this.config.btcWallet,{depositorBtcPubkey:u.hexToUint8Array(r),fundingOutpoints:o});let a,c;try{const f=await L.expandAuthAnchor(i);try{a=u.uint8ArrayToHex(f),c=u.uint8ArrayToHex(P.sha256(f))}finally{f.fill(0)}}catch(f){throw i.fill(0),f}const h=await Ee(i,t.amounts.length),{perVaultWotsKeys:l,wotsPkHashes:x,htlcSecretHexes:w,hashlocks:b}=h,g=await this.preparePeginCommit({depositorBtcPubkeyRaw:e,depositorBtcPubkey:r,hashlocks:b,authAnchorHash:c,sizing:s,params:t});for(let f=0;f<g.perVault.length;f++)if(g.perVault[f].htlcVout!==f)throw new Error(`Internal invariant violation: htlcVout/index mismatch at vault ${f} (expected ${f}, got ${g.perVault[f].htlcVout})`);return Gt(g.fundedPrePeginTxHex,t.amounts.length,c),{transaction:{...g,selectedUTXOs:s.selectedUTXOs,fee:s.fee,changeAmount:s.changeAmount},depositorBtcPubkey:r,derivedSecrets:{perVaultWotsKeys:l,wotsPkHashes:x,htlcSecretHexes:w,authAnchorHex:a}}}async prepareSizing(t,e){const r=e.amounts.map(()=>X),s=e.vaultKeeperBtcPubkeys.length,o=await R.buildPrePeginPsbt({depositorPubkey:t,vaultProviderPubkey:u.stripHexPrefix(e.vaultProviderBtcPubkey),vaultKeeperPubkeys:e.vaultKeeperBtcPubkeys.map(u.stripHexPrefix),universalChallengerPubkeys:e.universalChallengerBtcPubkeys.map(u.stripHexPrefix),hashlocks:r,timelockRefund:e.timelockRefund,pegInAmounts:e.amounts,feeRate:e.protocolFeeRate,numLocalChallengers:s,councilQuorum:e.councilQuorum,councilSize:e.councilSize,network:this.config.btcNetwork,authAnchorHash:X}),i=S.selectUtxosForPegin([...e.availableUTXOs],o.totalOutputValue,e.mempoolFeeRate,ot.peginOutputCount(o.htlcValues.length,X));return{selectedUTXOs:i.selectedUTXOs,fee:i.fee,changeAmount:i.changeAmount}}async preparePeginCommit(t){const{depositorBtcPubkeyRaw:e,depositorBtcPubkey:r,hashlocks:s,authAnchorHash:o,sizing:i,params:a}=t,c=X.toLowerCase();for(let d=0;d<s.length;d++)if(s[d].toLowerCase()===c)throw new Error(`preparePeginCommit refusing to build with sizing-pass placeholder hashlock at vault ${d} — internal substitution bug`);if(o.toLowerCase()===c)throw new Error("preparePeginCommit refusing to build with sizing-pass placeholder auth-anchor hash — internal substitution bug");const h=u.stripHexPrefix(a.vaultProviderBtcPubkey),l=a.vaultKeeperBtcPubkeys.map(u.stripHexPrefix),x=a.universalChallengerBtcPubkeys.map(u.stripHexPrefix),w=l.length,b={depositorPubkey:r,vaultProviderPubkey:h,vaultKeeperPubkeys:l,universalChallengerPubkeys:x,hashlocks:s,timelockRefund:a.timelockRefund,pegInAmounts:a.amounts,feeRate:a.protocolFeeRate,numLocalChallengers:w,councilQuorum:a.councilQuorum,councilSize:a.councilSize,network:this.config.btcNetwork,authAnchorHash:o},g=await R.buildPrePeginPsbt(b),f=u.getNetwork(this.config.btcNetwork),_=ot.fundPeginTransaction({unfundedTxHex:g.psbtHex,selectedUTXOs:i.selectedUTXOs,changeAddress:a.changeAddress,changeAmount:i.changeAmount,network:f}),A=u.stripHexPrefix(S.calculateBtcTxHash(_)),p=[],k=[],E=[];for(let d=0;d<s.length;d++){const I=await R.buildPeginTxFromFundedPrePegin({prePeginParams:b,timelockPegin:a.timelockPegin,fundedPrePeginTxHex:_,htlcVout:d}),v=await R.buildPeginInputPsbt({peginTxHex:I.txHex,fundedPrePeginTxHex:_,depositorPubkey:r,vaultProviderPubkey:h,vaultKeeperPubkeys:l,universalChallengerPubkeys:x,hashlock:s[d],timelockRefund:a.timelockRefund,network:this.config.btcNetwork});p.push(I),k.push(v.psbtHex),E.push(Nt.createTaprootScriptPathSignOptions(e,1))}const m=await Ae(this.config.btcWallet,k,E),y=[];for(let d=0;d<m.length;d++){const I=R.extractPeginInputSignature(m[d],r),v=R.finalizePeginInputPsbt(m[d]);y.push({htlcVout:d,htlcValue:g.htlcValues[d],peginTxHex:v,peginTxid:p[d].txid,peginInputSignature:I,vaultScriptPubKey:p[d].vaultScriptPubKey})}return{fundedPrePeginTxHex:_,prePeginTxid:A,perVault:y}}async signAndBroadcast(t){const{fundedPrePeginTxHex:e,depositorBtcPubkey:r}=t,s=e.startsWith("0x")?e.slice(2):e,o=K.Transaction.fromHex(s);if(o.ins.length===0)throw new Error("Transaction has no inputs");const i=new K.Psbt;i.setVersion(o.version),i.setLocktime(o.locktime);const a=Y.Buffer.from(V(r),"hex"),c=this.config.mempoolApiUrl,h=o.ins.map(p=>{const k=Y.Buffer.from(p.hash).reverse().toString("hex"),E=p.index;return Se(k,E,t.localPrevouts,c).then(m=>({input:p,utxoData:m,txid:k,vout:E}))}),l=await Promise.all(h),x=l.reduce((p,k)=>p+BigInt(k.utxoData.value),0n),w=o.outs.reduce((p,k)=>p+BigInt(k.value),0n);if(x<w)throw new Error(`UTXO value mismatch: total input value (${x} sat) is less than total output value (${w} sat). This may indicate the mempool API returned manipulated UTXO data.`);const b=x-w;if(b>st.MAX_REASONABLE_FEE_SATS)throw new Error(`Implied transaction fee (${b} sat) exceeds maximum reasonable fee (${st.MAX_REASONABLE_FEE_SATS} sat). This may indicate manipulated UTXO data.`);for(const{input:p,utxoData:k,txid:E,vout:m}of l){const y=S.getPsbtInputFields({value:k.value,scriptPubKey:k.scriptPubKey},a);i.addInput({hash:p.hash,index:p.index,sequence:p.sequence,...y})}for(const p of o.outs)i.addOutput({script:p.script,value:p.value});const g=await this.config.btcWallet.signPsbt(i.toHex()),f=K.Psbt.fromHex(g);try{f.finalizeAllInputs()}catch(p){if(!f.data.inputs.every(E=>E.finalScriptWitness||E.finalScriptSig))throw new Error(`PSBT finalization failed and wallet did not auto-finalize: ${p}`)}const _=f.extractTransaction().toHex();return await pt.pushTx(_,c)}async registerPeginOnChain(t){const{unsignedPrePeginTx:e,depositorSignedPeginTx:r,vaultProvider:s,hashlock:o,htlcVout:i,depositorPayoutBtcAddress:a,depositorWotsPkHash:c,popSignature:h}=t;if(!this.config.ethWallet.account)throw new Error("Ethereum wallet account not found");const l=this.config.ethWallet.account.address;if(!C.isAddressEqual(h.depositorEthAddress,l))throw new Error(`Proof of possession was signed for ${h.depositorEthAddress} but the Ethereum wallet is currently connected to ${l}. Reconnect the original account or call signProofOfPossession() again.`);const x=await this.assertPopMatchesBtcWallet(h),w=h.btcPopSignature,b=u.ensureHexPrefix(h.depositorBtcPubkey),g=u.ensureHexPrefix(e),f=u.ensureHexPrefix(r),_=a??await this.config.btcWallet.getAddress(),A=this.resolvePayoutScriptPubKey(x,_),p=S.calculateBtcTxHash(f),k=await L.deriveVaultId(u.stripHexPrefix(p),u.stripHexPrefix(l)),E=u.ensureHexPrefix(k);if(await this.checkVaultExists(E))throw new Error(`Vault already exists (ID: ${E}, peginTxHash: ${p}). 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 y=this.config.publicClient;let d;try{d=await y.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:$.BTCVaultRegistryABI,functionName:"getPegInFee",args:[s]})}catch(O){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",{cause:O})}const I=C.encodeFunctionData({abi:$.BTCVaultRegistryABI,functionName:"submitPeginRequest",args:[l,b,w,g,f,s,o,i,A,c]});let v;try{v=await y.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:I,value:d,account:this.config.ethWallet.account.address})}catch(O){H.handleContractError(O)}let q;try{q=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:I,value:d,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:v})}catch(O){H.handleContractError(O)}const z=await S.waitForTransactionReceiptSmartAware({publicClient:y,walletAddress:this.config.ethWallet.account.address,hash:q,timeout:ft});return z.status==="reverted"&&H.handleContractError(new Error(`Transaction reverted. Hash: ${z.transactionHash}. Check the transaction on block explorer for details.`)),{ethTxHash:z.transactionHash,vaultId:E,peginTxHash:p}}async registerPeginBatchOnChain(t){const{vaultProvider:e,unsignedPrePeginTx:r,requests:s,popSignature:o}=t;if(s.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(!C.isAddressEqual(o.depositorEthAddress,i))throw new Error(`Proof of possession was signed for ${o.depositorEthAddress} but the Ethereum wallet is currently connected to ${i}. Reconnect the original account or call signProofOfPossession() again.`);const a=await this.assertPopMatchesBtcWallet(o),c=o.btcPopSignature,h=s.map(m=>this.resolvePayoutScriptPubKey(a,m.depositorPayoutBtcAddress)),l=[];for(const m of s){const y=u.ensureHexPrefix(m.depositorSignedPeginTx),d=S.calculateBtcTxHash(y),I=await L.deriveVaultId(u.stripHexPrefix(d),u.stripHexPrefix(i)),v=u.ensureHexPrefix(I);if(await this.checkVaultExists(v))throw new Error(`Vault already exists (ID: ${v}, peginTxHash: ${d}). To create a new vault, use different UTXOs or a different amount.`);l.push({vaultId:v,peginTxHash:d})}const x=this.config.publicClient;let w;try{w=await x.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:$.BTCVaultRegistryABI,functionName:"getPegInFee",args:[e]})}catch(m){throw new Error("Failed to query pegin fee from the contract. Please check your network connection and that the contract address is correct.",{cause:m})}const b=w*BigInt(s.length),g=u.ensureHexPrefix(o.depositorBtcPubkey),f=u.ensureHexPrefix(r),_=s.map((m,y)=>({depositorBtcPubKey:g,btcPopSignature:c,unsignedPrePeginTx:f,depositorSignedPeginTx:u.ensureHexPrefix(m.depositorSignedPeginTx),hashlock:m.hashlock,htlcVout:m.htlcVout,referralCode:Ie,depositorPayoutBtcAddress:h[y],depositorWotsPkHash:m.depositorWotsPkHash})),A=C.encodeFunctionData({abi:$.BTCVaultRegistryABI,functionName:"submitPeginRequestBatch",args:[i,e,_]});let p;try{p=await x.estimateGas({to:this.config.vaultContracts.btcVaultRegistry,data:A,value:b,account:this.config.ethWallet.account.address})}catch(m){H.handleContractError(m)}let k;try{k=await this.config.ethWallet.sendTransaction({to:this.config.vaultContracts.btcVaultRegistry,data:A,value:b,account:this.config.ethWallet.account,chain:this.config.ethChain,gas:p})}catch(m){H.handleContractError(m)}const E=await S.waitForTransactionReceiptSmartAware({publicClient:x,walletAddress:this.config.ethWallet.account.address,hash:k,timeout:ft});return E.status==="reverted"&&H.handleContractError(new Error(`Batch transaction reverted. Hash: ${E.transactionHash}. Check the transaction on block explorer for details.`)),{ethTxHash:E.transactionHash,vaults:l}}async checkVaultExists(t){return(await this.config.publicClient.readContract({address:this.config.vaultContracts.btcVaultRegistry,abi:$.BTCVaultRegistryABI,functionName:"getBtcVaultBasicInfo",args:[t]})).depositor!==C.zeroAddress}resolvePayoutScriptPubKey(t,e){if(!u.isAddressFromPublicKey(e,t,this.config.btcNetwork))throw 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 r=u.getNetwork(this.config.btcNetwork);try{return`0x${mt.address.toOutputScript(e,r).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=V(await this.config.btcWallet.getPublicKeyHex()),r=this.config.vaultContracts.btcVaultRegistry,s=`${t.toLowerCase()}:${this.config.ethChain.id}:pegin:${r.toLowerCase()}`,o=await this.config.btcWallet.signMessage(s,"bip322-simple");return{btcPopSignature:ve(o),depositorEthAddress:t,depositorBtcPubkey:e}}async assertPopMatchesBtcWallet(t){const e=await this.config.btcWallet.getPublicKeyHex(),r=V(e),s=V(t.depositorBtcPubkey);if(r!==s)throw new Error(`Proof of possession was signed with BTC pubkey ${s} but the BTC wallet is currently connected to ${r}. Reconnect the original wallet or call signProofOfPossession() again.`);return e}getNetwork(){return this.config.btcNetwork}getVaultContractAddress(){return this.config.vaultContracts.btcVaultRegistry}}exports.PeginManager=He;exports.VAULT_APP_NAME=bt;exports.buildFundingOutpointsCommitment=xt;exports.buildVaultContext=wt;exports.computeWotsBlockPublicKeysHash=$t;exports.deriveVaultRoot=kt;exports.deriveWotsBlocksFromSeed=Ct;
2
+ //# sourceMappingURL=PeginManager-BPXVXu8t.cjs.map