@gardenfi/core 2.1.3-beta.16 → 2.1.3-beta.18
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/index.cjs +10 -10
- package/dist/index.js +2388 -2322
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
"use strict";var ff=Object.defineProperty;var uf=(e,t,r)=>t in e?ff(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var gr=(e,t,r)=>uf(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const le=require("@gardenfi/orderbook"),j=require("@gardenfi/utils"),Rr=require("@catalogfi/wallets"),it=require("viem"),pa=require("varuint-bitcoin"),lf=require("tiny-secp256k1"),ya=require("bitcoinjs-lib"),df=require("bignumber.js"),Ne=require("starknet");function As(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const to=As(pa),sr=As(lf),ie=As(ya);var ma=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Ri=(e,t,r)=>(ma(e,t,"read from private field"),r?r.call(e):t.get(e)),Ci=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},Ui=(e,t,r,n)=>(ma(e,t,"write to private field"),t.set(e,r),r);const hf=e=>new Promise(t=>setTimeout(t,e));class pf{constructor(t,r){this.maxRetries=Math.max(t,0),this.delay=r}async retry(t){let r=0,n;for(;r<this.maxRetries+1;)try{return await t()}catch(i){r++,n=i,await hf(this.delay*r)}throw n}}const yf=e=>{try{return JSON.parse(e)}catch{return e}};class xt{static async _postWithFallback(t,r){let n="";for(const i of t)try{const s=await fetch(i,{method:"POST",...r});if(s.status>=500){n=await(s.text()||s.json());continue}return await this.parse(s)}catch(s){n=ro(s);continue}throw new Error(n||"All APIs failed")}static async postWithFallback(t,r){return await On(r).retry(()=>this._postWithFallback(t,r))}static async _getWithFallback(t,r){let n="";for(const i of t)try{const s=await fetch(i,r);if(s.status>=500){n=await(s.text()||s.json());continue}return await this.parse(s)}catch(s){n=ro(s);continue}throw new Error(n||"All APIs failed")}static async getWithFallback(t,r){return await On(r).retry(()=>this._getWithFallback(t,r))}static async _get(t,r){return await this.parse(await fetch(t,r))}static async get(t,r){return await On(r).retry(()=>this._get(t,r))}static async _post(t,r){return await this.parse(await fetch(t,{method:"POST",...r}))}static async post(t,r){return await On(r).retry(()=>this._post(t,r))}static async parse(t){const r=await t.text();if(t.status>=200&&t.status<300)return yf(r);throw new Error(r)}}function ro(e){return(e==null?void 0:e.message)||(e==null?void 0:e.toString())||"unknown error"}const On=e=>new pf((e==null?void 0:e.retryCount)??2,(e==null?void 0:e.retryDelay)??1e3),$n=e=>e.startsWith("0x")?e:`0x${e}`,rr=e=>e.startsWith("0x")?e.slice(2):e;var jn,Gn,Vn;let us=class{constructor(t,r,n=void 0){Ci(this,jn,void 0),Ci(this,Gn,void 0),Ci(this,Vn,void 0),Ui(this,jn,t),Ui(this,Vn,n),Ui(this,Gn,r)}get ok(){return Ri(this,jn)}get error(){return Ri(this,Vn)}get val(){return Ri(this,Gn)}};jn=new WeakMap,Gn=new WeakMap,Vn=new WeakMap;const re=e=>new us(!0,e),M=(e,...t)=>{if(typeof e=="string"&&t&&t.length>0){let r=[e,...t].map(n=>{if(n){if(n instanceof Error)return n.message;if(typeof n=="string")return n;if(n!=null&&n.toString)return n.toString()}});return new us(!1,null,r.filter(n=>n!==void 0).join(" "))}return new us(!1,null,e)};var Te=(e=>(e.Idle="Idle",e.Initiate="Initiate",e.Redeem="Redeem",e.Refund="Refund",e))(Te||{});function ls(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function er(e,t){if(!e)throw new Error(t)}function mf(e){return Buffer.concat([Uint8Array.from([192]),bf(e)])}function bf(e){const t=to.encodingLength(e.length),r=Buffer.allocUnsafe(t);return to.encode(e.length,r),Buffer.concat([r,e])}function wf(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const Dt=e=>e.length===64?e:e.slice(2),gf=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return sr.isPoint(t)}catch{return!1}},ba=(e,t,r,n)=>e+":"+t.toLowerCase()+"::"+r+":"+n.toLowerCase();function _f(e,t){if(!e)return!1;const r=t===j.Environment.MAINNET?ie.networks.bitcoin:t===j.Environment.TESTNET?ie.networks.testnet:ie.networks.regtest;if(!r)return!1;ie.initEccLib(sr);try{return ie.address.toOutputScript(e,r),!0}catch{return!1}}const vf=e=>{switch(e){case j.Environment.MAINNET:return Rr.BitcoinNetwork.Mainnet;case j.Environment.TESTNET:return Rr.BitcoinNetwork.Testnet;default:throw new Error(`Invalid bitcoin network ${e}`)}},Ef=e=>{const t=e.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(t)},xf=e=>{if(typeof e=="object"&&"r"in e&&"s"in e)return j.Ok([e.r.toString(),e.s.toString()]);if(Array.isArray(e)){const t=e.map(r=>typeof r=="string"&&r.startsWith("0x")&&Ef(r)?BigInt(r).toString():r);return j.Ok(t)}return j.Err("Invalid signature format")};var de=(e=>(e.Created="Created",e.Matched="Matched",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.CounterPartyInitiateDetected="CounterPartyInitiateDetected",e.CounterPartyInitiated="CounterPartyInitiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.CounterPartyRedeemDetected="CounterPartyRedeemDetected",e.CounterPartyRedeemed="CounterPartyRedeemed",e.Completed="Completed",e.CounterPartySwapExpired="CounterPartySwapExpired",e.Expired="Expired",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.CounterPartyRefundDetected="CounterPartyRefundDetected",e.CounterPartyRefunded="CounterPartyRefunded",e.Cancelled="Cancelled",e.DeadLineExceeded="DeadLineExceeded",e))(de||{}),be=(e=>(e.Idle="Idle",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.Expired="Expired",e))(be||{});const ks=(e,t,r)=>{const n=ds(e.source_swap,t),i=ds(e.destination_swap,r);if(i===be.RedeemDetected)return de.RedeemDetected;if(i===be.Redeemed)return de.Redeemed;if(n===be.Refunded)return de.Refunded;if(n===be.RefundDetected)return de.RefundDetected;if(i===be.Expired)return de.CounterPartySwapExpired;if(n===be.Expired)return de.Expired;if(i===be.Refunded)return de.CounterPartyRefunded;if(i===be.RefundDetected)return de.CounterPartyRefundDetected;const s=Number(e.create_order.additional_data.deadline);return i===be.Initiated?de.CounterPartyInitiated:i===be.InitiateDetected?de.CounterPartyInitiateDetected:pn(s,12)?de.DeadLineExceeded:n===be.Initiated?de.Initiated:pn(s,1)?de.DeadLineExceeded:n===be.InitiateDetected?de.InitiateDetected:n===be.Redeemed?de.CounterPartyRedeemed:n===be.RedeemDetected?de.CounterPartyRedeemDetected:de.Matched},ds=(e,t)=>{if(e.redeem_tx_hash)return Number(e.redeem_block_number)?be.Redeemed:be.RedeemDetected;if(e.refund_tx_hash)return Number(e.refund_block_number)?be.Refunded:be.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return be.Expired}return e.initiate_tx_hash?Number(e.initiate_block_number)?be.Initiated:be.InitiateDetected:be.Idle},Sf=(e,t,r)=>{const n=ks(e,t,r);return Bs(n)},Bs=e=>{switch(e){case de.Matched:return Te.Initiate;case de.CounterPartyInitiated:case de.CounterPartyInitiateDetected:case de.RedeemDetected:return Te.Redeem;case de.Expired:return Te.Refund;default:return Te.Idle}},pn=(e,t=0)=>{const r=Date.now(),n=e*1e3+t*36e5;return r>=n},Tf=e=>e.filter(t=>!wa(t)),wa=e=>{const{source_swap:t,create_order:r}=e,{initiate_tx_hash:n,initiate_block_number:i}=t,{deadline:s}=r.additional_data;return n&&Number(i)?!1:n&&!Number(i)?pn(Number(s),12):n?!1:pn(Number(s),1)},Af=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),kf=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),Bf=Buffer.concat([Af,kf]),If=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),no={failedToCreateInternalPubkey:"failed to create internal pubkey"};function Pf(){const e=ya.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=sr.pointMultiply(Buffer.concat([Buffer.from("04","hex"),Bf]),e);if(!t)throw new Error(no.failedToCreateInternalPubkey);const r=sr.pointAdd(If,t);if(!r)throw new Error(no.failedToCreateInternalPubkey);return ls(Buffer.from(r))}var zt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Of(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Rf(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var we={},Fe={},It={},ci={};ci.byteLength=Lf;ci.toByteArray=Hf;ci.fromByteArray=Df;var ht=[],et=[],Cf=typeof Uint8Array<"u"?Uint8Array:Array,Li="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var _r=0,Uf=Li.length;_r<Uf;++_r)ht[_r]=Li[_r],et[Li.charCodeAt(_r)]=_r;et[45]=62;et[95]=63;function ga(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function Lf(e){var t=ga(e),r=t[0],n=t[1];return(r+n)*3/4-n}function Nf(e,t,r){return(t+r)*3/4-r}function Hf(e){var t,r=ga(e),n=r[0],i=r[1],s=new Cf(Nf(e,n,i)),o=0,a=i>0?n-4:n,u;for(u=0;u<a;u+=4)t=et[e.charCodeAt(u)]<<18|et[e.charCodeAt(u+1)]<<12|et[e.charCodeAt(u+2)]<<6|et[e.charCodeAt(u+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=et[e.charCodeAt(u)]<<2|et[e.charCodeAt(u+1)]>>4,s[o++]=t&255),i===1&&(t=et[e.charCodeAt(u)]<<10|et[e.charCodeAt(u+1)]<<4|et[e.charCodeAt(u+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function Ff(e){return ht[e>>18&63]+ht[e>>12&63]+ht[e>>6&63]+ht[e&63]}function Mf(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push(Ff(n));return i.join("")}function Df(e){for(var t,r=e.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(Mf(e,o,o+s>a?a:o+s));return n===1?(t=e[r-1],i.push(ht[t>>2]+ht[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(ht[t>>10]+ht[t>>4&63]+ht[t<<2&63]+"=")),i.join("")}var Is={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Is.read=function(e,t,r,n,i){var s,o,a=i*8-n-1,u=(1<<a)-1,d=u>>1,h=-7,y=r?i-1:0,v=r?-1:1,p=e[t+y];for(y+=v,s=p&(1<<-h)-1,p>>=-h,h+=a;h>0;s=s*256+e[t+y],y+=v,h-=8);for(o=s&(1<<-h)-1,s>>=-h,h+=n;h>0;o=o*256+e[t+y],y+=v,h-=8);if(s===0)s=1-d;else{if(s===u)return o?NaN:(p?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-d}return(p?-1:1)*o*Math.pow(2,s-n)};Is.write=function(e,t,r,n,i,s){var o,a,u,d=s*8-i-1,h=(1<<d)-1,y=h>>1,v=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,p=n?0:s-1,I=n?1:-1,k=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=h):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+y>=1?t+=v/u:t+=v*Math.pow(2,1-y),t*u>=2&&(o++,u/=2),o+y>=h?(a=0,o=h):o+y>=1?(a=(t*u-1)*Math.pow(2,i),o=o+y):(a=t*Math.pow(2,y-1)*Math.pow(2,i),o=0));i>=8;e[r+p]=a&255,p+=I,a/=256,i-=8);for(o=o<<i|a,d+=i;d>0;e[r+p]=o&255,p+=I,o/=256,d-=8);e[r+p-I]|=k*128};/*!
|
|
1
|
+
"use strict";var df=Object.defineProperty;var pf=(e,t,r)=>t in e?df(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var wr=(e,t,r)=>pf(e,typeof t!="symbol"?t+"":t,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const le=require("@gardenfi/orderbook"),j=require("@gardenfi/utils"),Or=require("@catalogfi/wallets"),nt=require("viem"),ya=require("varuint-bitcoin"),yf=require("tiny-secp256k1"),ma=require("bitcoinjs-lib"),mf=require("bignumber.js"),Ne=require("starknet");function As(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}return t.default=e,Object.freeze(t)}const no=As(ya),ir=As(yf),ie=As(ma);var ba=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)},Ri=(e,t,r)=>(ba(e,t,"read from private field"),r?r.call(e):t.get(e)),Ci=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},Ui=(e,t,r,n)=>(ba(e,t,"write to private field"),t.set(e,r),r);const bf=e=>new Promise(t=>setTimeout(t,e));class wf{constructor(t,r){this.maxRetries=Math.max(t,0),this.delay=r}async retry(t){let r=0,n;for(;r<this.maxRetries+1;)try{return await t()}catch(i){r++,n=i,await bf(this.delay*r)}throw n}}const gf=e=>{try{return JSON.parse(e)}catch{return e}};class xt{static async _postWithFallback(t,r){let n="";for(const i of t)try{const s=await fetch(i,{method:"POST",...r});if(s.status>=500){n=await(s.text()||s.json());continue}return await this.parse(s)}catch(s){n=io(s);continue}throw new Error(n||"All APIs failed")}static async postWithFallback(t,r){return await In(r).retry(()=>this._postWithFallback(t,r))}static async _getWithFallback(t,r){let n="";for(const i of t)try{const s=await fetch(i,r);if(s.status>=500){n=await(s.text()||s.json());continue}return await this.parse(s)}catch(s){n=io(s);continue}throw new Error(n||"All APIs failed")}static async getWithFallback(t,r){return await In(r).retry(()=>this._getWithFallback(t,r))}static async _get(t,r){return await this.parse(await fetch(t,r))}static async get(t,r){return await In(r).retry(()=>this._get(t,r))}static async _post(t,r){return await this.parse(await fetch(t,{method:"POST",...r}))}static async post(t,r){return await In(r).retry(()=>this._post(t,r))}static async parse(t){const r=await t.text();if(t.status>=200&&t.status<300)return gf(r);throw new Error(r)}}function io(e){return(e==null?void 0:e.message)||(e==null?void 0:e.toString())||"unknown error"}const In=e=>new wf((e==null?void 0:e.retryCount)??2,(e==null?void 0:e.retryDelay)??1e3),Mn=e=>e.startsWith("0x")?e:`0x${e}`,tr=e=>e.startsWith("0x")?e.slice(2):e;var Dn,$n,jn;let us=class{constructor(t,r,n=void 0){Ci(this,Dn,void 0),Ci(this,$n,void 0),Ci(this,jn,void 0),Ui(this,Dn,t),Ui(this,jn,n),Ui(this,$n,r)}get ok(){return Ri(this,Dn)}get error(){return Ri(this,jn)}get val(){return Ri(this,$n)}};Dn=new WeakMap,$n=new WeakMap,jn=new WeakMap;const re=e=>new us(!0,e),M=(e,...t)=>{if(typeof e=="string"&&t&&t.length>0){let r=[e,...t].map(n=>{if(n){if(n instanceof Error)return n.message;if(typeof n=="string")return n;if(n!=null&&n.toString)return n.toString()}});return new us(!1,null,r.filter(n=>n!==void 0).join(" "))}return new us(!1,null,e)};var Te=(e=>(e.Idle="Idle",e.Initiate="Initiate",e.Redeem="Redeem",e.Refund="Refund",e))(Te||{});function ls(e){return typeof e=="string"&&(e=Buffer.from(e,"hex")),e.length===32?e:e.subarray(1,33)}function Zt(e,t){if(!e)throw new Error(t)}function _f(e){return Buffer.concat([Uint8Array.from([192]),vf(e)])}function vf(e){const t=no.encodingLength(e.length),r=Buffer.allocUnsafe(t);return no.encode(e.length,r),Buffer.concat([r,e])}function Ef(e,t){if(e.compare(t)>0){const r=e;e=t,t=r}return[e,t]}const Ft=e=>e.length===64?e:e.slice(2),xf=e=>{if(!e)return!1;try{const t=Buffer.from(e,"hex");return ir.isPoint(t)}catch{return!1}},wa=(e,t,r,n)=>e+":"+t.toLowerCase()+"::"+r+":"+n.toLowerCase();function Sf(e,t){if(!e)return!1;const r=t===j.Environment.MAINNET?ie.networks.bitcoin:t===j.Environment.TESTNET?ie.networks.testnet:ie.networks.regtest;if(!r)return!1;ie.initEccLib(ir);try{return ie.address.toOutputScript(e,r),!0}catch{return!1}}const Tf=e=>{switch(e){case j.Environment.MAINNET:return Or.BitcoinNetwork.Mainnet;case j.Environment.TESTNET:return Or.BitcoinNetwork.Testnet;default:throw new Error(`Invalid bitcoin network ${e}`)}},Af=e=>{const t=e.toLowerCase().replace("0x","");return/^[0-9a-f]+$/.test(t)},kf=e=>{if(typeof e=="object"&&"r"in e&&"s"in e)return j.Ok([e.r.toString(),e.s.toString()]);if(Array.isArray(e)){const t=e.map(r=>typeof r=="string"&&r.startsWith("0x")&&Af(r)?BigInt(r).toString():r);return j.Ok(t)}return j.Err("Invalid signature format")};var he=(e=>(e.Created="Created",e.Matched="Matched",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.CounterPartyInitiateDetected="CounterPartyInitiateDetected",e.CounterPartyInitiated="CounterPartyInitiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.CounterPartyRedeemDetected="CounterPartyRedeemDetected",e.CounterPartyRedeemed="CounterPartyRedeemed",e.Completed="Completed",e.CounterPartySwapExpired="CounterPartySwapExpired",e.Expired="Expired",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.CounterPartyRefundDetected="CounterPartyRefundDetected",e.CounterPartyRefunded="CounterPartyRefunded",e.Cancelled="Cancelled",e.DeadLineExceeded="DeadLineExceeded",e))(he||{}),be=(e=>(e.Idle="Idle",e.InitiateDetected="InitiateDetected",e.Initiated="Initiated",e.RedeemDetected="RedeemDetected",e.Redeemed="Redeemed",e.RefundDetected="RefundDetected",e.Refunded="Refunded",e.Expired="Expired",e))(be||{});const ks=(e,t,r)=>{const n=hs(e.source_swap,t),i=hs(e.destination_swap,r);if(i===be.RedeemDetected)return he.RedeemDetected;if(i===be.Redeemed)return he.Redeemed;if(n===be.Refunded)return he.Refunded;if(n===be.RefundDetected)return he.RefundDetected;if(i===be.Expired)return he.CounterPartySwapExpired;if(n===be.Expired)return he.Expired;if(i===be.Refunded)return he.CounterPartyRefunded;if(i===be.RefundDetected)return he.CounterPartyRefundDetected;const s=Number(e.create_order.additional_data.deadline);return i===be.Initiated?he.CounterPartyInitiated:i===be.InitiateDetected?he.CounterPartyInitiateDetected:dn(s,12)?he.DeadLineExceeded:n===be.Initiated?he.Initiated:dn(s,1)?he.DeadLineExceeded:n===be.InitiateDetected?he.InitiateDetected:n===be.Redeemed?he.CounterPartyRedeemed:n===be.RedeemDetected?he.CounterPartyRedeemDetected:he.Matched},hs=(e,t)=>{if(e.redeem_tx_hash)return Number(e.redeem_block_number)?be.Redeemed:be.RedeemDetected;if(e.refund_tx_hash)return Number(e.refund_block_number)?be.Refunded:be.RefundDetected;if(Number(e.initiate_block_number)){const r=Number(e.initiate_block_number)+e.timelock;if(t>r)return be.Expired}return e.initiate_tx_hash?Number(e.initiate_block_number)?be.Initiated:be.InitiateDetected:be.Idle},Bf=(e,t,r)=>{const n=ks(e,t,r);return Bs(n)},Bs=e=>{switch(e){case he.Matched:return Te.Initiate;case he.CounterPartyInitiated:case he.CounterPartyInitiateDetected:case he.RedeemDetected:return Te.Redeem;case he.Expired:return Te.Refund;default:return Te.Idle}},dn=(e,t=0)=>{const r=Date.now(),n=e*1e3+t*36e5;return r>=n},If=e=>e.filter(t=>!ga(t)),ga=e=>{const{source_swap:t,create_order:r}=e,{initiate_tx_hash:n,initiate_block_number:i}=t,{deadline:s}=r.additional_data;return n&&Number(i)?!1:n&&!Number(i)?dn(Number(s),12):n?!1:dn(Number(s),1)},Pf=Buffer.from("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798","hex"),Of=Buffer.from("483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8","hex"),Rf=Buffer.concat([Pf,Of]),Cf=Buffer.from("0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0","hex"),so={failedToCreateInternalPubkey:"failed to create internal pubkey"};function Uf(){const e=ma.crypto.sha256(Buffer.from("GardenHTLC","utf-8")),t=ir.pointMultiply(Buffer.concat([Buffer.from("04","hex"),Rf]),e);if(!t)throw new Error(so.failedToCreateInternalPubkey);const r=ir.pointAdd(Cf,t);if(!r)throw new Error(so.failedToCreateInternalPubkey);return ls(Buffer.from(r))}var Gt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Lf(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function _a(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var i=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return e[n]}})}),r}var we={},Fe={},Bt={},ai={};ai.byteLength=Ff;ai.toByteArray=Df;ai.fromByteArray=Gf;var dt=[],Ze=[],Nf=typeof Uint8Array<"u"?Uint8Array:Array,Li="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var gr=0,Hf=Li.length;gr<Hf;++gr)dt[gr]=Li[gr],Ze[Li.charCodeAt(gr)]=gr;Ze[45]=62;Ze[95]=63;function va(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");r===-1&&(r=t);var n=r===t?0:4-r%4;return[r,n]}function Ff(e){var t=va(e),r=t[0],n=t[1];return(r+n)*3/4-n}function Mf(e,t,r){return(t+r)*3/4-r}function Df(e){var t,r=va(e),n=r[0],i=r[1],s=new Nf(Mf(e,n,i)),o=0,a=i>0?n-4:n,u;for(u=0;u<a;u+=4)t=Ze[e.charCodeAt(u)]<<18|Ze[e.charCodeAt(u+1)]<<12|Ze[e.charCodeAt(u+2)]<<6|Ze[e.charCodeAt(u+3)],s[o++]=t>>16&255,s[o++]=t>>8&255,s[o++]=t&255;return i===2&&(t=Ze[e.charCodeAt(u)]<<2|Ze[e.charCodeAt(u+1)]>>4,s[o++]=t&255),i===1&&(t=Ze[e.charCodeAt(u)]<<10|Ze[e.charCodeAt(u+1)]<<4|Ze[e.charCodeAt(u+2)]>>2,s[o++]=t>>8&255,s[o++]=t&255),s}function $f(e){return dt[e>>18&63]+dt[e>>12&63]+dt[e>>6&63]+dt[e&63]}function jf(e,t,r){for(var n,i=[],s=t;s<r;s+=3)n=(e[s]<<16&16711680)+(e[s+1]<<8&65280)+(e[s+2]&255),i.push($f(n));return i.join("")}function Gf(e){for(var t,r=e.length,n=r%3,i=[],s=16383,o=0,a=r-n;o<a;o+=s)i.push(jf(e,o,o+s>a?a:o+s));return n===1?(t=e[r-1],i.push(dt[t>>2]+dt[t<<4&63]+"==")):n===2&&(t=(e[r-2]<<8)+e[r-1],i.push(dt[t>>10]+dt[t>>4&63]+dt[t<<2&63]+"=")),i.join("")}var Is={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */Is.read=function(e,t,r,n,i){var s,o,a=i*8-n-1,u=(1<<a)-1,h=u>>1,d=-7,p=r?i-1:0,v=r?-1:1,y=e[t+p];for(p+=v,s=y&(1<<-d)-1,y>>=-d,d+=a;d>0;s=s*256+e[t+p],p+=v,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=n;d>0;o=o*256+e[t+p],p+=v,d-=8);if(s===0)s=1-h;else{if(s===u)return o?NaN:(y?-1:1)*(1/0);o=o+Math.pow(2,n),s=s-h}return(y?-1:1)*o*Math.pow(2,s-n)};Is.write=function(e,t,r,n,i,s){var o,a,u,h=s*8-i-1,d=(1<<h)-1,p=d>>1,v=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=n?0:s-1,I=n?1:-1,k=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=d):(o=Math.floor(Math.log(t)/Math.LN2),t*(u=Math.pow(2,-o))<1&&(o--,u*=2),o+p>=1?t+=v/u:t+=v*Math.pow(2,1-p),t*u>=2&&(o++,u/=2),o+p>=d?(a=0,o=d):o+p>=1?(a=(t*u-1)*Math.pow(2,i),o=o+p):(a=t*Math.pow(2,p-1)*Math.pow(2,i),o=0));i>=8;e[r+y]=a&255,y+=I,a/=256,i-=8);for(o=o<<i|a,h+=i;h>0;e[r+y]=o&255,y+=I,o/=256,h-=8);e[r+y-I]|=k*128};/*!
|
|
2
2
|
* The buffer module from node.js, for the browser.
|
|
3
3
|
*
|
|
4
4
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
5
5
|
* @license MIT
|
|
6
|
-
*/(function(e){const t=ci,r=Is,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=a,e.SlowBuffer=U,e.INSPECT_MAX_BYTES=50;const i=2147483647;e.kMaxLength=i,a.TYPED_ARRAY_SUPPORT=s(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const l=new Uint8Array(1),c={foo:function(){return 42}};return Object.setPrototypeOf(c,Uint8Array.prototype),Object.setPrototypeOf(l,c),l.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(l){if(l>i)throw new RangeError('The value "'+l+'" is invalid for option "size"');const c=new Uint8Array(l);return Object.setPrototypeOf(c,a.prototype),c}function a(l,c,f){if(typeof l=="number"){if(typeof c=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return y(l)}return u(l,c,f)}a.poolSize=8192;function u(l,c,f){if(typeof l=="string")return v(l,c);if(ArrayBuffer.isView(l))return I(l);if(l==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l);if(Ke(l,ArrayBuffer)||l&&Ke(l.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ke(l,SharedArrayBuffer)||l&&Ke(l.buffer,SharedArrayBuffer)))return k(l,c,f);if(typeof l=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const m=l.valueOf&&l.valueOf();if(m!=null&&m!==l)return a.from(m,c,f);const _=B(l);if(_)return _;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof l[Symbol.toPrimitive]=="function")return a.from(l[Symbol.toPrimitive]("string"),c,f);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l)}a.from=function(l,c,f){return u(l,c,f)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function d(l){if(typeof l!="number")throw new TypeError('"size" argument must be of type number');if(l<0)throw new RangeError('The value "'+l+'" is invalid for option "size"')}function h(l,c,f){return d(l),l<=0?o(l):c!==void 0?typeof f=="string"?o(l).fill(c,f):o(l).fill(c):o(l)}a.alloc=function(l,c,f){return h(l,c,f)};function y(l){return d(l),o(l<0?0:R(l)|0)}a.allocUnsafe=function(l){return y(l)},a.allocUnsafeSlow=function(l){return y(l)};function v(l,c){if((typeof c!="string"||c==="")&&(c="utf8"),!a.isEncoding(c))throw new TypeError("Unknown encoding: "+c);const f=x(l,c)|0;let m=o(f);const _=m.write(l,c);return _!==f&&(m=m.slice(0,_)),m}function p(l){const c=l.length<0?0:R(l.length)|0,f=o(c);for(let m=0;m<c;m+=1)f[m]=l[m]&255;return f}function I(l){if(Ke(l,Uint8Array)){const c=new Uint8Array(l);return k(c.buffer,c.byteOffset,c.byteLength)}return p(l)}function k(l,c,f){if(c<0||l.byteLength<c)throw new RangeError('"offset" is outside of buffer bounds');if(l.byteLength<c+(f||0))throw new RangeError('"length" is outside of buffer bounds');let m;return c===void 0&&f===void 0?m=new Uint8Array(l):f===void 0?m=new Uint8Array(l,c):m=new Uint8Array(l,c,f),Object.setPrototypeOf(m,a.prototype),m}function B(l){if(a.isBuffer(l)){const c=R(l.length)|0,f=o(c);return f.length===0||l.copy(f,0,0,c),f}if(l.length!==void 0)return typeof l.length!="number"||Qt(l.length)?o(0):p(l);if(l.type==="Buffer"&&Array.isArray(l.data))return p(l.data)}function R(l){if(l>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return l|0}function U(l){return+l!=l&&(l=0),a.alloc(+l)}a.isBuffer=function(c){return c!=null&&c._isBuffer===!0&&c!==a.prototype},a.compare=function(c,f){if(Ke(c,Uint8Array)&&(c=a.from(c,c.offset,c.byteLength)),Ke(f,Uint8Array)&&(f=a.from(f,f.offset,f.byteLength)),!a.isBuffer(c)||!a.isBuffer(f))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(c===f)return 0;let m=c.length,_=f.length;for(let P=0,L=Math.min(m,_);P<L;++P)if(c[P]!==f[P]){m=c[P],_=f[P];break}return m<_?-1:_<m?1:0},a.isEncoding=function(c){switch(String(c).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(c,f){if(!Array.isArray(c))throw new TypeError('"list" argument must be an Array of Buffers');if(c.length===0)return a.alloc(0);let m;if(f===void 0)for(f=0,m=0;m<c.length;++m)f+=c[m].length;const _=a.allocUnsafe(f);let P=0;for(m=0;m<c.length;++m){let L=c[m];if(Ke(L,Uint8Array))P+L.length>_.length?(a.isBuffer(L)||(L=a.from(L)),L.copy(_,P)):Uint8Array.prototype.set.call(_,L,P);else if(a.isBuffer(L))L.copy(_,P);else throw new TypeError('"list" argument must be an Array of Buffers');P+=L.length}return _};function x(l,c){if(a.isBuffer(l))return l.length;if(ArrayBuffer.isView(l)||Ke(l,ArrayBuffer))return l.byteLength;if(typeof l!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof l);const f=l.length,m=arguments.length>2&&arguments[2]===!0;if(!m&&f===0)return 0;let _=!1;for(;;)switch(c){case"ascii":case"latin1":case"binary":return f;case"utf8":case"utf-8":return ne(l).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return f*2;case"hex":return f>>>1;case"base64":return Gr(l).length;default:if(_)return m?-1:ne(l).length;c=(""+c).toLowerCase(),_=!0}}a.byteLength=x;function g(l,c,f){let m=!1;if((c===void 0||c<0)&&(c=0),c>this.length||((f===void 0||f>this.length)&&(f=this.length),f<=0)||(f>>>=0,c>>>=0,f<=c))return"";for(l||(l="utf8");;)switch(l){case"hex":return qe(this,c,f);case"utf8":case"utf-8":return z(this,c,f);case"ascii":return ze(this,c,f);case"latin1":case"binary":return rt(this,c,f);case"base64":return V(this,c,f);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return Ot(this,c,f);default:if(m)throw new TypeError("Unknown encoding: "+l);l=(l+"").toLowerCase(),m=!0}}a.prototype._isBuffer=!0;function S(l,c,f){const m=l[c];l[c]=l[f],l[f]=m}a.prototype.swap16=function(){const c=this.length;if(c%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let f=0;f<c;f+=2)S(this,f,f+1);return this},a.prototype.swap32=function(){const c=this.length;if(c%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let f=0;f<c;f+=4)S(this,f,f+3),S(this,f+1,f+2);return this},a.prototype.swap64=function(){const c=this.length;if(c%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let f=0;f<c;f+=8)S(this,f,f+7),S(this,f+1,f+6),S(this,f+2,f+5),S(this,f+3,f+4);return this},a.prototype.toString=function(){const c=this.length;return c===0?"":arguments.length===0?z(this,0,c):g.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(c){if(!a.isBuffer(c))throw new TypeError("Argument must be a Buffer");return this===c?!0:a.compare(this,c)===0},a.prototype.inspect=function(){let c="";const f=e.INSPECT_MAX_BYTES;return c=this.toString("hex",0,f).replace(/(.{2})/g,"$1 ").trim(),this.length>f&&(c+=" ... "),"<Buffer "+c+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(c,f,m,_,P){if(Ke(c,Uint8Array)&&(c=a.from(c,c.offset,c.byteLength)),!a.isBuffer(c))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof c);if(f===void 0&&(f=0),m===void 0&&(m=c?c.length:0),_===void 0&&(_=0),P===void 0&&(P=this.length),f<0||m>c.length||_<0||P>this.length)throw new RangeError("out of range index");if(_>=P&&f>=m)return 0;if(_>=P)return-1;if(f>=m)return 1;if(f>>>=0,m>>>=0,_>>>=0,P>>>=0,this===c)return 0;let L=P-_,Z=m-f;const ge=Math.min(L,Z),me=this.slice(_,P),_e=c.slice(f,m);for(let oe=0;oe<ge;++oe)if(me[oe]!==_e[oe]){L=me[oe],Z=_e[oe];break}return L<Z?-1:Z<L?1:0};function E(l,c,f,m,_){if(l.length===0)return-1;if(typeof f=="string"?(m=f,f=0):f>2147483647?f=2147483647:f<-2147483648&&(f=-2147483648),f=+f,Qt(f)&&(f=_?0:l.length-1),f<0&&(f=l.length+f),f>=l.length){if(_)return-1;f=l.length-1}else if(f<0)if(_)f=0;else return-1;if(typeof c=="string"&&(c=a.from(c,m)),a.isBuffer(c))return c.length===0?-1:F(l,c,f,m,_);if(typeof c=="number")return c=c&255,typeof Uint8Array.prototype.indexOf=="function"?_?Uint8Array.prototype.indexOf.call(l,c,f):Uint8Array.prototype.lastIndexOf.call(l,c,f):F(l,[c],f,m,_);throw new TypeError("val must be string, number or Buffer")}function F(l,c,f,m,_){let P=1,L=l.length,Z=c.length;if(m!==void 0&&(m=String(m).toLowerCase(),m==="ucs2"||m==="ucs-2"||m==="utf16le"||m==="utf-16le")){if(l.length<2||c.length<2)return-1;P=2,L/=2,Z/=2,f/=2}function ge(_e,oe){return P===1?_e[oe]:_e.readUInt16BE(oe*P)}let me;if(_){let _e=-1;for(me=f;me<L;me++)if(ge(l,me)===ge(c,_e===-1?0:me-_e)){if(_e===-1&&(_e=me),me-_e+1===Z)return _e*P}else _e!==-1&&(me-=me-_e),_e=-1}else for(f+Z>L&&(f=L-Z),me=f;me>=0;me--){let _e=!0;for(let oe=0;oe<Z;oe++)if(ge(l,me+oe)!==ge(c,oe)){_e=!1;break}if(_e)return me}return-1}a.prototype.includes=function(c,f,m){return this.indexOf(c,f,m)!==-1},a.prototype.indexOf=function(c,f,m){return E(this,c,f,m,!0)},a.prototype.lastIndexOf=function(c,f,m){return E(this,c,f,m,!1)};function D(l,c,f,m){f=Number(f)||0;const _=l.length-f;m?(m=Number(m),m>_&&(m=_)):m=_;const P=c.length;m>P/2&&(m=P/2);let L;for(L=0;L<m;++L){const Z=parseInt(c.substr(L*2,2),16);if(Qt(Z))return L;l[f+L]=Z}return L}function O(l,c,f,m){return wr(ne(c,l.length-f),l,f,m)}function K(l,c,f,m){return wr(Ct(c),l,f,m)}function C(l,c,f,m){return wr(Gr(c),l,f,m)}function G(l,c,f,m){return wr(br(c,l.length-f),l,f,m)}a.prototype.write=function(c,f,m,_){if(f===void 0)_="utf8",m=this.length,f=0;else if(m===void 0&&typeof f=="string")_=f,m=this.length,f=0;else if(isFinite(f))f=f>>>0,isFinite(m)?(m=m>>>0,_===void 0&&(_="utf8")):(_=m,m=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const P=this.length-f;if((m===void 0||m>P)&&(m=P),c.length>0&&(m<0||f<0)||f>this.length)throw new RangeError("Attempt to write outside buffer bounds");_||(_="utf8");let L=!1;for(;;)switch(_){case"hex":return D(this,c,f,m);case"utf8":case"utf-8":return O(this,c,f,m);case"ascii":case"latin1":case"binary":return K(this,c,f,m);case"base64":return C(this,c,f,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G(this,c,f,m);default:if(L)throw new TypeError("Unknown encoding: "+_);_=(""+_).toLowerCase(),L=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function V(l,c,f){return c===0&&f===l.length?t.fromByteArray(l):t.fromByteArray(l.slice(c,f))}function z(l,c,f){f=Math.min(l.length,f);const m=[];let _=c;for(;_<f;){const P=l[_];let L=null,Z=P>239?4:P>223?3:P>191?2:1;if(_+Z<=f){let ge,me,_e,oe;switch(Z){case 1:P<128&&(L=P);break;case 2:ge=l[_+1],(ge&192)===128&&(oe=(P&31)<<6|ge&63,oe>127&&(L=oe));break;case 3:ge=l[_+1],me=l[_+2],(ge&192)===128&&(me&192)===128&&(oe=(P&15)<<12|(ge&63)<<6|me&63,oe>2047&&(oe<55296||oe>57343)&&(L=oe));break;case 4:ge=l[_+1],me=l[_+2],_e=l[_+3],(ge&192)===128&&(me&192)===128&&(_e&192)===128&&(oe=(P&15)<<18|(ge&63)<<12|(me&63)<<6|_e&63,oe>65535&&oe<1114112&&(L=oe))}}L===null?(L=65533,Z=1):L>65535&&(L-=65536,m.push(L>>>10&1023|55296),L=56320|L&1023),m.push(L),_+=Z}return ve(m)}const ee=4096;function ve(l){const c=l.length;if(c<=ee)return String.fromCharCode.apply(String,l);let f="",m=0;for(;m<c;)f+=String.fromCharCode.apply(String,l.slice(m,m+=ee));return f}function ze(l,c,f){let m="";f=Math.min(l.length,f);for(let _=c;_<f;++_)m+=String.fromCharCode(l[_]&127);return m}function rt(l,c,f){let m="";f=Math.min(l.length,f);for(let _=c;_<f;++_)m+=String.fromCharCode(l[_]);return m}function qe(l,c,f){const m=l.length;(!c||c<0)&&(c=0),(!f||f<0||f>m)&&(f=m);let _="";for(let P=c;P<f;++P)_+=Vr[l[P]];return _}function Ot(l,c,f){const m=l.slice(c,f);let _="";for(let P=0;P<m.length-1;P+=2)_+=String.fromCharCode(m[P]+m[P+1]*256);return _}a.prototype.slice=function(c,f){const m=this.length;c=~~c,f=f===void 0?m:~~f,c<0?(c+=m,c<0&&(c=0)):c>m&&(c=m),f<0?(f+=m,f<0&&(f=0)):f>m&&(f=m),f<c&&(f=c);const _=this.subarray(c,f);return Object.setPrototypeOf(_,a.prototype),_};function pe(l,c,f){if(l%1!==0||l<0)throw new RangeError("offset is not uint");if(l+c>f)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(c,f,m){c=c>>>0,f=f>>>0,m||pe(c,f,this.length);let _=this[c],P=1,L=0;for(;++L<f&&(P*=256);)_+=this[c+L]*P;return _},a.prototype.readUintBE=a.prototype.readUIntBE=function(c,f,m){c=c>>>0,f=f>>>0,m||pe(c,f,this.length);let _=this[c+--f],P=1;for(;f>0&&(P*=256);)_+=this[c+--f]*P;return _},a.prototype.readUint8=a.prototype.readUInt8=function(c,f){return c=c>>>0,f||pe(c,1,this.length),this[c]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(c,f){return c=c>>>0,f||pe(c,2,this.length),this[c]|this[c+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(c,f){return c=c>>>0,f||pe(c,2,this.length),this[c]<<8|this[c+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),(this[c]|this[c+1]<<8|this[c+2]<<16)+this[c+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),this[c]*16777216+(this[c+1]<<16|this[c+2]<<8|this[c+3])},a.prototype.readBigUInt64LE=Je(function(c){c=c>>>0,N(c,"offset");const f=this[c],m=this[c+7];(f===void 0||m===void 0)&&$(c,this.length-8);const _=f+this[++c]*2**8+this[++c]*2**16+this[++c]*2**24,P=this[++c]+this[++c]*2**8+this[++c]*2**16+m*2**24;return BigInt(_)+(BigInt(P)<<BigInt(32))}),a.prototype.readBigUInt64BE=Je(function(c){c=c>>>0,N(c,"offset");const f=this[c],m=this[c+7];(f===void 0||m===void 0)&&$(c,this.length-8);const _=f*2**24+this[++c]*2**16+this[++c]*2**8+this[++c],P=this[++c]*2**24+this[++c]*2**16+this[++c]*2**8+m;return(BigInt(_)<<BigInt(32))+BigInt(P)}),a.prototype.readIntLE=function(c,f,m){c=c>>>0,f=f>>>0,m||pe(c,f,this.length);let _=this[c],P=1,L=0;for(;++L<f&&(P*=256);)_+=this[c+L]*P;return P*=128,_>=P&&(_-=Math.pow(2,8*f)),_},a.prototype.readIntBE=function(c,f,m){c=c>>>0,f=f>>>0,m||pe(c,f,this.length);let _=f,P=1,L=this[c+--_];for(;_>0&&(P*=256);)L+=this[c+--_]*P;return P*=128,L>=P&&(L-=Math.pow(2,8*f)),L},a.prototype.readInt8=function(c,f){return c=c>>>0,f||pe(c,1,this.length),this[c]&128?(255-this[c]+1)*-1:this[c]},a.prototype.readInt16LE=function(c,f){c=c>>>0,f||pe(c,2,this.length);const m=this[c]|this[c+1]<<8;return m&32768?m|4294901760:m},a.prototype.readInt16BE=function(c,f){c=c>>>0,f||pe(c,2,this.length);const m=this[c+1]|this[c]<<8;return m&32768?m|4294901760:m},a.prototype.readInt32LE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),this[c]|this[c+1]<<8|this[c+2]<<16|this[c+3]<<24},a.prototype.readInt32BE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),this[c]<<24|this[c+1]<<16|this[c+2]<<8|this[c+3]},a.prototype.readBigInt64LE=Je(function(c){c=c>>>0,N(c,"offset");const f=this[c],m=this[c+7];(f===void 0||m===void 0)&&$(c,this.length-8);const _=this[c+4]+this[c+5]*2**8+this[c+6]*2**16+(m<<24);return(BigInt(_)<<BigInt(32))+BigInt(f+this[++c]*2**8+this[++c]*2**16+this[++c]*2**24)}),a.prototype.readBigInt64BE=Je(function(c){c=c>>>0,N(c,"offset");const f=this[c],m=this[c+7];(f===void 0||m===void 0)&&$(c,this.length-8);const _=(f<<24)+this[++c]*2**16+this[++c]*2**8+this[++c];return(BigInt(_)<<BigInt(32))+BigInt(this[++c]*2**24+this[++c]*2**16+this[++c]*2**8+m)}),a.prototype.readFloatLE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),r.read(this,c,!0,23,4)},a.prototype.readFloatBE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),r.read(this,c,!1,23,4)},a.prototype.readDoubleLE=function(c,f){return c=c>>>0,f||pe(c,8,this.length),r.read(this,c,!0,52,8)},a.prototype.readDoubleBE=function(c,f){return c=c>>>0,f||pe(c,8,this.length),r.read(this,c,!1,52,8)};function Ee(l,c,f,m,_,P){if(!a.isBuffer(l))throw new TypeError('"buffer" argument must be a Buffer instance');if(c>_||c<P)throw new RangeError('"value" argument is out of bounds');if(f+m>l.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(c,f,m,_){if(c=+c,f=f>>>0,m=m>>>0,!_){const Z=Math.pow(2,8*m)-1;Ee(this,c,f,m,Z,0)}let P=1,L=0;for(this[f]=c&255;++L<m&&(P*=256);)this[f+L]=c/P&255;return f+m},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(c,f,m,_){if(c=+c,f=f>>>0,m=m>>>0,!_){const Z=Math.pow(2,8*m)-1;Ee(this,c,f,m,Z,0)}let P=m-1,L=1;for(this[f+P]=c&255;--P>=0&&(L*=256);)this[f+P]=c/L&255;return f+m},a.prototype.writeUint8=a.prototype.writeUInt8=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,1,255,0),this[f]=c&255,f+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,2,65535,0),this[f]=c&255,this[f+1]=c>>>8,f+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,2,65535,0),this[f]=c>>>8,this[f+1]=c&255,f+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,4,4294967295,0),this[f+3]=c>>>24,this[f+2]=c>>>16,this[f+1]=c>>>8,this[f]=c&255,f+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,4,4294967295,0),this[f]=c>>>24,this[f+1]=c>>>16,this[f+2]=c>>>8,this[f+3]=c&255,f+4};function We(l,c,f,m,_){w(c,m,_,l,f,7);let P=Number(c&BigInt(4294967295));l[f++]=P,P=P>>8,l[f++]=P,P=P>>8,l[f++]=P,P=P>>8,l[f++]=P;let L=Number(c>>BigInt(32)&BigInt(4294967295));return l[f++]=L,L=L>>8,l[f++]=L,L=L>>8,l[f++]=L,L=L>>8,l[f++]=L,f}function Rt(l,c,f,m,_){w(c,m,_,l,f,7);let P=Number(c&BigInt(4294967295));l[f+7]=P,P=P>>8,l[f+6]=P,P=P>>8,l[f+5]=P,P=P>>8,l[f+4]=P;let L=Number(c>>BigInt(32)&BigInt(4294967295));return l[f+3]=L,L=L>>8,l[f+2]=L,L=L>>8,l[f+1]=L,L=L>>8,l[f]=L,f+8}a.prototype.writeBigUInt64LE=Je(function(c,f=0){return We(this,c,f,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Je(function(c,f=0){return Rt(this,c,f,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(c,f,m,_){if(c=+c,f=f>>>0,!_){const ge=Math.pow(2,8*m-1);Ee(this,c,f,m,ge-1,-ge)}let P=0,L=1,Z=0;for(this[f]=c&255;++P<m&&(L*=256);)c<0&&Z===0&&this[f+P-1]!==0&&(Z=1),this[f+P]=(c/L>>0)-Z&255;return f+m},a.prototype.writeIntBE=function(c,f,m,_){if(c=+c,f=f>>>0,!_){const ge=Math.pow(2,8*m-1);Ee(this,c,f,m,ge-1,-ge)}let P=m-1,L=1,Z=0;for(this[f+P]=c&255;--P>=0&&(L*=256);)c<0&&Z===0&&this[f+P+1]!==0&&(Z=1),this[f+P]=(c/L>>0)-Z&255;return f+m},a.prototype.writeInt8=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,1,127,-128),c<0&&(c=255+c+1),this[f]=c&255,f+1},a.prototype.writeInt16LE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,2,32767,-32768),this[f]=c&255,this[f+1]=c>>>8,f+2},a.prototype.writeInt16BE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,2,32767,-32768),this[f]=c>>>8,this[f+1]=c&255,f+2},a.prototype.writeInt32LE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,4,2147483647,-2147483648),this[f]=c&255,this[f+1]=c>>>8,this[f+2]=c>>>16,this[f+3]=c>>>24,f+4},a.prototype.writeInt32BE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,4,2147483647,-2147483648),c<0&&(c=4294967295+c+1),this[f]=c>>>24,this[f+1]=c>>>16,this[f+2]=c>>>8,this[f+3]=c&255,f+4},a.prototype.writeBigInt64LE=Je(function(c,f=0){return We(this,c,f,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Je(function(c,f=0){return Rt(this,c,f,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function yt(l,c,f,m,_,P){if(f+m>l.length)throw new RangeError("Index out of range");if(f<0)throw new RangeError("Index out of range")}function A(l,c,f,m,_){return c=+c,f=f>>>0,_||yt(l,c,f,4),r.write(l,c,f,m,23,4),f+4}a.prototype.writeFloatLE=function(c,f,m){return A(this,c,f,!0,m)},a.prototype.writeFloatBE=function(c,f,m){return A(this,c,f,!1,m)};function T(l,c,f,m,_){return c=+c,f=f>>>0,_||yt(l,c,f,8),r.write(l,c,f,m,52,8),f+8}a.prototype.writeDoubleLE=function(c,f,m){return T(this,c,f,!0,m)},a.prototype.writeDoubleBE=function(c,f,m){return T(this,c,f,!1,m)},a.prototype.copy=function(c,f,m,_){if(!a.isBuffer(c))throw new TypeError("argument should be a Buffer");if(m||(m=0),!_&&_!==0&&(_=this.length),f>=c.length&&(f=c.length),f||(f=0),_>0&&_<m&&(_=m),_===m||c.length===0||this.length===0)return 0;if(f<0)throw new RangeError("targetStart out of bounds");if(m<0||m>=this.length)throw new RangeError("Index out of range");if(_<0)throw new RangeError("sourceEnd out of bounds");_>this.length&&(_=this.length),c.length-f<_-m&&(_=c.length-f+m);const P=_-m;return this===c&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(f,m,_):Uint8Array.prototype.set.call(c,this.subarray(m,_),f),P},a.prototype.fill=function(c,f,m,_){if(typeof c=="string"){if(typeof f=="string"?(_=f,f=0,m=this.length):typeof m=="string"&&(_=m,m=this.length),_!==void 0&&typeof _!="string")throw new TypeError("encoding must be a string");if(typeof _=="string"&&!a.isEncoding(_))throw new TypeError("Unknown encoding: "+_);if(c.length===1){const L=c.charCodeAt(0);(_==="utf8"&&L<128||_==="latin1")&&(c=L)}}else typeof c=="number"?c=c&255:typeof c=="boolean"&&(c=Number(c));if(f<0||this.length<f||this.length<m)throw new RangeError("Out of range index");if(m<=f)return this;f=f>>>0,m=m===void 0?this.length:m>>>0,c||(c=0);let P;if(typeof c=="number")for(P=f;P<m;++P)this[P]=c;else{const L=a.isBuffer(c)?c:a.from(c,_),Z=L.length;if(Z===0)throw new TypeError('The value "'+c+'" is invalid for argument "value"');for(P=0;P<m-f;++P)this[P+f]=L[P%Z]}return this};const H={};function q(l,c,f){H[l]=class extends f{constructor(){super(),Object.defineProperty(this,"message",{value:c.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${l}]`,this.stack,delete this.name}get code(){return l}set code(_){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:_,writable:!0})}toString(){return`${this.name} [${l}]: ${this.message}`}}}q("ERR_BUFFER_OUT_OF_BOUNDS",function(l){return l?`${l} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),q("ERR_INVALID_ARG_TYPE",function(l,c){return`The "${l}" argument must be of type number. Received type ${typeof c}`},TypeError),q("ERR_OUT_OF_RANGE",function(l,c,f){let m=`The value of "${l}" is out of range.`,_=f;return Number.isInteger(f)&&Math.abs(f)>2**32?_=Y(String(f)):typeof f=="bigint"&&(_=String(f),(f>BigInt(2)**BigInt(32)||f<-(BigInt(2)**BigInt(32)))&&(_=Y(_)),_+="n"),m+=` It must be ${c}. Received ${_}`,m},RangeError);function Y(l){let c="",f=l.length;const m=l[0]==="-"?1:0;for(;f>=m+4;f-=3)c=`_${l.slice(f-3,f)}${c}`;return`${l.slice(0,f)}${c}`}function b(l,c,f){N(c,"offset"),(l[c]===void 0||l[c+f]===void 0)&&$(c,l.length-(f+1))}function w(l,c,f,m,_,P){if(l>f||l<c){const L=typeof c=="bigint"?"n":"";let Z;throw c===0||c===BigInt(0)?Z=`>= 0${L} and < 2${L} ** ${(P+1)*8}${L}`:Z=`>= -(2${L} ** ${(P+1)*8-1}${L}) and < 2 ** ${(P+1)*8-1}${L}`,new H.ERR_OUT_OF_RANGE("value",Z,l)}b(m,_,P)}function N(l,c){if(typeof l!="number")throw new H.ERR_INVALID_ARG_TYPE(c,"number",l)}function $(l,c,f){throw Math.floor(l)!==l?(N(l,f),new H.ERR_OUT_OF_RANGE("offset","an integer",l)):c<0?new H.ERR_BUFFER_OUT_OF_BOUNDS:new H.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${c}`,l)}const ye=/[^+/0-9A-Za-z-_]/g;function X(l){if(l=l.split("=")[0],l=l.trim().replace(ye,""),l.length<2)return"";for(;l.length%4!==0;)l=l+"=";return l}function ne(l,c){c=c||1/0;let f;const m=l.length;let _=null;const P=[];for(let L=0;L<m;++L){if(f=l.charCodeAt(L),f>55295&&f<57344){if(!_){if(f>56319){(c-=3)>-1&&P.push(239,191,189);continue}else if(L+1===m){(c-=3)>-1&&P.push(239,191,189);continue}_=f;continue}if(f<56320){(c-=3)>-1&&P.push(239,191,189),_=f;continue}f=(_-55296<<10|f-56320)+65536}else _&&(c-=3)>-1&&P.push(239,191,189);if(_=null,f<128){if((c-=1)<0)break;P.push(f)}else if(f<2048){if((c-=2)<0)break;P.push(f>>6|192,f&63|128)}else if(f<65536){if((c-=3)<0)break;P.push(f>>12|224,f>>6&63|128,f&63|128)}else if(f<1114112){if((c-=4)<0)break;P.push(f>>18|240,f>>12&63|128,f>>6&63|128,f&63|128)}else throw new Error("Invalid code point")}return P}function Ct(l){const c=[];for(let f=0;f<l.length;++f)c.push(l.charCodeAt(f)&255);return c}function br(l,c){let f,m,_;const P=[];for(let L=0;L<l.length&&!((c-=2)<0);++L)f=l.charCodeAt(L),m=f>>8,_=f%256,P.push(_),P.push(m);return P}function Gr(l){return t.toByteArray(X(l))}function wr(l,c,f,m){let _;for(_=0;_<m&&!(_+f>=c.length||_>=l.length);++_)c[_+f]=l[_];return _}function Ke(l,c){return l instanceof c||l!=null&&l.constructor!=null&&l.constructor.name!=null&&l.constructor.name===c.name}function Qt(l){return l!==l}const Vr=function(){const l="0123456789abcdef",c=new Array(256);for(let f=0;f<16;++f){const m=f*16;for(let _=0;_<16;++_)c[m+_]=l[f]+l[_]}return c}();function Je(l){return typeof BigInt>"u"?Zt:l}function Zt(){throw new Error("BigInt not supported")}})(It);var yn={Array:function(e){return e!=null&&e.constructor===Array},Boolean:function(e){return typeof e=="boolean"},Function:function(e){return typeof e=="function"},Nil:function(e){return e==null},Number:function(e){return typeof e=="number"},Object:function(e){return typeof e=="object"},String:function(e){return typeof e=="string"},"":function(){return!0}};yn.Null=yn.Nil;for(var io in yn)yn[io].toJSON=(function(e){return e}).bind(null,io);var Ps=yn,nr=Ps;function _a(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function Os(e){return nr.Nil(e)?"":_a(e.constructor)}function $f(e){return nr.Function(e)?"":nr.String(e)?JSON.stringify(e):e&&nr.Object(e)?"":e}function Rs(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function Zn(e){return nr.Function(e)?e.toJSON?e.toJSON():_a(e):nr.Array(e)?"Array":e&&nr.Object(e)?"Object":e!==void 0?e:""}function va(e,t,r){var n=$f(t);return"Expected "+Zn(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function At(e,t,r){r=r||Os(t),this.message=va(e,t,r),Rs(this,At),this.__type=e,this.__value=t,this.__valueTypeName=r}At.prototype=Object.create(Error.prototype);At.prototype.constructor=At;function jf(e,t,r,n,i){var s='" of type ';return t==="key"&&(s='" with key type '),va('property "'+Zn(r)+s+Zn(e),n,i)}function Br(e,t,r,n,i){e?(i=i||Os(n),this.message=jf(e,r,t,n,i)):this.message='Unexpected property "'+t+'"',Rs(this,At),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=i}Br.prototype=Object.create(Error.prototype);Br.prototype.constructor=At;function Gf(e,t){return new At(e,{},t)}function Vf(e,t,r){return e instanceof Br?(t=t+"."+e.__property,e=new Br(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof At&&(e=new Br(e.__type,t,r,e.__value,e.__valueTypeName)),Rs(e),e}var Ea={TfTypeError:At,TfPropertyTypeError:Br,tfCustomError:Gf,tfSubError:Vf,tfJSON:Zn,getValueTypeName:Os},Ni,so;function zf(){if(so)return Ni;so=1;var e=Ps,t=Ea;function r(E){return Buffer.isBuffer(E)}function n(E){return typeof E=="string"&&/^([0-9a-f]{2})+$/i.test(E)}function i(E,F){var D=E.toJSON();function O(K){if(!E(K))return!1;if(K.length===F)return!0;throw t.tfCustomError(D+"(Length: "+F+")",D+"(Length: "+K.length+")")}return O.toJSON=function(){return D},O}var s=i.bind(null,e.Array),o=i.bind(null,r),a=i.bind(null,n),u=i.bind(null,e.String);function d(E,F,D){D=D||e.Number;function O(K,C){return D(K,C)&&K>E&&K<F}return O.toJSON=function(){return`${D.toJSON()} between [${E}, ${F}]`},O}var h=Math.pow(2,53)-1;function y(E){return typeof E=="number"&&isFinite(E)}function v(E){return E<<24>>24===E}function p(E){return E<<16>>16===E}function I(E){return(E|0)===E}function k(E){return typeof E=="number"&&E>=-h&&E<=h&&Math.floor(E)===E}function B(E){return(E&255)===E}function R(E){return(E&65535)===E}function U(E){return E>>>0===E}function x(E){return typeof E=="number"&&E>=0&&E<=h&&Math.floor(E)===E}var g={ArrayN:s,Buffer:r,BufferN:o,Finite:y,Hex:n,HexN:a,Int8:v,Int16:p,Int32:I,Int53:k,Range:d,StringN:u,UInt8:B,UInt16:R,UInt32:U,UInt53:x};for(var S in g)g[S].toJSON=(function(E){return E}).bind(null,S);return Ni=g,Ni}var gn=Ea,Ie=Ps,mt=gn.tfJSON,xa=gn.TfTypeError,Sa=gn.TfPropertyTypeError,zr=gn.tfSubError,qf=gn.getValueTypeName,Et={arrayOf:function(t,r){t=lt(t),r=r||{};function n(i,s){return!Ie.Array(i)||Ie.Nil(i)||r.minLength!==void 0&&i.length<r.minLength||r.maxLength!==void 0&&i.length>r.maxLength||r.length!==void 0&&i.length!==r.length?!1:i.every(function(o,a){try{return Ge(t,o,s)}catch(u){throw zr(u,a)}})}return n.toJSON=function(){var i="["+mt(t)+"]";return r.length!==void 0?i+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(i+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),i},n},maybe:function e(t){t=lt(t);function r(n,i){return Ie.Nil(n)||t(n,i,e)}return r.toJSON=function(){return"?"+mt(t)},r},map:function(t,r){t=lt(t),r&&(r=lt(r));function n(i,s){if(!Ie.Object(i)||Ie.Nil(i))return!1;for(var o in i){try{r&&Ge(r,o,s)}catch(u){throw zr(u,o,"key")}try{var a=i[o];Ge(t,a,s)}catch(u){throw zr(u,o)}}return!0}return r?n.toJSON=function(){return"{"+mt(r)+": "+mt(t)+"}"}:n.toJSON=function(){return"{"+mt(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=lt(t[n]);function i(s,o){if(!Ie.Object(s)||Ie.Nil(s))return!1;var a;try{for(a in r){var u=r[a],d=s[a];Ge(u,d,o)}}catch(h){throw zr(h,a)}if(o){for(a in s)if(!r[a])throw new Sa(void 0,a)}return!0}return i.toJSON=function(){return mt(r)},i},anyOf:function(){var t=[].slice.call(arguments).map(lt);function r(n,i){return t.some(function(s){try{return Ge(s,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(mt).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(lt);function r(n,i){return t.every(function(s){try{return Ge(s,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(mt).join(" & ")},r},quacksLike:function(t){function r(n){return t===qf(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(lt);function r(n,i){return Ie.Nil(n)||Ie.Nil(n.length)||i&&n.length!==t.length?!1:t.every(function(s,o){try{return Ge(s,n[o],i)}catch(a){throw zr(a,o)}})}return r.toJSON=function(){return"("+t.map(mt).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};Et.oneOf=Et.anyOf;function lt(e){if(Ie.String(e))return e[0]==="?"?Et.maybe(e.slice(1)):Ie[e]||Et.quacksLike(e);if(e&&Ie.Object(e)){if(Ie.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return Et.arrayOf(e[0])}return Et.object(e)}else if(Ie.Function(e))return e;return Et.value(e)}function Ge(e,t,r,n){if(Ie.Function(e)){if(e(t,r))return!0;throw new xa(n||e,t)}return Ge(lt(e),t,r)}for(var Gt in Ie)Ge[Gt]=Ie[Gt];for(Gt in Et)Ge[Gt]=Et[Gt];var oo=zf();for(Gt in oo)Ge[Gt]=oo[Gt];Ge.compile=lt;Ge.TfTypeError=xa;Ge.TfPropertyTypeError=Sa;var Ta=Ge;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.oneOf=e.Null=e.BufferN=e.Function=e.UInt32=e.UInt8=e.tuple=e.maybe=e.Hex=e.Buffer=e.String=e.Boolean=e.Array=e.Number=e.Hash256bit=e.Hash160bit=e.Buffer256bit=e.isTaptree=e.isTapleaf=e.TAPLEAF_VERSION_MASK=e.Satoshi=e.isPoint=e.stacksEqual=e.typeforce=void 0;const t=It;e.typeforce=Ta;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(h,y){return h.length!==y.length?!1:h.every((v,p)=>v.equals(y[p]))}e.stacksEqual=i;function s(h){if(!t.Buffer.isBuffer(h)||h.length<33)return!1;const y=h[0],v=h.slice(1,33);if(v.compare(r)===0||v.compare(n)>=0)return!1;if((y===2||y===3)&&h.length===33)return!0;const p=h.slice(33);return p.compare(r)===0||p.compare(n)>=0?!1:y===4&&h.length===65}e.isPoint=s;const o=21*1e14;function a(h){return e.typeforce.UInt53(h)&&h<=o}e.Satoshi=a,e.TAPLEAF_VERSION_MASK=254;function u(h){return!h||!("output"in h)||!t.Buffer.isBuffer(h.output)?!1:h.version!==void 0?(h.version&e.TAPLEAF_VERSION_MASK)===h.version:!0}e.isTapleaf=u;function d(h){return(0,e.Array)(h)?h.length!==2?!1:h.every(y=>d(y)):u(h)}e.isTaptree=d,e.Buffer256bit=e.typeforce.BufferN(32),e.Hash160bit=e.typeforce.BufferN(20),e.Hash256bit=e.typeforce.BufferN(32),e.Number=e.typeforce.Number,e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.String=e.typeforce.String,e.Buffer=e.typeforce.Buffer,e.Hex=e.typeforce.Hex,e.maybe=e.typeforce.maybe,e.tuple=e.typeforce.tuple,e.UInt8=e.typeforce.UInt8,e.UInt32=e.typeforce.UInt32,e.Function=e.typeforce.Function,e.BufferN=e.typeforce.BufferN,e.Null=e.typeforce.Null,e.oneOf=e.typeforce.oneOf})(Fe);var _n={},Pe={};Object.defineProperty(Pe,"__esModule",{value:!0});Pe.BufferReader=Pe.BufferWriter=Pe.cloneBuffer=Pe.reverseBuffer=Pe.writeUInt64LE=Pe.readUInt64LE=Pe.varuint=void 0;const ir=Fe,{typeforce:Aa}=ir,mn=pa;Pe.varuint=mn;function ka(e,t){if(typeof e!="number")throw new Error("cannot write a non-number as a number");if(e<0)throw new Error("specified a negative value for writing an unsigned value");if(e>t)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function Ba(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,ka(n+r,9007199254740991),n+r}Pe.readUInt64LE=Ba;function Ia(e,t,r){return ka(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}Pe.writeUInt64LE=Ia;function Wf(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;n<e.length/2;n++)r=e[n],e[n]=e[t],e[t]=r,t--;return e}Pe.reverseBuffer=Wf;function Kf(e){const t=Buffer.allocUnsafe(e.length);return e.copy(t),t}Pe.cloneBuffer=Kf;class Cs{static withCapacity(t){return new Cs(Buffer.alloc(t))}constructor(t,r=0){this.buffer=t,this.offset=r,Aa(ir.tuple(ir.Buffer,ir.UInt32),[t,r])}writeUInt8(t){this.offset=this.buffer.writeUInt8(t,this.offset)}writeInt32(t){this.offset=this.buffer.writeInt32LE(t,this.offset)}writeUInt32(t){this.offset=this.buffer.writeUInt32LE(t,this.offset)}writeUInt64(t){this.offset=Ia(this.buffer,t,this.offset)}writeVarInt(t){mn.encode(t,this.buffer,this.offset),this.offset+=mn.encode.bytes}writeSlice(t){if(this.buffer.length<this.offset+t.length)throw new Error("Cannot write slice out of bounds");this.offset+=t.copy(this.buffer,this.offset)}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}writeVector(t){this.writeVarInt(t.length),t.forEach(r=>this.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}Pe.BufferWriter=Cs;class Yf{constructor(t,r=0){this.buffer=t,this.offset=r,Aa(ir.tuple(ir.Buffer,ir.UInt32),[t,r])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=Ba(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=mn.decode(this.buffer,this.offset);return this.offset+=mn.decode.bytes,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const t=this.readVarInt(),r=[];for(let n=0;n<t;n++)r.push(this.readVarSlice());return r}}Pe.BufferReader=Yf;var Wt={},Cr={},Pt={},Kt={};Object.defineProperty(Kt,"__esModule",{value:!0});Kt.anumber=hs;Kt.abytes=Pa;Kt.ahash=Jf;Kt.aexists=Qf;Kt.aoutput=Zf;function hs(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Xf(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Pa(e,...t){if(!Xf(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Jf(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");hs(e.outputLen),hs(e.blockLen)}function Qf(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Zf(e,t){Pa(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}var vn={},fi={};Object.defineProperty(fi,"__esModule",{value:!0});fi.crypto=void 0;fi.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(e){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(e,"__esModule",{value:!0}),e.Hash=e.nextTick=e.byteSwapIfBE=e.isLE=void 0,e.isBytes=n,e.u8=i,e.u32=s,e.createView=o,e.rotr=a,e.rotl=u,e.byteSwap=d,e.byteSwap32=h,e.bytesToHex=v,e.hexToBytes=k,e.asyncLoop=R,e.utf8ToBytes=U,e.toBytes=x,e.concatBytes=g,e.checkOpts=E,e.wrapConstructor=F,e.wrapConstructorWithOpts=D,e.wrapXOFConstructorWithOpts=O,e.randomBytes=K;const t=fi,r=Kt;function n(C){return C instanceof Uint8Array||ArrayBuffer.isView(C)&&C.constructor.name==="Uint8Array"}function i(C){return new Uint8Array(C.buffer,C.byteOffset,C.byteLength)}function s(C){return new Uint32Array(C.buffer,C.byteOffset,Math.floor(C.byteLength/4))}function o(C){return new DataView(C.buffer,C.byteOffset,C.byteLength)}function a(C,G){return C<<32-G|C>>>G}function u(C,G){return C<<G|C>>>32-G>>>0}e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function d(C){return C<<24&4278190080|C<<8&16711680|C>>>8&65280|C>>>24&255}e.byteSwapIfBE=e.isLE?C=>C:C=>d(C);function h(C){for(let G=0;G<C.length;G++)C[G]=d(C[G])}const y=Array.from({length:256},(C,G)=>G.toString(16).padStart(2,"0"));function v(C){(0,r.abytes)(C);let G="";for(let V=0;V<C.length;V++)G+=y[C[V]];return G}const p={_0:48,_9:57,A:65,F:70,a:97,f:102};function I(C){if(C>=p._0&&C<=p._9)return C-p._0;if(C>=p.A&&C<=p.F)return C-(p.A-10);if(C>=p.a&&C<=p.f)return C-(p.a-10)}function k(C){if(typeof C!="string")throw new Error("hex string expected, got "+typeof C);const G=C.length,V=G/2;if(G%2)throw new Error("hex string expected, got unpadded hex of length "+G);const z=new Uint8Array(V);for(let ee=0,ve=0;ee<V;ee++,ve+=2){const ze=I(C.charCodeAt(ve)),rt=I(C.charCodeAt(ve+1));if(ze===void 0||rt===void 0){const qe=C[ve]+C[ve+1];throw new Error('hex string expected, got non-hex character "'+qe+'" at index '+ve)}z[ee]=ze*16+rt}return z}const B=async()=>{};e.nextTick=B;async function R(C,G,V){let z=Date.now();for(let ee=0;ee<C;ee++){V(ee);const ve=Date.now()-z;ve>=0&&ve<G||(await(0,e.nextTick)(),z+=ve)}}function U(C){if(typeof C!="string")throw new Error("utf8ToBytes expected string, got "+typeof C);return new Uint8Array(new TextEncoder().encode(C))}function x(C){return typeof C=="string"&&(C=U(C)),(0,r.abytes)(C),C}function g(...C){let G=0;for(let z=0;z<C.length;z++){const ee=C[z];(0,r.abytes)(ee),G+=ee.length}const V=new Uint8Array(G);for(let z=0,ee=0;z<C.length;z++){const ve=C[z];V.set(ve,ee),ee+=ve.length}return V}class S{clone(){return this._cloneInto()}}e.Hash=S;function E(C,G){if(G!==void 0&&{}.toString.call(G)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(C,G)}function F(C){const G=z=>C().update(x(z)).digest(),V=C();return G.outputLen=V.outputLen,G.blockLen=V.blockLen,G.create=()=>C(),G}function D(C){const G=(z,ee)=>C(ee).update(x(z)).digest(),V=C({});return G.outputLen=V.outputLen,G.blockLen=V.blockLen,G.create=z=>C(z),G}function O(C){const G=(z,ee)=>C(ee).update(x(z)).digest(),V=C({});return G.outputLen=V.outputLen,G.blockLen=V.blockLen,G.create=z=>C(z),G}function K(C=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(C));if(t.crypto&&typeof t.crypto.randomBytes=="function")return t.crypto.randomBytes(C);throw new Error("crypto.getRandomValues must be defined")}})(vn);Object.defineProperty(Pt,"__esModule",{value:!0});Pt.HashMD=void 0;Pt.setBigUint64=Oa;Pt.Chi=eu;Pt.Maj=tu;const Hi=Kt,qr=vn;function Oa(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),u=n?4:0,d=n?0:4;e.setUint32(t+u,o,n),e.setUint32(t+d,a,n)}function eu(e,t,r){return e&t^~e&r}function tu(e,t,r){return e&t^e&r^t&r}class ru extends qr.Hash{constructor(t,r,n,i){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=(0,qr.createView)(this.buffer)}update(t){(0,Hi.aexists)(this);const{view:r,buffer:n,blockLen:i}=this;t=(0,qr.toBytes)(t);const s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const u=(0,qr.createView)(t);for(;i<=s-o;o+=i)this.process(u,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){(0,Hi.aexists)(this),(0,Hi.aoutput)(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(n,0),o=0);for(let y=o;y<i;y++)r[y]=0;Oa(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=(0,qr.createView)(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const d=u/4,h=this.get();if(d>h.length)throw new Error("_sha2: outputLen bigger than state");for(let y=0;y<d;y++)a.setUint32(4*y,h[y],s)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return t.length=i,t.pos=a,t.finished=s,t.destroyed=o,i%r&&t.buffer.set(n),t}}Pt.HashMD=ru;Object.defineProperty(Cr,"__esModule",{value:!0});Cr.ripemd160=Cr.RIPEMD160=void 0;const nu=Pt,an=vn,iu=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ra=new Uint8Array(new Array(16).fill(0).map((e,t)=>t)),su=Ra.map(e=>(9*e+5)%16);let Us=[Ra],Ls=[su];for(let e=0;e<4;e++)for(let t of[Us,Ls])t.push(t[e].map(r=>iu[r]));const Ca=[[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(e=>new Uint8Array(e)),ou=Us.map((e,t)=>e.map(r=>Ca[t][r])),au=Ls.map((e,t)=>e.map(r=>Ca[t][r])),cu=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),fu=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function ao(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const Rn=new Uint32Array(16);let Ua=class extends nu.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:r,h2:n,h3:i,h4:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=s|0}process(t,r){for(let p=0;p<16;p++,r+=4)Rn[p]=t.getUint32(r,!0);let n=this.h0|0,i=n,s=this.h1|0,o=s,a=this.h2|0,u=a,d=this.h3|0,h=d,y=this.h4|0,v=y;for(let p=0;p<5;p++){const I=4-p,k=cu[p],B=fu[p],R=Us[p],U=Ls[p],x=ou[p],g=au[p];for(let S=0;S<16;S++){const E=(0,an.rotl)(n+ao(p,s,a,d)+Rn[R[S]]+k,x[S])+y|0;n=y,y=d,d=(0,an.rotl)(a,10)|0,a=s,s=E}for(let S=0;S<16;S++){const E=(0,an.rotl)(i+ao(I,o,u,h)+Rn[U[S]]+B,g[S])+v|0;i=v,v=h,h=(0,an.rotl)(u,10)|0,u=o,o=E}}this.set(this.h1+a+h|0,this.h2+d+v|0,this.h3+y+i|0,this.h4+n+o|0,this.h0+s+u|0)}roundClean(){Rn.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}};Cr.RIPEMD160=Ua;Cr.ripemd160=(0,an.wrapConstructor)(()=>new Ua);var Ur={};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.sha1=Ur.SHA1=void 0;const Fi=Pt,zn=vn,Wr=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),Ut=new Uint32Array(80);class La extends Fi.HashMD{constructor(){super(64,20,8,!1),this.A=Wr[0]|0,this.B=Wr[1]|0,this.C=Wr[2]|0,this.D=Wr[3]|0,this.E=Wr[4]|0}get(){const{A:t,B:r,C:n,D:i,E:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0}process(t,r){for(let u=0;u<16;u++,r+=4)Ut[u]=t.getUint32(r,!1);for(let u=16;u<80;u++)Ut[u]=(0,zn.rotl)(Ut[u-3]^Ut[u-8]^Ut[u-14]^Ut[u-16],1);let{A:n,B:i,C:s,D:o,E:a}=this;for(let u=0;u<80;u++){let d,h;u<20?(d=(0,Fi.Chi)(i,s,o),h=1518500249):u<40?(d=i^s^o,h=1859775393):u<60?(d=(0,Fi.Maj)(i,s,o),h=2400959708):(d=i^s^o,h=3395469782);const y=(0,zn.rotl)(n,5)+d+a+h+Ut[u]|0;a=o,o=s,s=(0,zn.rotl)(i,30),i=n,n=y}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,this.set(n,i,s,o,a)}roundClean(){Ut.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}}Ur.SHA1=La;Ur.sha1=(0,zn.wrapConstructor)(()=>new La);var St={};Object.defineProperty(St,"__esModule",{value:!0});St.sha224=Na=St.sha256=St.SHA256=void 0;const Mi=Pt,Ze=vn,uu=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Lt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Nt=new Uint32Array(64);class Ns extends Mi.HashMD{constructor(){super(64,32,8,!1),this.A=Lt[0]|0,this.B=Lt[1]|0,this.C=Lt[2]|0,this.D=Lt[3]|0,this.E=Lt[4]|0,this.F=Lt[5]|0,this.G=Lt[6]|0,this.H=Lt[7]|0}get(){const{A:t,B:r,C:n,D:i,E:s,F:o,G:a,H:u}=this;return[t,r,n,i,s,o,a,u]}set(t,r,n,i,s,o,a,u){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=u|0}process(t,r){for(let y=0;y<16;y++,r+=4)Nt[y]=t.getUint32(r,!1);for(let y=16;y<64;y++){const v=Nt[y-15],p=Nt[y-2],I=(0,Ze.rotr)(v,7)^(0,Ze.rotr)(v,18)^v>>>3,k=(0,Ze.rotr)(p,17)^(0,Ze.rotr)(p,19)^p>>>10;Nt[y]=k+Nt[y-7]+I+Nt[y-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:u,G:d,H:h}=this;for(let y=0;y<64;y++){const v=(0,Ze.rotr)(a,6)^(0,Ze.rotr)(a,11)^(0,Ze.rotr)(a,25),p=h+v+(0,Mi.Chi)(a,u,d)+uu[y]+Nt[y]|0,k=((0,Ze.rotr)(n,2)^(0,Ze.rotr)(n,13)^(0,Ze.rotr)(n,22))+(0,Mi.Maj)(n,i,s)|0;h=d,d=u,u=a,a=o+p|0,o=s,s=i,i=n,n=p+k|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,u=u+this.F|0,d=d+this.G|0,h=h+this.H|0,this.set(n,i,s,o,a,u,d,h)}roundClean(){Nt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}St.SHA256=Ns;class lu extends Ns{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}var Na=St.sha256=(0,Ze.wrapConstructor)(()=>new Ns);St.sha224=(0,Ze.wrapConstructor)(()=>new lu);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.taggedHash=e.TAGGED_HASH_PREFIXES=e.TAGS=e.hash256=e.hash160=e.sha256=e.sha1=e.ripemd160=void 0;const t=Cr,r=Ur,n=St;function i(h){return Buffer.from((0,t.ripemd160)(Uint8Array.from(h)))}e.ripemd160=i;function s(h){return Buffer.from((0,r.sha1)(Uint8Array.from(h)))}e.sha1=s;function o(h){return Buffer.from((0,n.sha256)(Uint8Array.from(h)))}e.sha256=o;function a(h){return Buffer.from((0,t.ripemd160)((0,n.sha256)(Uint8Array.from(h))))}e.hash160=a;function u(h){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(h))))}e.hash256=u,e.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],e.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function d(h,y){return o(Buffer.concat([e.TAGGED_HASH_PREFIXES[h],y]))}e.taggedHash=d})(Wt);var Di={},Tt={};Object.defineProperty(Tt,"__esModule",{value:!0});Tt.encode=Tt.decode=Tt.check=void 0;function du(e){if(e.length<8||e.length>72||e[0]!==48||e[1]!==e.length-2||e[2]!==2)return!1;const t=e[3];if(t===0||5+t>=e.length||e[4+t]!==2)return!1;const r=e[5+t];return!(r===0||6+t+r!==e.length||e[4]&128||t>1&&e[4]===0&&!(e[5]&128)||e[t+6]&128||r>1&&e[t+6]===0&&!(e[t+7]&128))}Tt.check=du;function hu(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(e[0]!==48)throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(e[2]!==2)throw new Error("Expected DER integer");const t=e[3];if(t===0)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(e[4+t]!==2)throw new Error("Expected DER integer (2)");const r=e[5+t];if(r===0)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(e[4]&128)throw new Error("R value is negative");if(t>1&&e[4]===0&&!(e[5]&128))throw new Error("R value excessively padded");if(e[t+6]&128)throw new Error("S value is negative");if(r>1&&e[t+6]===0&&!(e[t+7]&128))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}}Tt.decode=hu;function pu(e,t){const r=e.length,n=t.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(e[0]&128)throw new Error("R value is negative");if(t[0]&128)throw new Error("S value is negative");if(r>1&&e[0]===0&&!(e[1]&128))throw new Error("R value excessively padded");if(n>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");const i=Buffer.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=e.length,e.copy(i,4),i[4+r]=2,i[5+r]=t.length,t.copy(i,6+r),i}Tt.encode=pu;var or={};Object.defineProperty(or,"__esModule",{value:!0});or.REVERSE_OPS=or.OPS=void 0;const ps={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_CHECKSIGADD:186,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};or.OPS=ps;const Ha={};or.REVERSE_OPS=Ha;for(const e of Object.keys(ps)){const t=ps[e];Ha[t]=e}var Vt={};Object.defineProperty(Vt,"__esModule",{value:!0});Vt.decode=Vt.encode=Vt.encodingLength=void 0;const jt=or;function Fa(e){return e<jt.OPS.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}Vt.encodingLength=Fa;function yu(e,t,r){const n=Fa(t);return n===1?e.writeUInt8(t,r):n===2?(e.writeUInt8(jt.OPS.OP_PUSHDATA1,r),e.writeUInt8(t,r+1)):n===3?(e.writeUInt8(jt.OPS.OP_PUSHDATA2,r),e.writeUInt16LE(t,r+1)):(e.writeUInt8(jt.OPS.OP_PUSHDATA4,r),e.writeUInt32LE(t,r+1)),n}Vt.encode=yu;function mu(e,t){const r=e.readUInt8(t);let n,i;if(r<jt.OPS.OP_PUSHDATA1)n=r,i=1;else if(r===jt.OPS.OP_PUSHDATA1){if(t+2>e.length)return null;n=e.readUInt8(t+1),i=2}else if(r===jt.OPS.OP_PUSHDATA2){if(t+3>e.length)return null;n=e.readUInt16LE(t+1),i=3}else{if(t+5>e.length)return null;if(r!==jt.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=e.readUInt32LE(t+1),i=5}return{opcode:r,number:n,size:i}}Vt.decode=mu;var Lr={};Object.defineProperty(Lr,"__esModule",{value:!0});Lr.encode=Lr.decode=void 0;function bu(e,t,r){t=t||4,r=r===void 0?!0:r;const n=e.length;if(n===0)return 0;if(n>t)throw new TypeError("Script number overflow");if(r&&!(e[n-1]&127)&&(n<=1||!(e[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const s=e.readUInt32LE(0),o=e.readUInt8(4);return o&128?-((o&-129)*4294967296+s):o*4294967296+s}let i=0;for(let s=0;s<n;++s)i|=e[s]<<8*s;return e[n-1]&128?-(i&~(128<<8*(n-1))):i}Lr.decode=bu;function wu(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function gu(e){let t=Math.abs(e);const r=wu(t),n=Buffer.allocUnsafe(r),i=e<0;for(let s=0;s<r;++s)n.writeUInt8(t&255,s),t>>=8;return n[r-1]&128?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n}Lr.encode=gu;var tr={},co;function _u(){if(co)return tr;co=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.encode=tr.decode=void 0;const e=Tt,t=Xe(),r=Fe,{typeforce:n}=r,i=Buffer.alloc(1,0);function s(d){let h=0;for(;d[h]===0;)++h;return h===d.length?i:(d=d.slice(h),d[0]&128?Buffer.concat([i,d],1+d.length):d)}function o(d){d[0]===0&&(d=d.slice(1));const h=Buffer.alloc(32,0),y=Math.max(0,32-d.length);return d.copy(h,y),h}function a(d){const h=d.readUInt8(d.length-1);if(!(0,t.isDefinedHashType)(h))throw new Error("Invalid hashType "+h);const y=e.decode(d.slice(0,-1)),v=o(y.r),p=o(y.s);return{signature:Buffer.concat([v,p],64),hashType:h}}tr.decode=a;function u(d,h){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:d,hashType:h}),!(0,t.isDefinedHashType)(h))throw new Error("Invalid hashType "+h);const y=Buffer.allocUnsafe(1);y.writeUInt8(h,0);const v=s(d.slice(0,32)),p=s(d.slice(32,64));return Buffer.concat([e.encode(v,p),y])}return tr.encode=u,tr}var fo;function Xe(){return fo||(fo=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.signature=e.number=e.isCanonicalScriptSignature=e.isDefinedHashType=e.isCanonicalPubKey=e.toStack=e.fromASM=e.toASM=e.decompile=e.compile=e.countNonPushOnlyOPs=e.isPushOnly=e.OPS=void 0;const t=Tt,r=or;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=Vt,i=Lr,s=_u(),o=Fe,{typeforce:a}=o,u=r.OPS.OP_RESERVED;function d(O){return o.Number(O)&&(O===r.OPS.OP_0||O>=r.OPS.OP_1&&O<=r.OPS.OP_16||O===r.OPS.OP_1NEGATE)}function h(O){return o.Buffer(O)||d(O)}function y(O){return o.Array(O)&&O.every(h)}e.isPushOnly=y;function v(O){return O.length-O.filter(h).length}e.countNonPushOnlyOPs=v;function p(O){if(O.length===0)return r.OPS.OP_0;if(O.length===1){if(O[0]>=1&&O[0]<=16)return u+O[0];if(O[0]===129)return r.OPS.OP_1NEGATE}}function I(O){return Buffer.isBuffer(O)}function k(O){return o.Array(O)}function B(O){return Buffer.isBuffer(O)}function R(O){if(I(O))return O;a(o.Array,O);const K=O.reduce((V,z)=>B(z)?z.length===1&&p(z)!==void 0?V+1:V+n.encodingLength(z.length)+z.length:V+1,0),C=Buffer.allocUnsafe(K);let G=0;if(O.forEach(V=>{if(B(V)){const z=p(V);if(z!==void 0){C.writeUInt8(z,G),G+=1;return}G+=n.encode(C,V.length,G),V.copy(C,G),G+=V.length}else C.writeUInt8(V,G),G+=1}),G!==C.length)throw new Error("Could not decode chunks");return C}e.compile=R;function U(O){if(k(O))return O;a(o.Buffer,O);const K=[];let C=0;for(;C<O.length;){const G=O[C];if(G>r.OPS.OP_0&&G<=r.OPS.OP_PUSHDATA4){const V=n.decode(O,C);if(V===null||(C+=V.size,C+V.number>O.length))return null;const z=O.slice(C,C+V.number);C+=V.number;const ee=p(z);ee!==void 0?K.push(ee):K.push(z)}else K.push(G),C+=1}return K}e.decompile=U;function x(O){if(I(O)&&(O=U(O)),!O)throw new Error("Could not convert invalid chunks to ASM");return O.map(K=>{if(B(K)){const C=p(K);if(C===void 0)return K.toString("hex");K=C}return r.REVERSE_OPS[K]}).join(" ")}e.toASM=x;function g(O){return a(o.String,O),R(O.split(" ").map(K=>r.OPS[K]!==void 0?r.OPS[K]:(a(o.Hex,K),Buffer.from(K,"hex"))))}e.fromASM=g;function S(O){return O=U(O),a(y,O),O.map(K=>B(K)?K:K===r.OPS.OP_0?Buffer.allocUnsafe(0):i.encode(K-u))}e.toStack=S;function E(O){return o.isPoint(O)}e.isCanonicalPubKey=E;function F(O){const K=O&-129;return K>0&&K<4}e.isDefinedHashType=F;function D(O){return!Buffer.isBuffer(O)||!F(O[O.length-1])?!1:t.check(O.slice(0,-1))}e.isCanonicalScriptSignature=D,e.number=i,e.signature=s}(Di)),Di}Object.defineProperty(_n,"__esModule",{value:!0});_n.Transaction=void 0;const Se=Pe,Me=Wt,uo=Xe(),vu=Xe(),te=Fe,{typeforce:ot}=te;function ft(e){const t=e.length;return Se.varuint.encodingLength(t)+t}function Eu(e){const t=e.length;return Se.varuint.encodingLength(t)+e.reduce((r,n)=>r+ft(n),0)}const $t=Buffer.allocUnsafe(0),$i=[],ji=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),lo=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),xu=Buffer.from("ffffffffffffffff","hex"),Su={script:$t,valueBuffer:xu};function Tu(e){return e.value!==void 0}class J{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new Se.BufferReader(t),i=new J;i.version=n.readInt32();const s=n.readUInt8(),o=n.readUInt8();let a=!1;s===J.ADVANCED_TRANSACTION_MARKER&&o===J.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const u=n.readVarInt();for(let h=0;h<u;++h)i.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:$i});const d=n.readVarInt();for(let h=0;h<d;++h)i.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let h=0;h<u;++h)i.ins[h].witness=n.readVector();if(!i.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(i.locktime=n.readUInt32(),r)return i;if(n.offset!==t.length)throw new Error("Transaction has unexpected data");return i}static fromHex(t){return J.fromBuffer(Buffer.from(t,"hex"),!1)}static isCoinbaseHash(t){ot(te.Hash256bit,t);for(let r=0;r<32;++r)if(t[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&J.isCoinbaseHash(this.ins[0].hash)}addInput(t,r,n,i){return ot(te.tuple(te.Hash256bit,te.UInt32,te.maybe(te.UInt32),te.maybe(te.Buffer)),arguments),te.Null(n)&&(n=J.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:r,script:i||$t,sequence:n,witness:$i})-1}addOutput(t,r){return ot(te.tuple(te.Buffer,te.Satoshi),arguments),this.outs.push({script:t,value:r})-1}hasWitnesses(){return this.ins.some(t=>t.witness.length!==0)}stripWitnesses(){this.ins.forEach(t=>{t.witness=$i})}weight(){const t=this.byteLength(!1),r=this.byteLength(!0);return t*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const r=t&&this.hasWitnesses();return(r?10:8)+Se.varuint.encodingLength(this.ins.length)+Se.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,i)=>n+40+ft(i.script),0)+this.outs.reduce((n,i)=>n+8+ft(i.script),0)+(r?this.ins.reduce((n,i)=>n+Eu(i.witness),0):0)}clone(){const t=new J;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),t.outs=this.outs.map(r=>({script:r.script,value:r.value})),t}hashForSignature(t,r,n){if(ot(te.tuple(te.UInt32,te.Buffer,te.Number),arguments),t>=this.ins.length)return lo;const i=uo.compile(uo.decompile(r).filter(a=>a!==vu.OPS.OP_CODESEPARATOR)),s=this.clone();if((n&31)===J.SIGHASH_NONE)s.outs=[],s.ins.forEach((a,u)=>{u!==t&&(a.sequence=0)});else if((n&31)===J.SIGHASH_SINGLE){if(t>=this.outs.length)return lo;s.outs.length=t+1;for(let a=0;a<t;a++)s.outs[a]=Su;s.ins.forEach((a,u)=>{u!==t&&(a.sequence=0)})}n&J.SIGHASH_ANYONECANPAY?(s.ins=[s.ins[t]],s.ins[0].script=i):(s.ins.forEach(a=>{a.script=$t}),s.ins[t].script=i);const o=Buffer.allocUnsafe(s.byteLength(!1)+4);return o.writeInt32LE(n,o.length-4),s.__toBuffer(o,0,!1),Me.hash256(o)}hashForWitnessV1(t,r,n,i,s,o){if(ot(te.tuple(te.UInt32,ot.arrayOf(te.Buffer),ot.arrayOf(te.Satoshi),te.UInt32),arguments),n.length!==this.ins.length||r.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const a=i===J.SIGHASH_DEFAULT?J.SIGHASH_ALL:i&J.SIGHASH_OUTPUT_MASK,d=(i&J.SIGHASH_INPUT_MASK)===J.SIGHASH_ANYONECANPAY,h=a===J.SIGHASH_NONE,y=a===J.SIGHASH_SINGLE;let v=$t,p=$t,I=$t,k=$t,B=$t;if(!d){let g=Se.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(S=>{g.writeSlice(S.hash),g.writeUInt32(S.index)}),v=Me.sha256(g.end()),g=Se.BufferWriter.withCapacity(8*this.ins.length),n.forEach(S=>g.writeUInt64(S)),p=Me.sha256(g.end()),g=Se.BufferWriter.withCapacity(r.map(ft).reduce((S,E)=>S+E)),r.forEach(S=>g.writeVarSlice(S)),I=Me.sha256(g.end()),g=Se.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(S=>g.writeUInt32(S.sequence)),k=Me.sha256(g.end())}if(h||y){if(y&&t<this.outs.length){const g=this.outs[t],S=Se.BufferWriter.withCapacity(8+ft(g.script));S.writeUInt64(g.value),S.writeVarSlice(g.script),B=Me.sha256(S.end())}}else{const g=this.outs.map(E=>8+ft(E.script)).reduce((E,F)=>E+F),S=Se.BufferWriter.withCapacity(g);this.outs.forEach(E=>{S.writeUInt64(E.value),S.writeVarSlice(E.script)}),B=Me.sha256(S.end())}const R=(s?2:0)+(o?1:0),U=174-(d?49:0)-(h?32:0)+(o?32:0)+(s?37:0),x=Se.BufferWriter.withCapacity(U);if(x.writeUInt8(i),x.writeInt32(this.version),x.writeUInt32(this.locktime),x.writeSlice(v),x.writeSlice(p),x.writeSlice(I),x.writeSlice(k),h||y||x.writeSlice(B),x.writeUInt8(R),d){const g=this.ins[t];x.writeSlice(g.hash),x.writeUInt32(g.index),x.writeUInt64(n[t]),x.writeVarSlice(r[t]),x.writeUInt32(g.sequence)}else x.writeUInt32(t);if(o){const g=Se.BufferWriter.withCapacity(ft(o));g.writeVarSlice(o),x.writeSlice(Me.sha256(g.end()))}return y&&x.writeSlice(B),s&&(x.writeSlice(s),x.writeUInt8(0),x.writeUInt32(4294967295)),Me.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),x.end()]))}hashForWitnessV0(t,r,n,i){ot(te.tuple(te.UInt32,te.Buffer,te.Satoshi,te.UInt32),arguments);let s=Buffer.from([]),o,a=ji,u=ji,d=ji;if(i&J.SIGHASH_ANYONECANPAY||(s=Buffer.allocUnsafe(36*this.ins.length),o=new Se.BufferWriter(s,0),this.ins.forEach(y=>{o.writeSlice(y.hash),o.writeUInt32(y.index)}),u=Me.hash256(s)),!(i&J.SIGHASH_ANYONECANPAY)&&(i&31)!==J.SIGHASH_SINGLE&&(i&31)!==J.SIGHASH_NONE&&(s=Buffer.allocUnsafe(4*this.ins.length),o=new Se.BufferWriter(s,0),this.ins.forEach(y=>{o.writeUInt32(y.sequence)}),d=Me.hash256(s)),(i&31)!==J.SIGHASH_SINGLE&&(i&31)!==J.SIGHASH_NONE){const y=this.outs.reduce((v,p)=>v+8+ft(p.script),0);s=Buffer.allocUnsafe(y),o=new Se.BufferWriter(s,0),this.outs.forEach(v=>{o.writeUInt64(v.value),o.writeVarSlice(v.script)}),a=Me.hash256(s)}else if((i&31)===J.SIGHASH_SINGLE&&t<this.outs.length){const y=this.outs[t];s=Buffer.allocUnsafe(8+ft(y.script)),o=new Se.BufferWriter(s,0),o.writeUInt64(y.value),o.writeVarSlice(y.script),a=Me.hash256(s)}s=Buffer.allocUnsafe(156+ft(r)),o=new Se.BufferWriter(s,0);const h=this.ins[t];return o.writeInt32(this.version),o.writeSlice(u),o.writeSlice(d),o.writeSlice(h.hash),o.writeUInt32(h.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(h.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(i),Me.hash256(s)}getHash(t){return t&&this.isCoinbase()?Buffer.alloc(32,0):Me.hash256(this.__toBuffer(void 0,void 0,t))}getId(){return(0,Se.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(t,r){return this.__toBuffer(t,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(t,r){ot(te.tuple(te.Number,te.Buffer),arguments),this.ins[t].script=r}setWitness(t,r){ot(te.tuple(te.Number,[te.Buffer]),arguments),this.ins[t].witness=r}__toBuffer(t,r,n=!1){t||(t=Buffer.allocUnsafe(this.byteLength(n)));const i=new Se.BufferWriter(t,r||0);i.writeInt32(this.version);const s=n&&this.hasWitnesses();return s&&(i.writeUInt8(J.ADVANCED_TRANSACTION_MARKER),i.writeUInt8(J.ADVANCED_TRANSACTION_FLAG)),i.writeVarInt(this.ins.length),this.ins.forEach(o=>{i.writeSlice(o.hash),i.writeUInt32(o.index),i.writeVarSlice(o.script),i.writeUInt32(o.sequence)}),i.writeVarInt(this.outs.length),this.outs.forEach(o=>{Tu(o)?i.writeUInt64(o.value):i.writeSlice(o.valueBuffer),i.writeVarSlice(o.script)}),s&&this.ins.forEach(o=>{i.writeVector(o.witness)}),i.writeUInt32(this.locktime),r!==void 0?t.slice(r,i.offset):t}}_n.Transaction=J;J.DEFAULT_SEQUENCE=4294967295;J.SIGHASH_DEFAULT=0;J.SIGHASH_ALL=1;J.SIGHASH_NONE=2;J.SIGHASH_SINGLE=3;J.SIGHASH_ANYONECANPAY=128;J.SIGHASH_OUTPUT_MASK=3;J.SIGHASH_INPUT_MASK=128;J.ADVANCED_TRANSACTION_MARKER=0;J.ADVANCED_TRANSACTION_FLAG=1;var ae={},En={};Object.defineProperty(En,"__esModule",{value:!0});const Au=9007199254740991;function Hs(e){if(e<0||e>Au||e%1!==0)throw new RangeError("value out of range")}function cn(e,t,r){if(Hs(e),t||(t=Buffer.allocUnsafe(Ma(e))),!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),e<253?(t.writeUInt8(e,r),Object.assign(cn,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(cn,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(cn,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(cn,{bytes:9})),t}En.encode=cn;function fn(e,t){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");t||(t=0);const r=e.readUInt8(t);if(r<253)return Object.assign(fn,{bytes:1}),r;if(r===253)return Object.assign(fn,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(fn,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(fn,{bytes:9});const n=e.readUInt32LE(t+1),s=e.readUInt32LE(t+5)*4294967296+n;return Hs(s),s}}En.decode=fn;function Ma(e){return Hs(e),e<253?1:e<=65535?3:e<=4294967295?5:9}En.encodingLength=Ma;var Gi={},ui={},He={};Object.defineProperty(He,"__esModule",{value:!0});He.testnet=He.regtest=He.bitcoin=void 0;He.bitcoin={messagePrefix:`Bitcoin Signed Message:
|
|
6
|
+
*/(function(e){const t=ai,r=Is,n=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=a,e.SlowBuffer=U,e.INSPECT_MAX_BYTES=50;const i=2147483647;e.kMaxLength=i,a.TYPED_ARRAY_SUPPORT=s(),!a.TYPED_ARRAY_SUPPORT&&typeof console<"u"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function s(){try{const l=new Uint8Array(1),c={foo:function(){return 42}};return Object.setPrototypeOf(c,Uint8Array.prototype),Object.setPrototypeOf(l,c),l.foo()===42}catch{return!1}}Object.defineProperty(a.prototype,"parent",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.buffer}}),Object.defineProperty(a.prototype,"offset",{enumerable:!0,get:function(){if(a.isBuffer(this))return this.byteOffset}});function o(l){if(l>i)throw new RangeError('The value "'+l+'" is invalid for option "size"');const c=new Uint8Array(l);return Object.setPrototypeOf(c,a.prototype),c}function a(l,c,f){if(typeof l=="number"){if(typeof c=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return p(l)}return u(l,c,f)}a.poolSize=8192;function u(l,c,f){if(typeof l=="string")return v(l,c);if(ArrayBuffer.isView(l))return I(l);if(l==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l);if(Ke(l,ArrayBuffer)||l&&Ke(l.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(Ke(l,SharedArrayBuffer)||l&&Ke(l.buffer,SharedArrayBuffer)))return k(l,c,f);if(typeof l=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const m=l.valueOf&&l.valueOf();if(m!=null&&m!==l)return a.from(m,c,f);const _=B(l);if(_)return _;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof l[Symbol.toPrimitive]=="function")return a.from(l[Symbol.toPrimitive]("string"),c,f);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof l)}a.from=function(l,c,f){return u(l,c,f)},Object.setPrototypeOf(a.prototype,Uint8Array.prototype),Object.setPrototypeOf(a,Uint8Array);function h(l){if(typeof l!="number")throw new TypeError('"size" argument must be of type number');if(l<0)throw new RangeError('The value "'+l+'" is invalid for option "size"')}function d(l,c,f){return h(l),l<=0?o(l):c!==void 0?typeof f=="string"?o(l).fill(c,f):o(l).fill(c):o(l)}a.alloc=function(l,c,f){return d(l,c,f)};function p(l){return h(l),o(l<0?0:R(l)|0)}a.allocUnsafe=function(l){return p(l)},a.allocUnsafeSlow=function(l){return p(l)};function v(l,c){if((typeof c!="string"||c==="")&&(c="utf8"),!a.isEncoding(c))throw new TypeError("Unknown encoding: "+c);const f=x(l,c)|0;let m=o(f);const _=m.write(l,c);return _!==f&&(m=m.slice(0,_)),m}function y(l){const c=l.length<0?0:R(l.length)|0,f=o(c);for(let m=0;m<c;m+=1)f[m]=l[m]&255;return f}function I(l){if(Ke(l,Uint8Array)){const c=new Uint8Array(l);return k(c.buffer,c.byteOffset,c.byteLength)}return y(l)}function k(l,c,f){if(c<0||l.byteLength<c)throw new RangeError('"offset" is outside of buffer bounds');if(l.byteLength<c+(f||0))throw new RangeError('"length" is outside of buffer bounds');let m;return c===void 0&&f===void 0?m=new Uint8Array(l):f===void 0?m=new Uint8Array(l,c):m=new Uint8Array(l,c,f),Object.setPrototypeOf(m,a.prototype),m}function B(l){if(a.isBuffer(l)){const c=R(l.length)|0,f=o(c);return f.length===0||l.copy(f,0,0,c),f}if(l.length!==void 0)return typeof l.length!="number"||Jt(l.length)?o(0):y(l);if(l.type==="Buffer"&&Array.isArray(l.data))return y(l.data)}function R(l){if(l>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return l|0}function U(l){return+l!=l&&(l=0),a.alloc(+l)}a.isBuffer=function(c){return c!=null&&c._isBuffer===!0&&c!==a.prototype},a.compare=function(c,f){if(Ke(c,Uint8Array)&&(c=a.from(c,c.offset,c.byteLength)),Ke(f,Uint8Array)&&(f=a.from(f,f.offset,f.byteLength)),!a.isBuffer(c)||!a.isBuffer(f))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(c===f)return 0;let m=c.length,_=f.length;for(let P=0,L=Math.min(m,_);P<L;++P)if(c[P]!==f[P]){m=c[P],_=f[P];break}return m<_?-1:_<m?1:0},a.isEncoding=function(c){switch(String(c).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},a.concat=function(c,f){if(!Array.isArray(c))throw new TypeError('"list" argument must be an Array of Buffers');if(c.length===0)return a.alloc(0);let m;if(f===void 0)for(f=0,m=0;m<c.length;++m)f+=c[m].length;const _=a.allocUnsafe(f);let P=0;for(m=0;m<c.length;++m){let L=c[m];if(Ke(L,Uint8Array))P+L.length>_.length?(a.isBuffer(L)||(L=a.from(L)),L.copy(_,P)):Uint8Array.prototype.set.call(_,L,P);else if(a.isBuffer(L))L.copy(_,P);else throw new TypeError('"list" argument must be an Array of Buffers');P+=L.length}return _};function x(l,c){if(a.isBuffer(l))return l.length;if(ArrayBuffer.isView(l)||Ke(l,ArrayBuffer))return l.byteLength;if(typeof l!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof l);const f=l.length,m=arguments.length>2&&arguments[2]===!0;if(!m&&f===0)return 0;let _=!1;for(;;)switch(c){case"ascii":case"latin1":case"binary":return f;case"utf8":case"utf-8":return ne(l).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return f*2;case"hex":return f>>>1;case"base64":return jr(l).length;default:if(_)return m?-1:ne(l).length;c=(""+c).toLowerCase(),_=!0}}a.byteLength=x;function g(l,c,f){let m=!1;if((c===void 0||c<0)&&(c=0),c>this.length||((f===void 0||f>this.length)&&(f=this.length),f<=0)||(f>>>=0,c>>>=0,f<=c))return"";for(l||(l="utf8");;)switch(l){case"hex":return qe(this,c,f);case"utf8":case"utf-8":return z(this,c,f);case"ascii":return ze(this,c,f);case"latin1":case"binary":return tt(this,c,f);case"base64":return V(this,c,f);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return It(this,c,f);default:if(m)throw new TypeError("Unknown encoding: "+l);l=(l+"").toLowerCase(),m=!0}}a.prototype._isBuffer=!0;function S(l,c,f){const m=l[c];l[c]=l[f],l[f]=m}a.prototype.swap16=function(){const c=this.length;if(c%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let f=0;f<c;f+=2)S(this,f,f+1);return this},a.prototype.swap32=function(){const c=this.length;if(c%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let f=0;f<c;f+=4)S(this,f,f+3),S(this,f+1,f+2);return this},a.prototype.swap64=function(){const c=this.length;if(c%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let f=0;f<c;f+=8)S(this,f,f+7),S(this,f+1,f+6),S(this,f+2,f+5),S(this,f+3,f+4);return this},a.prototype.toString=function(){const c=this.length;return c===0?"":arguments.length===0?z(this,0,c):g.apply(this,arguments)},a.prototype.toLocaleString=a.prototype.toString,a.prototype.equals=function(c){if(!a.isBuffer(c))throw new TypeError("Argument must be a Buffer");return this===c?!0:a.compare(this,c)===0},a.prototype.inspect=function(){let c="";const f=e.INSPECT_MAX_BYTES;return c=this.toString("hex",0,f).replace(/(.{2})/g,"$1 ").trim(),this.length>f&&(c+=" ... "),"<Buffer "+c+">"},n&&(a.prototype[n]=a.prototype.inspect),a.prototype.compare=function(c,f,m,_,P){if(Ke(c,Uint8Array)&&(c=a.from(c,c.offset,c.byteLength)),!a.isBuffer(c))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof c);if(f===void 0&&(f=0),m===void 0&&(m=c?c.length:0),_===void 0&&(_=0),P===void 0&&(P=this.length),f<0||m>c.length||_<0||P>this.length)throw new RangeError("out of range index");if(_>=P&&f>=m)return 0;if(_>=P)return-1;if(f>=m)return 1;if(f>>>=0,m>>>=0,_>>>=0,P>>>=0,this===c)return 0;let L=P-_,Z=m-f;const ge=Math.min(L,Z),me=this.slice(_,P),_e=c.slice(f,m);for(let oe=0;oe<ge;++oe)if(me[oe]!==_e[oe]){L=me[oe],Z=_e[oe];break}return L<Z?-1:Z<L?1:0};function E(l,c,f,m,_){if(l.length===0)return-1;if(typeof f=="string"?(m=f,f=0):f>2147483647?f=2147483647:f<-2147483648&&(f=-2147483648),f=+f,Jt(f)&&(f=_?0:l.length-1),f<0&&(f=l.length+f),f>=l.length){if(_)return-1;f=l.length-1}else if(f<0)if(_)f=0;else return-1;if(typeof c=="string"&&(c=a.from(c,m)),a.isBuffer(c))return c.length===0?-1:F(l,c,f,m,_);if(typeof c=="number")return c=c&255,typeof Uint8Array.prototype.indexOf=="function"?_?Uint8Array.prototype.indexOf.call(l,c,f):Uint8Array.prototype.lastIndexOf.call(l,c,f):F(l,[c],f,m,_);throw new TypeError("val must be string, number or Buffer")}function F(l,c,f,m,_){let P=1,L=l.length,Z=c.length;if(m!==void 0&&(m=String(m).toLowerCase(),m==="ucs2"||m==="ucs-2"||m==="utf16le"||m==="utf-16le")){if(l.length<2||c.length<2)return-1;P=2,L/=2,Z/=2,f/=2}function ge(_e,oe){return P===1?_e[oe]:_e.readUInt16BE(oe*P)}let me;if(_){let _e=-1;for(me=f;me<L;me++)if(ge(l,me)===ge(c,_e===-1?0:me-_e)){if(_e===-1&&(_e=me),me-_e+1===Z)return _e*P}else _e!==-1&&(me-=me-_e),_e=-1}else for(f+Z>L&&(f=L-Z),me=f;me>=0;me--){let _e=!0;for(let oe=0;oe<Z;oe++)if(ge(l,me+oe)!==ge(c,oe)){_e=!1;break}if(_e)return me}return-1}a.prototype.includes=function(c,f,m){return this.indexOf(c,f,m)!==-1},a.prototype.indexOf=function(c,f,m){return E(this,c,f,m,!0)},a.prototype.lastIndexOf=function(c,f,m){return E(this,c,f,m,!1)};function D(l,c,f,m){f=Number(f)||0;const _=l.length-f;m?(m=Number(m),m>_&&(m=_)):m=_;const P=c.length;m>P/2&&(m=P/2);let L;for(L=0;L<m;++L){const Z=parseInt(c.substr(L*2,2),16);if(Jt(Z))return L;l[f+L]=Z}return L}function O(l,c,f,m){return br(ne(c,l.length-f),l,f,m)}function K(l,c,f,m){return br(Ot(c),l,f,m)}function C(l,c,f,m){return br(jr(c),l,f,m)}function G(l,c,f,m){return br(mr(c,l.length-f),l,f,m)}a.prototype.write=function(c,f,m,_){if(f===void 0)_="utf8",m=this.length,f=0;else if(m===void 0&&typeof f=="string")_=f,m=this.length,f=0;else if(isFinite(f))f=f>>>0,isFinite(m)?(m=m>>>0,_===void 0&&(_="utf8")):(_=m,m=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const P=this.length-f;if((m===void 0||m>P)&&(m=P),c.length>0&&(m<0||f<0)||f>this.length)throw new RangeError("Attempt to write outside buffer bounds");_||(_="utf8");let L=!1;for(;;)switch(_){case"hex":return D(this,c,f,m);case"utf8":case"utf-8":return O(this,c,f,m);case"ascii":case"latin1":case"binary":return K(this,c,f,m);case"base64":return C(this,c,f,m);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return G(this,c,f,m);default:if(L)throw new TypeError("Unknown encoding: "+_);_=(""+_).toLowerCase(),L=!0}},a.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function V(l,c,f){return c===0&&f===l.length?t.fromByteArray(l):t.fromByteArray(l.slice(c,f))}function z(l,c,f){f=Math.min(l.length,f);const m=[];let _=c;for(;_<f;){const P=l[_];let L=null,Z=P>239?4:P>223?3:P>191?2:1;if(_+Z<=f){let ge,me,_e,oe;switch(Z){case 1:P<128&&(L=P);break;case 2:ge=l[_+1],(ge&192)===128&&(oe=(P&31)<<6|ge&63,oe>127&&(L=oe));break;case 3:ge=l[_+1],me=l[_+2],(ge&192)===128&&(me&192)===128&&(oe=(P&15)<<12|(ge&63)<<6|me&63,oe>2047&&(oe<55296||oe>57343)&&(L=oe));break;case 4:ge=l[_+1],me=l[_+2],_e=l[_+3],(ge&192)===128&&(me&192)===128&&(_e&192)===128&&(oe=(P&15)<<18|(ge&63)<<12|(me&63)<<6|_e&63,oe>65535&&oe<1114112&&(L=oe))}}L===null?(L=65533,Z=1):L>65535&&(L-=65536,m.push(L>>>10&1023|55296),L=56320|L&1023),m.push(L),_+=Z}return ve(m)}const ee=4096;function ve(l){const c=l.length;if(c<=ee)return String.fromCharCode.apply(String,l);let f="",m=0;for(;m<c;)f+=String.fromCharCode.apply(String,l.slice(m,m+=ee));return f}function ze(l,c,f){let m="";f=Math.min(l.length,f);for(let _=c;_<f;++_)m+=String.fromCharCode(l[_]&127);return m}function tt(l,c,f){let m="";f=Math.min(l.length,f);for(let _=c;_<f;++_)m+=String.fromCharCode(l[_]);return m}function qe(l,c,f){const m=l.length;(!c||c<0)&&(c=0),(!f||f<0||f>m)&&(f=m);let _="";for(let P=c;P<f;++P)_+=Gr[l[P]];return _}function It(l,c,f){const m=l.slice(c,f);let _="";for(let P=0;P<m.length-1;P+=2)_+=String.fromCharCode(m[P]+m[P+1]*256);return _}a.prototype.slice=function(c,f){const m=this.length;c=~~c,f=f===void 0?m:~~f,c<0?(c+=m,c<0&&(c=0)):c>m&&(c=m),f<0?(f+=m,f<0&&(f=0)):f>m&&(f=m),f<c&&(f=c);const _=this.subarray(c,f);return Object.setPrototypeOf(_,a.prototype),_};function pe(l,c,f){if(l%1!==0||l<0)throw new RangeError("offset is not uint");if(l+c>f)throw new RangeError("Trying to access beyond buffer length")}a.prototype.readUintLE=a.prototype.readUIntLE=function(c,f,m){c=c>>>0,f=f>>>0,m||pe(c,f,this.length);let _=this[c],P=1,L=0;for(;++L<f&&(P*=256);)_+=this[c+L]*P;return _},a.prototype.readUintBE=a.prototype.readUIntBE=function(c,f,m){c=c>>>0,f=f>>>0,m||pe(c,f,this.length);let _=this[c+--f],P=1;for(;f>0&&(P*=256);)_+=this[c+--f]*P;return _},a.prototype.readUint8=a.prototype.readUInt8=function(c,f){return c=c>>>0,f||pe(c,1,this.length),this[c]},a.prototype.readUint16LE=a.prototype.readUInt16LE=function(c,f){return c=c>>>0,f||pe(c,2,this.length),this[c]|this[c+1]<<8},a.prototype.readUint16BE=a.prototype.readUInt16BE=function(c,f){return c=c>>>0,f||pe(c,2,this.length),this[c]<<8|this[c+1]},a.prototype.readUint32LE=a.prototype.readUInt32LE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),(this[c]|this[c+1]<<8|this[c+2]<<16)+this[c+3]*16777216},a.prototype.readUint32BE=a.prototype.readUInt32BE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),this[c]*16777216+(this[c+1]<<16|this[c+2]<<8|this[c+3])},a.prototype.readBigUInt64LE=Je(function(c){c=c>>>0,N(c,"offset");const f=this[c],m=this[c+7];(f===void 0||m===void 0)&&$(c,this.length-8);const _=f+this[++c]*2**8+this[++c]*2**16+this[++c]*2**24,P=this[++c]+this[++c]*2**8+this[++c]*2**16+m*2**24;return BigInt(_)+(BigInt(P)<<BigInt(32))}),a.prototype.readBigUInt64BE=Je(function(c){c=c>>>0,N(c,"offset");const f=this[c],m=this[c+7];(f===void 0||m===void 0)&&$(c,this.length-8);const _=f*2**24+this[++c]*2**16+this[++c]*2**8+this[++c],P=this[++c]*2**24+this[++c]*2**16+this[++c]*2**8+m;return(BigInt(_)<<BigInt(32))+BigInt(P)}),a.prototype.readIntLE=function(c,f,m){c=c>>>0,f=f>>>0,m||pe(c,f,this.length);let _=this[c],P=1,L=0;for(;++L<f&&(P*=256);)_+=this[c+L]*P;return P*=128,_>=P&&(_-=Math.pow(2,8*f)),_},a.prototype.readIntBE=function(c,f,m){c=c>>>0,f=f>>>0,m||pe(c,f,this.length);let _=f,P=1,L=this[c+--_];for(;_>0&&(P*=256);)L+=this[c+--_]*P;return P*=128,L>=P&&(L-=Math.pow(2,8*f)),L},a.prototype.readInt8=function(c,f){return c=c>>>0,f||pe(c,1,this.length),this[c]&128?(255-this[c]+1)*-1:this[c]},a.prototype.readInt16LE=function(c,f){c=c>>>0,f||pe(c,2,this.length);const m=this[c]|this[c+1]<<8;return m&32768?m|4294901760:m},a.prototype.readInt16BE=function(c,f){c=c>>>0,f||pe(c,2,this.length);const m=this[c+1]|this[c]<<8;return m&32768?m|4294901760:m},a.prototype.readInt32LE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),this[c]|this[c+1]<<8|this[c+2]<<16|this[c+3]<<24},a.prototype.readInt32BE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),this[c]<<24|this[c+1]<<16|this[c+2]<<8|this[c+3]},a.prototype.readBigInt64LE=Je(function(c){c=c>>>0,N(c,"offset");const f=this[c],m=this[c+7];(f===void 0||m===void 0)&&$(c,this.length-8);const _=this[c+4]+this[c+5]*2**8+this[c+6]*2**16+(m<<24);return(BigInt(_)<<BigInt(32))+BigInt(f+this[++c]*2**8+this[++c]*2**16+this[++c]*2**24)}),a.prototype.readBigInt64BE=Je(function(c){c=c>>>0,N(c,"offset");const f=this[c],m=this[c+7];(f===void 0||m===void 0)&&$(c,this.length-8);const _=(f<<24)+this[++c]*2**16+this[++c]*2**8+this[++c];return(BigInt(_)<<BigInt(32))+BigInt(this[++c]*2**24+this[++c]*2**16+this[++c]*2**8+m)}),a.prototype.readFloatLE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),r.read(this,c,!0,23,4)},a.prototype.readFloatBE=function(c,f){return c=c>>>0,f||pe(c,4,this.length),r.read(this,c,!1,23,4)},a.prototype.readDoubleLE=function(c,f){return c=c>>>0,f||pe(c,8,this.length),r.read(this,c,!0,52,8)},a.prototype.readDoubleBE=function(c,f){return c=c>>>0,f||pe(c,8,this.length),r.read(this,c,!1,52,8)};function Ee(l,c,f,m,_,P){if(!a.isBuffer(l))throw new TypeError('"buffer" argument must be a Buffer instance');if(c>_||c<P)throw new RangeError('"value" argument is out of bounds');if(f+m>l.length)throw new RangeError("Index out of range")}a.prototype.writeUintLE=a.prototype.writeUIntLE=function(c,f,m,_){if(c=+c,f=f>>>0,m=m>>>0,!_){const Z=Math.pow(2,8*m)-1;Ee(this,c,f,m,Z,0)}let P=1,L=0;for(this[f]=c&255;++L<m&&(P*=256);)this[f+L]=c/P&255;return f+m},a.prototype.writeUintBE=a.prototype.writeUIntBE=function(c,f,m,_){if(c=+c,f=f>>>0,m=m>>>0,!_){const Z=Math.pow(2,8*m)-1;Ee(this,c,f,m,Z,0)}let P=m-1,L=1;for(this[f+P]=c&255;--P>=0&&(L*=256);)this[f+P]=c/L&255;return f+m},a.prototype.writeUint8=a.prototype.writeUInt8=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,1,255,0),this[f]=c&255,f+1},a.prototype.writeUint16LE=a.prototype.writeUInt16LE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,2,65535,0),this[f]=c&255,this[f+1]=c>>>8,f+2},a.prototype.writeUint16BE=a.prototype.writeUInt16BE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,2,65535,0),this[f]=c>>>8,this[f+1]=c&255,f+2},a.prototype.writeUint32LE=a.prototype.writeUInt32LE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,4,4294967295,0),this[f+3]=c>>>24,this[f+2]=c>>>16,this[f+1]=c>>>8,this[f]=c&255,f+4},a.prototype.writeUint32BE=a.prototype.writeUInt32BE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,4,4294967295,0),this[f]=c>>>24,this[f+1]=c>>>16,this[f+2]=c>>>8,this[f+3]=c&255,f+4};function We(l,c,f,m,_){w(c,m,_,l,f,7);let P=Number(c&BigInt(4294967295));l[f++]=P,P=P>>8,l[f++]=P,P=P>>8,l[f++]=P,P=P>>8,l[f++]=P;let L=Number(c>>BigInt(32)&BigInt(4294967295));return l[f++]=L,L=L>>8,l[f++]=L,L=L>>8,l[f++]=L,L=L>>8,l[f++]=L,f}function Pt(l,c,f,m,_){w(c,m,_,l,f,7);let P=Number(c&BigInt(4294967295));l[f+7]=P,P=P>>8,l[f+6]=P,P=P>>8,l[f+5]=P,P=P>>8,l[f+4]=P;let L=Number(c>>BigInt(32)&BigInt(4294967295));return l[f+3]=L,L=L>>8,l[f+2]=L,L=L>>8,l[f+1]=L,L=L>>8,l[f]=L,f+8}a.prototype.writeBigUInt64LE=Je(function(c,f=0){return We(this,c,f,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeBigUInt64BE=Je(function(c,f=0){return Pt(this,c,f,BigInt(0),BigInt("0xffffffffffffffff"))}),a.prototype.writeIntLE=function(c,f,m,_){if(c=+c,f=f>>>0,!_){const ge=Math.pow(2,8*m-1);Ee(this,c,f,m,ge-1,-ge)}let P=0,L=1,Z=0;for(this[f]=c&255;++P<m&&(L*=256);)c<0&&Z===0&&this[f+P-1]!==0&&(Z=1),this[f+P]=(c/L>>0)-Z&255;return f+m},a.prototype.writeIntBE=function(c,f,m,_){if(c=+c,f=f>>>0,!_){const ge=Math.pow(2,8*m-1);Ee(this,c,f,m,ge-1,-ge)}let P=m-1,L=1,Z=0;for(this[f+P]=c&255;--P>=0&&(L*=256);)c<0&&Z===0&&this[f+P+1]!==0&&(Z=1),this[f+P]=(c/L>>0)-Z&255;return f+m},a.prototype.writeInt8=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,1,127,-128),c<0&&(c=255+c+1),this[f]=c&255,f+1},a.prototype.writeInt16LE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,2,32767,-32768),this[f]=c&255,this[f+1]=c>>>8,f+2},a.prototype.writeInt16BE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,2,32767,-32768),this[f]=c>>>8,this[f+1]=c&255,f+2},a.prototype.writeInt32LE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,4,2147483647,-2147483648),this[f]=c&255,this[f+1]=c>>>8,this[f+2]=c>>>16,this[f+3]=c>>>24,f+4},a.prototype.writeInt32BE=function(c,f,m){return c=+c,f=f>>>0,m||Ee(this,c,f,4,2147483647,-2147483648),c<0&&(c=4294967295+c+1),this[f]=c>>>24,this[f+1]=c>>>16,this[f+2]=c>>>8,this[f+3]=c&255,f+4},a.prototype.writeBigInt64LE=Je(function(c,f=0){return We(this,c,f,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),a.prototype.writeBigInt64BE=Je(function(c,f=0){return Pt(this,c,f,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function yt(l,c,f,m,_,P){if(f+m>l.length)throw new RangeError("Index out of range");if(f<0)throw new RangeError("Index out of range")}function A(l,c,f,m,_){return c=+c,f=f>>>0,_||yt(l,c,f,4),r.write(l,c,f,m,23,4),f+4}a.prototype.writeFloatLE=function(c,f,m){return A(this,c,f,!0,m)},a.prototype.writeFloatBE=function(c,f,m){return A(this,c,f,!1,m)};function T(l,c,f,m,_){return c=+c,f=f>>>0,_||yt(l,c,f,8),r.write(l,c,f,m,52,8),f+8}a.prototype.writeDoubleLE=function(c,f,m){return T(this,c,f,!0,m)},a.prototype.writeDoubleBE=function(c,f,m){return T(this,c,f,!1,m)},a.prototype.copy=function(c,f,m,_){if(!a.isBuffer(c))throw new TypeError("argument should be a Buffer");if(m||(m=0),!_&&_!==0&&(_=this.length),f>=c.length&&(f=c.length),f||(f=0),_>0&&_<m&&(_=m),_===m||c.length===0||this.length===0)return 0;if(f<0)throw new RangeError("targetStart out of bounds");if(m<0||m>=this.length)throw new RangeError("Index out of range");if(_<0)throw new RangeError("sourceEnd out of bounds");_>this.length&&(_=this.length),c.length-f<_-m&&(_=c.length-f+m);const P=_-m;return this===c&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(f,m,_):Uint8Array.prototype.set.call(c,this.subarray(m,_),f),P},a.prototype.fill=function(c,f,m,_){if(typeof c=="string"){if(typeof f=="string"?(_=f,f=0,m=this.length):typeof m=="string"&&(_=m,m=this.length),_!==void 0&&typeof _!="string")throw new TypeError("encoding must be a string");if(typeof _=="string"&&!a.isEncoding(_))throw new TypeError("Unknown encoding: "+_);if(c.length===1){const L=c.charCodeAt(0);(_==="utf8"&&L<128||_==="latin1")&&(c=L)}}else typeof c=="number"?c=c&255:typeof c=="boolean"&&(c=Number(c));if(f<0||this.length<f||this.length<m)throw new RangeError("Out of range index");if(m<=f)return this;f=f>>>0,m=m===void 0?this.length:m>>>0,c||(c=0);let P;if(typeof c=="number")for(P=f;P<m;++P)this[P]=c;else{const L=a.isBuffer(c)?c:a.from(c,_),Z=L.length;if(Z===0)throw new TypeError('The value "'+c+'" is invalid for argument "value"');for(P=0;P<m-f;++P)this[P+f]=L[P%Z]}return this};const H={};function q(l,c,f){H[l]=class extends f{constructor(){super(),Object.defineProperty(this,"message",{value:c.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${l}]`,this.stack,delete this.name}get code(){return l}set code(_){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:_,writable:!0})}toString(){return`${this.name} [${l}]: ${this.message}`}}}q("ERR_BUFFER_OUT_OF_BOUNDS",function(l){return l?`${l} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),q("ERR_INVALID_ARG_TYPE",function(l,c){return`The "${l}" argument must be of type number. Received type ${typeof c}`},TypeError),q("ERR_OUT_OF_RANGE",function(l,c,f){let m=`The value of "${l}" is out of range.`,_=f;return Number.isInteger(f)&&Math.abs(f)>2**32?_=Y(String(f)):typeof f=="bigint"&&(_=String(f),(f>BigInt(2)**BigInt(32)||f<-(BigInt(2)**BigInt(32)))&&(_=Y(_)),_+="n"),m+=` It must be ${c}. Received ${_}`,m},RangeError);function Y(l){let c="",f=l.length;const m=l[0]==="-"?1:0;for(;f>=m+4;f-=3)c=`_${l.slice(f-3,f)}${c}`;return`${l.slice(0,f)}${c}`}function b(l,c,f){N(c,"offset"),(l[c]===void 0||l[c+f]===void 0)&&$(c,l.length-(f+1))}function w(l,c,f,m,_,P){if(l>f||l<c){const L=typeof c=="bigint"?"n":"";let Z;throw c===0||c===BigInt(0)?Z=`>= 0${L} and < 2${L} ** ${(P+1)*8}${L}`:Z=`>= -(2${L} ** ${(P+1)*8-1}${L}) and < 2 ** ${(P+1)*8-1}${L}`,new H.ERR_OUT_OF_RANGE("value",Z,l)}b(m,_,P)}function N(l,c){if(typeof l!="number")throw new H.ERR_INVALID_ARG_TYPE(c,"number",l)}function $(l,c,f){throw Math.floor(l)!==l?(N(l,f),new H.ERR_OUT_OF_RANGE("offset","an integer",l)):c<0?new H.ERR_BUFFER_OUT_OF_BOUNDS:new H.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${c}`,l)}const ye=/[^+/0-9A-Za-z-_]/g;function X(l){if(l=l.split("=")[0],l=l.trim().replace(ye,""),l.length<2)return"";for(;l.length%4!==0;)l=l+"=";return l}function ne(l,c){c=c||1/0;let f;const m=l.length;let _=null;const P=[];for(let L=0;L<m;++L){if(f=l.charCodeAt(L),f>55295&&f<57344){if(!_){if(f>56319){(c-=3)>-1&&P.push(239,191,189);continue}else if(L+1===m){(c-=3)>-1&&P.push(239,191,189);continue}_=f;continue}if(f<56320){(c-=3)>-1&&P.push(239,191,189),_=f;continue}f=(_-55296<<10|f-56320)+65536}else _&&(c-=3)>-1&&P.push(239,191,189);if(_=null,f<128){if((c-=1)<0)break;P.push(f)}else if(f<2048){if((c-=2)<0)break;P.push(f>>6|192,f&63|128)}else if(f<65536){if((c-=3)<0)break;P.push(f>>12|224,f>>6&63|128,f&63|128)}else if(f<1114112){if((c-=4)<0)break;P.push(f>>18|240,f>>12&63|128,f>>6&63|128,f&63|128)}else throw new Error("Invalid code point")}return P}function Ot(l){const c=[];for(let f=0;f<l.length;++f)c.push(l.charCodeAt(f)&255);return c}function mr(l,c){let f,m,_;const P=[];for(let L=0;L<l.length&&!((c-=2)<0);++L)f=l.charCodeAt(L),m=f>>8,_=f%256,P.push(_),P.push(m);return P}function jr(l){return t.toByteArray(X(l))}function br(l,c,f,m){let _;for(_=0;_<m&&!(_+f>=c.length||_>=l.length);++_)c[_+f]=l[_];return _}function Ke(l,c){return l instanceof c||l!=null&&l.constructor!=null&&l.constructor.name!=null&&l.constructor.name===c.name}function Jt(l){return l!==l}const Gr=function(){const l="0123456789abcdef",c=new Array(256);for(let f=0;f<16;++f){const m=f*16;for(let _=0;_<16;++_)c[m+_]=l[f]+l[_]}return c}();function Je(l){return typeof BigInt>"u"?Qt:l}function Qt(){throw new Error("BigInt not supported")}})(Bt);var pn={Array:function(e){return e!=null&&e.constructor===Array},Boolean:function(e){return typeof e=="boolean"},Function:function(e){return typeof e=="function"},Nil:function(e){return e==null},Number:function(e){return typeof e=="number"},Object:function(e){return typeof e=="object"},String:function(e){return typeof e=="string"},"":function(){return!0}};pn.Null=pn.Nil;for(var oo in pn)pn[oo].toJSON=(function(e){return e}).bind(null,oo);var Ps=pn,rr=Ps;function Ea(e){return e.name||e.toString().match(/function (.*?)\s*\(/)[1]}function Os(e){return rr.Nil(e)?"":Ea(e.constructor)}function Vf(e){return rr.Function(e)?"":rr.String(e)?JSON.stringify(e):e&&rr.Object(e)?"":e}function Rs(e,t){Error.captureStackTrace&&Error.captureStackTrace(e,t)}function Jn(e){return rr.Function(e)?e.toJSON?e.toJSON():Ea(e):rr.Array(e)?"Array":e&&rr.Object(e)?"Object":e!==void 0?e:""}function xa(e,t,r){var n=Vf(t);return"Expected "+Jn(e)+", got"+(r!==""?" "+r:"")+(n!==""?" "+n:"")}function Tt(e,t,r){r=r||Os(t),this.message=xa(e,t,r),Rs(this,Tt),this.__type=e,this.__value=t,this.__valueTypeName=r}Tt.prototype=Object.create(Error.prototype);Tt.prototype.constructor=Tt;function zf(e,t,r,n,i){var s='" of type ';return t==="key"&&(s='" with key type '),xa('property "'+Jn(r)+s+Jn(e),n,i)}function kr(e,t,r,n,i){e?(i=i||Os(n),this.message=zf(e,r,t,n,i)):this.message='Unexpected property "'+t+'"',Rs(this,Tt),this.__label=r,this.__property=t,this.__type=e,this.__value=n,this.__valueTypeName=i}kr.prototype=Object.create(Error.prototype);kr.prototype.constructor=Tt;function qf(e,t){return new Tt(e,{},t)}function Wf(e,t,r){return e instanceof kr?(t=t+"."+e.__property,e=new kr(e.__type,t,e.__label,e.__value,e.__valueTypeName)):e instanceof Tt&&(e=new kr(e.__type,t,r,e.__value,e.__valueTypeName)),Rs(e),e}var Sa={TfTypeError:Tt,TfPropertyTypeError:kr,tfCustomError:qf,tfSubError:Wf,tfJSON:Jn,getValueTypeName:Os},Ni,ao;function Kf(){if(ao)return Ni;ao=1;var e=Ps,t=Sa;function r(E){return Buffer.isBuffer(E)}function n(E){return typeof E=="string"&&/^([0-9a-f]{2})+$/i.test(E)}function i(E,F){var D=E.toJSON();function O(K){if(!E(K))return!1;if(K.length===F)return!0;throw t.tfCustomError(D+"(Length: "+F+")",D+"(Length: "+K.length+")")}return O.toJSON=function(){return D},O}var s=i.bind(null,e.Array),o=i.bind(null,r),a=i.bind(null,n),u=i.bind(null,e.String);function h(E,F,D){D=D||e.Number;function O(K,C){return D(K,C)&&K>E&&K<F}return O.toJSON=function(){return`${D.toJSON()} between [${E}, ${F}]`},O}var d=Math.pow(2,53)-1;function p(E){return typeof E=="number"&&isFinite(E)}function v(E){return E<<24>>24===E}function y(E){return E<<16>>16===E}function I(E){return(E|0)===E}function k(E){return typeof E=="number"&&E>=-d&&E<=d&&Math.floor(E)===E}function B(E){return(E&255)===E}function R(E){return(E&65535)===E}function U(E){return E>>>0===E}function x(E){return typeof E=="number"&&E>=0&&E<=d&&Math.floor(E)===E}var g={ArrayN:s,Buffer:r,BufferN:o,Finite:p,Hex:n,HexN:a,Int8:v,Int16:y,Int32:I,Int53:k,Range:h,StringN:u,UInt8:B,UInt16:R,UInt32:U,UInt53:x};for(var S in g)g[S].toJSON=(function(E){return E}).bind(null,S);return Ni=g,Ni}var wn=Sa,Ie=Ps,mt=wn.tfJSON,Ta=wn.TfTypeError,Aa=wn.TfPropertyTypeError,Vr=wn.tfSubError,Yf=wn.getValueTypeName,Et={arrayOf:function(t,r){t=lt(t),r=r||{};function n(i,s){return!Ie.Array(i)||Ie.Nil(i)||r.minLength!==void 0&&i.length<r.minLength||r.maxLength!==void 0&&i.length>r.maxLength||r.length!==void 0&&i.length!==r.length?!1:i.every(function(o,a){try{return Ge(t,o,s)}catch(u){throw Vr(u,a)}})}return n.toJSON=function(){var i="["+mt(t)+"]";return r.length!==void 0?i+="{"+r.length+"}":(r.minLength!==void 0||r.maxLength!==void 0)&&(i+="{"+(r.minLength===void 0?0:r.minLength)+","+(r.maxLength===void 0?1/0:r.maxLength)+"}"),i},n},maybe:function e(t){t=lt(t);function r(n,i){return Ie.Nil(n)||t(n,i,e)}return r.toJSON=function(){return"?"+mt(t)},r},map:function(t,r){t=lt(t),r&&(r=lt(r));function n(i,s){if(!Ie.Object(i)||Ie.Nil(i))return!1;for(var o in i){try{r&&Ge(r,o,s)}catch(u){throw Vr(u,o,"key")}try{var a=i[o];Ge(t,a,s)}catch(u){throw Vr(u,o)}}return!0}return r?n.toJSON=function(){return"{"+mt(r)+": "+mt(t)+"}"}:n.toJSON=function(){return"{"+mt(t)+"}"},n},object:function(t){var r={};for(var n in t)r[n]=lt(t[n]);function i(s,o){if(!Ie.Object(s)||Ie.Nil(s))return!1;var a;try{for(a in r){var u=r[a],h=s[a];Ge(u,h,o)}}catch(d){throw Vr(d,a)}if(o){for(a in s)if(!r[a])throw new Aa(void 0,a)}return!0}return i.toJSON=function(){return mt(r)},i},anyOf:function(){var t=[].slice.call(arguments).map(lt);function r(n,i){return t.some(function(s){try{return Ge(s,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(mt).join("|")},r},allOf:function(){var t=[].slice.call(arguments).map(lt);function r(n,i){return t.every(function(s){try{return Ge(s,n,i)}catch{return!1}})}return r.toJSON=function(){return t.map(mt).join(" & ")},r},quacksLike:function(t){function r(n){return t===Yf(n)}return r.toJSON=function(){return t},r},tuple:function(){var t=[].slice.call(arguments).map(lt);function r(n,i){return Ie.Nil(n)||Ie.Nil(n.length)||i&&n.length!==t.length?!1:t.every(function(s,o){try{return Ge(s,n[o],i)}catch(a){throw Vr(a,o)}})}return r.toJSON=function(){return"("+t.map(mt).join(", ")+")"},r},value:function(t){function r(n){return n===t}return r.toJSON=function(){return t},r}};Et.oneOf=Et.anyOf;function lt(e){if(Ie.String(e))return e[0]==="?"?Et.maybe(e.slice(1)):Ie[e]||Et.quacksLike(e);if(e&&Ie.Object(e)){if(Ie.Array(e)){if(e.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return Et.arrayOf(e[0])}return Et.object(e)}else if(Ie.Function(e))return e;return Et.value(e)}function Ge(e,t,r,n){if(Ie.Function(e)){if(e(t,r))return!0;throw new Ta(n||e,t)}return Ge(lt(e),t,r)}for(var $t in Ie)Ge[$t]=Ie[$t];for($t in Et)Ge[$t]=Et[$t];var co=Kf();for($t in co)Ge[$t]=co[$t];Ge.compile=lt;Ge.TfTypeError=Ta;Ge.TfPropertyTypeError=Aa;var ka=Ge;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.oneOf=e.Null=e.BufferN=e.Function=e.UInt32=e.UInt8=e.tuple=e.maybe=e.Hex=e.Buffer=e.String=e.Boolean=e.Array=e.Number=e.Hash256bit=e.Hash160bit=e.Buffer256bit=e.isTaptree=e.isTapleaf=e.TAPLEAF_VERSION_MASK=e.Satoshi=e.isPoint=e.stacksEqual=e.typeforce=void 0;const t=Bt;e.typeforce=ka;const r=t.Buffer.alloc(32,0),n=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(d,p){return d.length!==p.length?!1:d.every((v,y)=>v.equals(p[y]))}e.stacksEqual=i;function s(d){if(!t.Buffer.isBuffer(d)||d.length<33)return!1;const p=d[0],v=d.slice(1,33);if(v.compare(r)===0||v.compare(n)>=0)return!1;if((p===2||p===3)&&d.length===33)return!0;const y=d.slice(33);return y.compare(r)===0||y.compare(n)>=0?!1:p===4&&d.length===65}e.isPoint=s;const o=21*1e14;function a(d){return e.typeforce.UInt53(d)&&d<=o}e.Satoshi=a,e.TAPLEAF_VERSION_MASK=254;function u(d){return!d||!("output"in d)||!t.Buffer.isBuffer(d.output)?!1:d.version!==void 0?(d.version&e.TAPLEAF_VERSION_MASK)===d.version:!0}e.isTapleaf=u;function h(d){return(0,e.Array)(d)?d.length!==2?!1:d.every(p=>h(p)):u(d)}e.isTaptree=h,e.Buffer256bit=e.typeforce.BufferN(32),e.Hash160bit=e.typeforce.BufferN(20),e.Hash256bit=e.typeforce.BufferN(32),e.Number=e.typeforce.Number,e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.String=e.typeforce.String,e.Buffer=e.typeforce.Buffer,e.Hex=e.typeforce.Hex,e.maybe=e.typeforce.maybe,e.tuple=e.typeforce.tuple,e.UInt8=e.typeforce.UInt8,e.UInt32=e.typeforce.UInt32,e.Function=e.typeforce.Function,e.BufferN=e.typeforce.BufferN,e.Null=e.typeforce.Null,e.oneOf=e.typeforce.oneOf})(Fe);var gn={},Pe={};Object.defineProperty(Pe,"__esModule",{value:!0});Pe.BufferReader=Pe.BufferWriter=Pe.cloneBuffer=Pe.reverseBuffer=Pe.writeUInt64LE=Pe.readUInt64LE=Pe.varuint=void 0;const nr=Fe,{typeforce:Ba}=nr,yn=ya;Pe.varuint=yn;function Ia(e,t){if(typeof e!="number")throw new Error("cannot write a non-number as a number");if(e<0)throw new Error("specified a negative value for writing an unsigned value");if(e>t)throw new Error("RangeError: value out of range");if(Math.floor(e)!==e)throw new Error("value has a fractional component")}function Pa(e,t){const r=e.readUInt32LE(t);let n=e.readUInt32LE(t+4);return n*=4294967296,Ia(n+r,9007199254740991),n+r}Pe.readUInt64LE=Pa;function Oa(e,t,r){return Ia(t,9007199254740991),e.writeInt32LE(t&-1,r),e.writeUInt32LE(Math.floor(t/4294967296),r+4),r+8}Pe.writeUInt64LE=Oa;function Xf(e){if(e.length<1)return e;let t=e.length-1,r=0;for(let n=0;n<e.length/2;n++)r=e[n],e[n]=e[t],e[t]=r,t--;return e}Pe.reverseBuffer=Xf;function Jf(e){const t=Buffer.allocUnsafe(e.length);return e.copy(t),t}Pe.cloneBuffer=Jf;class Cs{static withCapacity(t){return new Cs(Buffer.alloc(t))}constructor(t,r=0){this.buffer=t,this.offset=r,Ba(nr.tuple(nr.Buffer,nr.UInt32),[t,r])}writeUInt8(t){this.offset=this.buffer.writeUInt8(t,this.offset)}writeInt32(t){this.offset=this.buffer.writeInt32LE(t,this.offset)}writeUInt32(t){this.offset=this.buffer.writeUInt32LE(t,this.offset)}writeUInt64(t){this.offset=Oa(this.buffer,t,this.offset)}writeVarInt(t){yn.encode(t,this.buffer,this.offset),this.offset+=yn.encode.bytes}writeSlice(t){if(this.buffer.length<this.offset+t.length)throw new Error("Cannot write slice out of bounds");this.offset+=t.copy(this.buffer,this.offset)}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}writeVector(t){this.writeVarInt(t.length),t.forEach(r=>this.writeVarSlice(r))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}Pe.BufferWriter=Cs;class Qf{constructor(t,r=0){this.buffer=t,this.offset=r,Ba(nr.tuple(nr.Buffer,nr.UInt32),[t,r])}readUInt8(){const t=this.buffer.readUInt8(this.offset);return this.offset++,t}readInt32(){const t=this.buffer.readInt32LE(this.offset);return this.offset+=4,t}readUInt32(){const t=this.buffer.readUInt32LE(this.offset);return this.offset+=4,t}readUInt64(){const t=Pa(this.buffer,this.offset);return this.offset+=8,t}readVarInt(){const t=yn.decode(this.buffer,this.offset);return this.offset+=yn.decode.bytes,t}readSlice(t){if(this.buffer.length<this.offset+t)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+t);return this.offset+=t,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const t=this.readVarInt(),r=[];for(let n=0;n<t;n++)r.push(this.readVarSlice());return r}}Pe.BufferReader=Qf;var zt={},Rr={},qt={},Wt={};Object.defineProperty(Wt,"__esModule",{value:!0});Wt.anumber=ds;Wt.abytes=Ra;Wt.ahash=eu;Wt.aexists=tu;Wt.aoutput=ru;function ds(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function Zf(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ra(e,...t){if(!Zf(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function eu(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");ds(e.outputLen),ds(e.blockLen)}function tu(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function ru(e,t){Ra(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}var ci={},fi={};Object.defineProperty(fi,"__esModule",{value:!0});fi.crypto=void 0;fi.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;(function(e){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(e,"__esModule",{value:!0}),e.Hash=e.nextTick=e.byteSwapIfBE=e.isLE=void 0,e.isBytes=n,e.u8=i,e.u32=s,e.createView=o,e.rotr=a,e.rotl=u,e.byteSwap=h,e.byteSwap32=d,e.bytesToHex=v,e.hexToBytes=k,e.asyncLoop=R,e.utf8ToBytes=U,e.toBytes=x,e.concatBytes=g,e.checkOpts=E,e.wrapConstructor=F,e.wrapConstructorWithOpts=D,e.wrapXOFConstructorWithOpts=O,e.randomBytes=K;const t=fi,r=Wt;function n(C){return C instanceof Uint8Array||ArrayBuffer.isView(C)&&C.constructor.name==="Uint8Array"}function i(C){return new Uint8Array(C.buffer,C.byteOffset,C.byteLength)}function s(C){return new Uint32Array(C.buffer,C.byteOffset,Math.floor(C.byteLength/4))}function o(C){return new DataView(C.buffer,C.byteOffset,C.byteLength)}function a(C,G){return C<<32-G|C>>>G}function u(C,G){return C<<G|C>>>32-G>>>0}e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function h(C){return C<<24&4278190080|C<<8&16711680|C>>>8&65280|C>>>24&255}e.byteSwapIfBE=e.isLE?C=>C:C=>h(C);function d(C){for(let G=0;G<C.length;G++)C[G]=h(C[G])}const p=Array.from({length:256},(C,G)=>G.toString(16).padStart(2,"0"));function v(C){(0,r.abytes)(C);let G="";for(let V=0;V<C.length;V++)G+=p[C[V]];return G}const y={_0:48,_9:57,A:65,F:70,a:97,f:102};function I(C){if(C>=y._0&&C<=y._9)return C-y._0;if(C>=y.A&&C<=y.F)return C-(y.A-10);if(C>=y.a&&C<=y.f)return C-(y.a-10)}function k(C){if(typeof C!="string")throw new Error("hex string expected, got "+typeof C);const G=C.length,V=G/2;if(G%2)throw new Error("hex string expected, got unpadded hex of length "+G);const z=new Uint8Array(V);for(let ee=0,ve=0;ee<V;ee++,ve+=2){const ze=I(C.charCodeAt(ve)),tt=I(C.charCodeAt(ve+1));if(ze===void 0||tt===void 0){const qe=C[ve]+C[ve+1];throw new Error('hex string expected, got non-hex character "'+qe+'" at index '+ve)}z[ee]=ze*16+tt}return z}const B=async()=>{};e.nextTick=B;async function R(C,G,V){let z=Date.now();for(let ee=0;ee<C;ee++){V(ee);const ve=Date.now()-z;ve>=0&&ve<G||(await(0,e.nextTick)(),z+=ve)}}function U(C){if(typeof C!="string")throw new Error("utf8ToBytes expected string, got "+typeof C);return new Uint8Array(new TextEncoder().encode(C))}function x(C){return typeof C=="string"&&(C=U(C)),(0,r.abytes)(C),C}function g(...C){let G=0;for(let z=0;z<C.length;z++){const ee=C[z];(0,r.abytes)(ee),G+=ee.length}const V=new Uint8Array(G);for(let z=0,ee=0;z<C.length;z++){const ve=C[z];V.set(ve,ee),ee+=ve.length}return V}class S{clone(){return this._cloneInto()}}e.Hash=S;function E(C,G){if(G!==void 0&&{}.toString.call(G)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(C,G)}function F(C){const G=z=>C().update(x(z)).digest(),V=C();return G.outputLen=V.outputLen,G.blockLen=V.blockLen,G.create=()=>C(),G}function D(C){const G=(z,ee)=>C(ee).update(x(z)).digest(),V=C({});return G.outputLen=V.outputLen,G.blockLen=V.blockLen,G.create=z=>C(z),G}function O(C){const G=(z,ee)=>C(ee).update(x(z)).digest(),V=C({});return G.outputLen=V.outputLen,G.blockLen=V.blockLen,G.create=z=>C(z),G}function K(C=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(C));if(t.crypto&&typeof t.crypto.randomBytes=="function")return t.crypto.randomBytes(C);throw new Error("crypto.getRandomValues must be defined")}})(ci);Object.defineProperty(qt,"__esModule",{value:!0});qt.HashMD=void 0;qt.setBigUint64=Ca;qt.Chi=nu;qt.Maj=iu;const Hi=Wt,zr=ci;function Ca(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),u=n?4:0,h=n?0:4;e.setUint32(t+u,o,n),e.setUint32(t+h,a,n)}function nu(e,t,r){return e&t^~e&r}function iu(e,t,r){return e&t^e&r^t&r}let su=class extends zr.Hash{constructor(t,r,n,i){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=(0,zr.createView)(this.buffer)}update(t){(0,Hi.aexists)(this);const{view:r,buffer:n,blockLen:i}=this;t=(0,zr.toBytes)(t);const s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const u=(0,zr.createView)(t);for(;i<=s-o;o+=i)this.process(u,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){(0,Hi.aexists)(this),(0,Hi.aoutput)(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(n,0),o=0);for(let p=o;p<i;p++)r[p]=0;Ca(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=(0,zr.createView)(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=u/4,d=this.get();if(h>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<h;p++)a.setUint32(4*p,d[p],s)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return t.length=i,t.pos=a,t.finished=s,t.destroyed=o,i%r&&t.buffer.set(n),t}};qt.HashMD=su;Object.defineProperty(Rr,"__esModule",{value:!0});Rr.ripemd160=Rr.RIPEMD160=void 0;const ou=qt,on=ci,au=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Ua=new Uint8Array(new Array(16).fill(0).map((e,t)=>t)),cu=Ua.map(e=>(9*e+5)%16);let Us=[Ua],Ls=[cu];for(let e=0;e<4;e++)for(let t of[Us,Ls])t.push(t[e].map(r=>au[r]));const La=[[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(e=>new Uint8Array(e)),fu=Us.map((e,t)=>e.map(r=>La[t][r])),uu=Ls.map((e,t)=>e.map(r=>La[t][r])),lu=new Uint32Array([0,1518500249,1859775393,2400959708,2840853838]),hu=new Uint32Array([1352829926,1548603684,1836072691,2053994217,0]);function fo(e,t,r,n){return e===0?t^r^n:e===1?t&r|~t&n:e===2?(t|~r)^n:e===3?t&n|r&~n:t^(r|~n)}const Pn=new Uint32Array(16);let Na=class extends ou.HashMD{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){const{h0:t,h1:r,h2:n,h3:i,h4:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.h0=t|0,this.h1=r|0,this.h2=n|0,this.h3=i|0,this.h4=s|0}process(t,r){for(let y=0;y<16;y++,r+=4)Pn[y]=t.getUint32(r,!0);let n=this.h0|0,i=n,s=this.h1|0,o=s,a=this.h2|0,u=a,h=this.h3|0,d=h,p=this.h4|0,v=p;for(let y=0;y<5;y++){const I=4-y,k=lu[y],B=hu[y],R=Us[y],U=Ls[y],x=fu[y],g=uu[y];for(let S=0;S<16;S++){const E=(0,on.rotl)(n+fo(y,s,a,h)+Pn[R[S]]+k,x[S])+p|0;n=p,p=h,h=(0,on.rotl)(a,10)|0,a=s,s=E}for(let S=0;S<16;S++){const E=(0,on.rotl)(i+fo(I,o,u,d)+Pn[U[S]]+B,g[S])+v|0;i=v,v=d,d=(0,on.rotl)(u,10)|0,u=o,o=E}}this.set(this.h1+a+d|0,this.h2+h+v|0,this.h3+p+i|0,this.h4+n+o|0,this.h0+s+u|0)}roundClean(){Pn.fill(0)}destroy(){this.destroyed=!0,this.buffer.fill(0),this.set(0,0,0,0,0)}};Rr.RIPEMD160=Na;Rr.ripemd160=(0,on.wrapConstructor)(()=>new Na);var Cr={};Object.defineProperty(Cr,"__esModule",{value:!0});Cr.sha1=Cr.SHA1=void 0;const Fi=qt,Gn=ci,qr=new Uint32Array([1732584193,4023233417,2562383102,271733878,3285377520]),Rt=new Uint32Array(80);class Ha extends Fi.HashMD{constructor(){super(64,20,8,!1),this.A=qr[0]|0,this.B=qr[1]|0,this.C=qr[2]|0,this.D=qr[3]|0,this.E=qr[4]|0}get(){const{A:t,B:r,C:n,D:i,E:s}=this;return[t,r,n,i,s]}set(t,r,n,i,s){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0}process(t,r){for(let u=0;u<16;u++,r+=4)Rt[u]=t.getUint32(r,!1);for(let u=16;u<80;u++)Rt[u]=(0,Gn.rotl)(Rt[u-3]^Rt[u-8]^Rt[u-14]^Rt[u-16],1);let{A:n,B:i,C:s,D:o,E:a}=this;for(let u=0;u<80;u++){let h,d;u<20?(h=(0,Fi.Chi)(i,s,o),d=1518500249):u<40?(h=i^s^o,d=1859775393):u<60?(h=(0,Fi.Maj)(i,s,o),d=2400959708):(h=i^s^o,d=3395469782);const p=(0,Gn.rotl)(n,5)+h+a+d+Rt[u]|0;a=o,o=s,s=(0,Gn.rotl)(i,30),i=n,n=p}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,this.set(n,i,s,o,a)}roundClean(){Rt.fill(0)}destroy(){this.set(0,0,0,0,0),this.buffer.fill(0)}}Cr.SHA1=Ha;Cr.sha1=(0,Gn.wrapConstructor)(()=>new Ha);function uo(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function du(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Ns(e,...t){if(!du(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function Qn(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Fa(e,t){Ns(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pu(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function Mi(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function st(e,t){return e<<32-t|e>>>t}const lo=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function yu(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function ho(e){for(let t=0;t<e.length;t++)e[t]=yu(e[t])}function mu(e){if(typeof e!="string")throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array(new TextEncoder().encode(e))}function Hs(e){return typeof e=="string"&&(e=mu(e)),Ns(e),e}let Ma=class{clone(){return this._cloneInto()}};function Fs(e){const t=n=>e().update(Hs(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function bu(e,t,r,n){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),u=n?4:0,h=n?0:4;e.setUint32(t+u,o,n),e.setUint32(t+h,a,n)}function wu(e,t,r){return e&t^~e&r}function gu(e,t,r){return e&t^e&r^t&r}class _u extends Ma{constructor(t,r,n,i){super(),this.blockLen=t,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(t),this.view=Mi(this.buffer)}update(t){Qn(this);const{view:r,buffer:n,blockLen:i}=this;t=Hs(t);const s=t.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const u=Mi(t);for(;i<=s-o;o+=i)this.process(u,o);continue}n.set(t.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){Qn(this),Fa(t,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(n,0),o=0);for(let p=o;p<i;p++)r[p]=0;bu(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Mi(t),u=this.outputLen;if(u%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const h=u/4,d=this.get();if(h>d.length)throw new Error("_sha2: outputLen bigger than state");for(let p=0;p<h;p++)a.setUint32(4*p,d[p],s)}digest(){const{buffer:t,outputLen:r}=this;this.digestInto(t);const n=t.slice(0,r);return this.destroy(),n}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return t.length=i,t.pos=a,t.finished=s,t.destroyed=o,i%r&&t.buffer.set(n),t}}const vu=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ct=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ut=new Uint32Array(64);class Ms extends _u{constructor(){super(64,32,8,!1),this.A=Ct[0]|0,this.B=Ct[1]|0,this.C=Ct[2]|0,this.D=Ct[3]|0,this.E=Ct[4]|0,this.F=Ct[5]|0,this.G=Ct[6]|0,this.H=Ct[7]|0}get(){const{A:t,B:r,C:n,D:i,E:s,F:o,G:a,H:u}=this;return[t,r,n,i,s,o,a,u]}set(t,r,n,i,s,o,a,u){this.A=t|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=u|0}process(t,r){for(let p=0;p<16;p++,r+=4)Ut[p]=t.getUint32(r,!1);for(let p=16;p<64;p++){const v=Ut[p-15],y=Ut[p-2],I=st(v,7)^st(v,18)^v>>>3,k=st(y,17)^st(y,19)^y>>>10;Ut[p]=k+Ut[p-7]+I+Ut[p-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:u,G:h,H:d}=this;for(let p=0;p<64;p++){const v=st(a,6)^st(a,11)^st(a,25),y=d+v+wu(a,u,h)+vu[p]+Ut[p]|0,k=(st(n,2)^st(n,13)^st(n,22))+gu(n,i,s)|0;d=h,h=u,u=a,a=o+y|0,o=s,s=i,i=n,n=y+k|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,u=u+this.F|0,h=h+this.G|0,d=d+this.H|0,this.set(n,i,s,o,a,u,h,d)}roundClean(){Ut.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}class Eu extends Ms{constructor(){super(),this.A=-1056596264,this.B=914150663,this.C=812702999,this.D=-150054599,this.E=-4191439,this.F=1750603025,this.G=1694076839,this.H=-1090891868,this.outputLen=28}}const Da=Fs(()=>new Ms),xu=Fs(()=>new Eu),Su=Object.freeze(Object.defineProperty({__proto__:null,SHA256:Ms,sha224:xu,sha256:Da},Symbol.toStringTag,{value:"Module"})),$a=_a(Su);(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.taggedHash=e.TAGGED_HASH_PREFIXES=e.TAGS=e.hash256=e.hash160=e.sha256=e.sha1=e.ripemd160=void 0;const t=Rr,r=Cr,n=$a;function i(d){return Buffer.from((0,t.ripemd160)(Uint8Array.from(d)))}e.ripemd160=i;function s(d){return Buffer.from((0,r.sha1)(Uint8Array.from(d)))}e.sha1=s;function o(d){return Buffer.from((0,n.sha256)(Uint8Array.from(d)))}e.sha256=o;function a(d){return Buffer.from((0,t.ripemd160)((0,n.sha256)(Uint8Array.from(d))))}e.hash160=a;function u(d){return Buffer.from((0,n.sha256)((0,n.sha256)(Uint8Array.from(d))))}e.hash256=u,e.TAGS=["BIP0340/challenge","BIP0340/aux","BIP0340/nonce","TapLeaf","TapBranch","TapSighash","TapTweak","KeyAgg list","KeyAgg coefficient"],e.TAGGED_HASH_PREFIXES={"BIP0340/challenge":Buffer.from([123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124,123,181,45,122,159,239,88,50,62,177,191,122,64,125,179,130,210,243,242,216,27,177,34,79,73,254,81,143,109,72,211,124]),"BIP0340/aux":Buffer.from([241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144,241,239,78,94,192,99,202,218,109,148,202,250,157,152,126,160,105,38,88,57,236,193,31,151,45,119,165,46,216,193,204,144]),"BIP0340/nonce":Buffer.from([7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47,7,73,119,52,167,155,203,53,91,155,140,125,3,79,18,28,244,52,215,62,247,45,218,25,135,0,97,251,82,191,235,47]),TapLeaf:Buffer.from([174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238,174,234,143,220,66,8,152,49,5,115,75,88,8,29,30,38,56,211,95,28,181,64,8,212,211,87,202,3,190,120,233,238]),TapBranch:Buffer.from([25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21,25,65,161,242,229,110,185,95,162,169,241,148,190,92,1,247,33,111,51,237,130,176,145,70,52,144,208,91,245,22,160,21]),TapSighash:Buffer.from([244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49,244,10,72,223,75,42,112,200,180,146,75,242,101,70,97,237,61,149,253,102,163,19,235,135,35,117,151,198,40,228,160,49]),TapTweak:Buffer.from([232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233,232,15,225,99,156,156,160,80,227,175,27,57,193,67,198,62,66,156,188,235,21,217,64,251,181,197,161,244,175,87,197,233]),"KeyAgg list":Buffer.from([72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240,72,28,151,28,60,11,70,215,240,178,117,174,89,141,78,44,126,215,49,156,89,74,92,110,199,158,160,212,153,2,148,240]),"KeyAgg coefficient":Buffer.from([191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129,191,201,4,3,77,28,136,232,200,14,34,229,61,36,86,109,100,130,78,214,66,114,129,192,145,0,249,77,205,82,201,129])};function h(d,p){return o(Buffer.concat([e.TAGGED_HASH_PREFIXES[d],p]))}e.taggedHash=h})(zt);var Di={},St={};Object.defineProperty(St,"__esModule",{value:!0});St.encode=St.decode=St.check=void 0;function Tu(e){if(e.length<8||e.length>72||e[0]!==48||e[1]!==e.length-2||e[2]!==2)return!1;const t=e[3];if(t===0||5+t>=e.length||e[4+t]!==2)return!1;const r=e[5+t];return!(r===0||6+t+r!==e.length||e[4]&128||t>1&&e[4]===0&&!(e[5]&128)||e[t+6]&128||r>1&&e[t+6]===0&&!(e[t+7]&128))}St.check=Tu;function Au(e){if(e.length<8)throw new Error("DER sequence length is too short");if(e.length>72)throw new Error("DER sequence length is too long");if(e[0]!==48)throw new Error("Expected DER sequence");if(e[1]!==e.length-2)throw new Error("DER sequence length is invalid");if(e[2]!==2)throw new Error("Expected DER integer");const t=e[3];if(t===0)throw new Error("R length is zero");if(5+t>=e.length)throw new Error("R length is too long");if(e[4+t]!==2)throw new Error("Expected DER integer (2)");const r=e[5+t];if(r===0)throw new Error("S length is zero");if(6+t+r!==e.length)throw new Error("S length is invalid");if(e[4]&128)throw new Error("R value is negative");if(t>1&&e[4]===0&&!(e[5]&128))throw new Error("R value excessively padded");if(e[t+6]&128)throw new Error("S value is negative");if(r>1&&e[t+6]===0&&!(e[t+7]&128))throw new Error("S value excessively padded");return{r:e.slice(4,4+t),s:e.slice(6+t)}}St.decode=Au;function ku(e,t){const r=e.length,n=t.length;if(r===0)throw new Error("R length is zero");if(n===0)throw new Error("S length is zero");if(r>33)throw new Error("R length is too long");if(n>33)throw new Error("S length is too long");if(e[0]&128)throw new Error("R value is negative");if(t[0]&128)throw new Error("S value is negative");if(r>1&&e[0]===0&&!(e[1]&128))throw new Error("R value excessively padded");if(n>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");const i=Buffer.allocUnsafe(6+r+n);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=e.length,e.copy(i,4),i[4+r]=2,i[5+r]=t.length,t.copy(i,6+r),i}St.encode=ku;var sr={};Object.defineProperty(sr,"__esModule",{value:!0});sr.REVERSE_OPS=sr.OPS=void 0;const ps={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_CHECKLOCKTIMEVERIFY:177,OP_NOP3:178,OP_CHECKSEQUENCEVERIFY:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_CHECKSIGADD:186,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255};sr.OPS=ps;const ja={};sr.REVERSE_OPS=ja;for(const e of Object.keys(ps)){const t=ps[e];ja[t]=e}var jt={};Object.defineProperty(jt,"__esModule",{value:!0});jt.decode=jt.encode=jt.encodingLength=void 0;const Dt=sr;function Ga(e){return e<Dt.OPS.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}jt.encodingLength=Ga;function Bu(e,t,r){const n=Ga(t);return n===1?e.writeUInt8(t,r):n===2?(e.writeUInt8(Dt.OPS.OP_PUSHDATA1,r),e.writeUInt8(t,r+1)):n===3?(e.writeUInt8(Dt.OPS.OP_PUSHDATA2,r),e.writeUInt16LE(t,r+1)):(e.writeUInt8(Dt.OPS.OP_PUSHDATA4,r),e.writeUInt32LE(t,r+1)),n}jt.encode=Bu;function Iu(e,t){const r=e.readUInt8(t);let n,i;if(r<Dt.OPS.OP_PUSHDATA1)n=r,i=1;else if(r===Dt.OPS.OP_PUSHDATA1){if(t+2>e.length)return null;n=e.readUInt8(t+1),i=2}else if(r===Dt.OPS.OP_PUSHDATA2){if(t+3>e.length)return null;n=e.readUInt16LE(t+1),i=3}else{if(t+5>e.length)return null;if(r!==Dt.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");n=e.readUInt32LE(t+1),i=5}return{opcode:r,number:n,size:i}}jt.decode=Iu;var Ur={};Object.defineProperty(Ur,"__esModule",{value:!0});Ur.encode=Ur.decode=void 0;function Pu(e,t,r){t=t||4,r=r===void 0?!0:r;const n=e.length;if(n===0)return 0;if(n>t)throw new TypeError("Script number overflow");if(r&&!(e[n-1]&127)&&(n<=1||!(e[n-2]&128)))throw new Error("Non-minimally encoded script number");if(n===5){const s=e.readUInt32LE(0),o=e.readUInt8(4);return o&128?-((o&-129)*4294967296+s):o*4294967296+s}let i=0;for(let s=0;s<n;++s)i|=e[s]<<8*s;return e[n-1]&128?-(i&~(128<<8*(n-1))):i}Ur.decode=Pu;function Ou(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function Ru(e){let t=Math.abs(e);const r=Ou(t),n=Buffer.allocUnsafe(r),i=e<0;for(let s=0;s<r;++s)n.writeUInt8(t&255,s),t>>=8;return n[r-1]&128?n.writeUInt8(i?128:0,r-1):i&&(n[r-1]|=128),n}Ur.encode=Ru;var er={},po;function Cu(){if(po)return er;po=1,Object.defineProperty(er,"__esModule",{value:!0}),er.encode=er.decode=void 0;const e=St,t=Xe(),r=Fe,{typeforce:n}=r,i=Buffer.alloc(1,0);function s(h){let d=0;for(;h[d]===0;)++d;return d===h.length?i:(h=h.slice(d),h[0]&128?Buffer.concat([i,h],1+h.length):h)}function o(h){h[0]===0&&(h=h.slice(1));const d=Buffer.alloc(32,0),p=Math.max(0,32-h.length);return h.copy(d,p),d}function a(h){const d=h.readUInt8(h.length-1);if(!(0,t.isDefinedHashType)(d))throw new Error("Invalid hashType "+d);const p=e.decode(h.slice(0,-1)),v=o(p.r),y=o(p.s);return{signature:Buffer.concat([v,y],64),hashType:d}}er.decode=a;function u(h,d){if(n({signature:r.BufferN(64),hashType:r.UInt8},{signature:h,hashType:d}),!(0,t.isDefinedHashType)(d))throw new Error("Invalid hashType "+d);const p=Buffer.allocUnsafe(1);p.writeUInt8(d,0);const v=s(h.slice(0,32)),y=s(h.slice(32,64));return Buffer.concat([e.encode(v,y),p])}return er.encode=u,er}var yo;function Xe(){return yo||(yo=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.signature=e.number=e.isCanonicalScriptSignature=e.isDefinedHashType=e.isCanonicalPubKey=e.toStack=e.fromASM=e.toASM=e.decompile=e.compile=e.countNonPushOnlyOPs=e.isPushOnly=e.OPS=void 0;const t=St,r=sr;Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return r.OPS}});const n=jt,i=Ur,s=Cu(),o=Fe,{typeforce:a}=o,u=r.OPS.OP_RESERVED;function h(O){return o.Number(O)&&(O===r.OPS.OP_0||O>=r.OPS.OP_1&&O<=r.OPS.OP_16||O===r.OPS.OP_1NEGATE)}function d(O){return o.Buffer(O)||h(O)}function p(O){return o.Array(O)&&O.every(d)}e.isPushOnly=p;function v(O){return O.length-O.filter(d).length}e.countNonPushOnlyOPs=v;function y(O){if(O.length===0)return r.OPS.OP_0;if(O.length===1){if(O[0]>=1&&O[0]<=16)return u+O[0];if(O[0]===129)return r.OPS.OP_1NEGATE}}function I(O){return Buffer.isBuffer(O)}function k(O){return o.Array(O)}function B(O){return Buffer.isBuffer(O)}function R(O){if(I(O))return O;a(o.Array,O);const K=O.reduce((V,z)=>B(z)?z.length===1&&y(z)!==void 0?V+1:V+n.encodingLength(z.length)+z.length:V+1,0),C=Buffer.allocUnsafe(K);let G=0;if(O.forEach(V=>{if(B(V)){const z=y(V);if(z!==void 0){C.writeUInt8(z,G),G+=1;return}G+=n.encode(C,V.length,G),V.copy(C,G),G+=V.length}else C.writeUInt8(V,G),G+=1}),G!==C.length)throw new Error("Could not decode chunks");return C}e.compile=R;function U(O){if(k(O))return O;a(o.Buffer,O);const K=[];let C=0;for(;C<O.length;){const G=O[C];if(G>r.OPS.OP_0&&G<=r.OPS.OP_PUSHDATA4){const V=n.decode(O,C);if(V===null||(C+=V.size,C+V.number>O.length))return null;const z=O.slice(C,C+V.number);C+=V.number;const ee=y(z);ee!==void 0?K.push(ee):K.push(z)}else K.push(G),C+=1}return K}e.decompile=U;function x(O){if(I(O)&&(O=U(O)),!O)throw new Error("Could not convert invalid chunks to ASM");return O.map(K=>{if(B(K)){const C=y(K);if(C===void 0)return K.toString("hex");K=C}return r.REVERSE_OPS[K]}).join(" ")}e.toASM=x;function g(O){return a(o.String,O),R(O.split(" ").map(K=>r.OPS[K]!==void 0?r.OPS[K]:(a(o.Hex,K),Buffer.from(K,"hex"))))}e.fromASM=g;function S(O){return O=U(O),a(p,O),O.map(K=>B(K)?K:K===r.OPS.OP_0?Buffer.allocUnsafe(0):i.encode(K-u))}e.toStack=S;function E(O){return o.isPoint(O)}e.isCanonicalPubKey=E;function F(O){const K=O&-129;return K>0&&K<4}e.isDefinedHashType=F;function D(O){return!Buffer.isBuffer(O)||!F(O[O.length-1])?!1:t.check(O.slice(0,-1))}e.isCanonicalScriptSignature=D,e.number=i,e.signature=s}(Di)),Di}Object.defineProperty(gn,"__esModule",{value:!0});gn.Transaction=void 0;const Se=Pe,Me=zt,mo=Xe(),Uu=Xe(),te=Fe,{typeforce:ot}=te;function ft(e){const t=e.length;return Se.varuint.encodingLength(t)+t}function Lu(e){const t=e.length;return Se.varuint.encodingLength(t)+e.reduce((r,n)=>r+ft(n),0)}const Mt=Buffer.allocUnsafe(0),$i=[],ji=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),bo=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),Nu=Buffer.from("ffffffffffffffff","hex"),Hu={script:Mt,valueBuffer:Nu};function Fu(e){return e.value!==void 0}class J{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(t,r){const n=new Se.BufferReader(t),i=new J;i.version=n.readInt32();const s=n.readUInt8(),o=n.readUInt8();let a=!1;s===J.ADVANCED_TRANSACTION_MARKER&&o===J.ADVANCED_TRANSACTION_FLAG?a=!0:n.offset-=2;const u=n.readVarInt();for(let d=0;d<u;++d)i.ins.push({hash:n.readSlice(32),index:n.readUInt32(),script:n.readVarSlice(),sequence:n.readUInt32(),witness:$i});const h=n.readVarInt();for(let d=0;d<h;++d)i.outs.push({value:n.readUInt64(),script:n.readVarSlice()});if(a){for(let d=0;d<u;++d)i.ins[d].witness=n.readVector();if(!i.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(i.locktime=n.readUInt32(),r)return i;if(n.offset!==t.length)throw new Error("Transaction has unexpected data");return i}static fromHex(t){return J.fromBuffer(Buffer.from(t,"hex"),!1)}static isCoinbaseHash(t){ot(te.Hash256bit,t);for(let r=0;r<32;++r)if(t[r]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&J.isCoinbaseHash(this.ins[0].hash)}addInput(t,r,n,i){return ot(te.tuple(te.Hash256bit,te.UInt32,te.maybe(te.UInt32),te.maybe(te.Buffer)),arguments),te.Null(n)&&(n=J.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:r,script:i||Mt,sequence:n,witness:$i})-1}addOutput(t,r){return ot(te.tuple(te.Buffer,te.Satoshi),arguments),this.outs.push({script:t,value:r})-1}hasWitnesses(){return this.ins.some(t=>t.witness.length!==0)}stripWitnesses(){this.ins.forEach(t=>{t.witness=$i})}weight(){const t=this.byteLength(!1),r=this.byteLength(!0);return t*3+r}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const r=t&&this.hasWitnesses();return(r?10:8)+Se.varuint.encodingLength(this.ins.length)+Se.varuint.encodingLength(this.outs.length)+this.ins.reduce((n,i)=>n+40+ft(i.script),0)+this.outs.reduce((n,i)=>n+8+ft(i.script),0)+(r?this.ins.reduce((n,i)=>n+Lu(i.witness),0):0)}clone(){const t=new J;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map(r=>({hash:r.hash,index:r.index,script:r.script,sequence:r.sequence,witness:r.witness})),t.outs=this.outs.map(r=>({script:r.script,value:r.value})),t}hashForSignature(t,r,n){if(ot(te.tuple(te.UInt32,te.Buffer,te.Number),arguments),t>=this.ins.length)return bo;const i=mo.compile(mo.decompile(r).filter(a=>a!==Uu.OPS.OP_CODESEPARATOR)),s=this.clone();if((n&31)===J.SIGHASH_NONE)s.outs=[],s.ins.forEach((a,u)=>{u!==t&&(a.sequence=0)});else if((n&31)===J.SIGHASH_SINGLE){if(t>=this.outs.length)return bo;s.outs.length=t+1;for(let a=0;a<t;a++)s.outs[a]=Hu;s.ins.forEach((a,u)=>{u!==t&&(a.sequence=0)})}n&J.SIGHASH_ANYONECANPAY?(s.ins=[s.ins[t]],s.ins[0].script=i):(s.ins.forEach(a=>{a.script=Mt}),s.ins[t].script=i);const o=Buffer.allocUnsafe(s.byteLength(!1)+4);return o.writeInt32LE(n,o.length-4),s.__toBuffer(o,0,!1),Me.hash256(o)}hashForWitnessV1(t,r,n,i,s,o){if(ot(te.tuple(te.UInt32,ot.arrayOf(te.Buffer),ot.arrayOf(te.Satoshi),te.UInt32),arguments),n.length!==this.ins.length||r.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const a=i===J.SIGHASH_DEFAULT?J.SIGHASH_ALL:i&J.SIGHASH_OUTPUT_MASK,h=(i&J.SIGHASH_INPUT_MASK)===J.SIGHASH_ANYONECANPAY,d=a===J.SIGHASH_NONE,p=a===J.SIGHASH_SINGLE;let v=Mt,y=Mt,I=Mt,k=Mt,B=Mt;if(!h){let g=Se.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(S=>{g.writeSlice(S.hash),g.writeUInt32(S.index)}),v=Me.sha256(g.end()),g=Se.BufferWriter.withCapacity(8*this.ins.length),n.forEach(S=>g.writeUInt64(S)),y=Me.sha256(g.end()),g=Se.BufferWriter.withCapacity(r.map(ft).reduce((S,E)=>S+E)),r.forEach(S=>g.writeVarSlice(S)),I=Me.sha256(g.end()),g=Se.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(S=>g.writeUInt32(S.sequence)),k=Me.sha256(g.end())}if(d||p){if(p&&t<this.outs.length){const g=this.outs[t],S=Se.BufferWriter.withCapacity(8+ft(g.script));S.writeUInt64(g.value),S.writeVarSlice(g.script),B=Me.sha256(S.end())}}else{const g=this.outs.map(E=>8+ft(E.script)).reduce((E,F)=>E+F),S=Se.BufferWriter.withCapacity(g);this.outs.forEach(E=>{S.writeUInt64(E.value),S.writeVarSlice(E.script)}),B=Me.sha256(S.end())}const R=(s?2:0)+(o?1:0),U=174-(h?49:0)-(d?32:0)+(o?32:0)+(s?37:0),x=Se.BufferWriter.withCapacity(U);if(x.writeUInt8(i),x.writeInt32(this.version),x.writeUInt32(this.locktime),x.writeSlice(v),x.writeSlice(y),x.writeSlice(I),x.writeSlice(k),d||p||x.writeSlice(B),x.writeUInt8(R),h){const g=this.ins[t];x.writeSlice(g.hash),x.writeUInt32(g.index),x.writeUInt64(n[t]),x.writeVarSlice(r[t]),x.writeUInt32(g.sequence)}else x.writeUInt32(t);if(o){const g=Se.BufferWriter.withCapacity(ft(o));g.writeVarSlice(o),x.writeSlice(Me.sha256(g.end()))}return p&&x.writeSlice(B),s&&(x.writeSlice(s),x.writeUInt8(0),x.writeUInt32(4294967295)),Me.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),x.end()]))}hashForWitnessV0(t,r,n,i){ot(te.tuple(te.UInt32,te.Buffer,te.Satoshi,te.UInt32),arguments);let s=Buffer.from([]),o,a=ji,u=ji,h=ji;if(i&J.SIGHASH_ANYONECANPAY||(s=Buffer.allocUnsafe(36*this.ins.length),o=new Se.BufferWriter(s,0),this.ins.forEach(p=>{o.writeSlice(p.hash),o.writeUInt32(p.index)}),u=Me.hash256(s)),!(i&J.SIGHASH_ANYONECANPAY)&&(i&31)!==J.SIGHASH_SINGLE&&(i&31)!==J.SIGHASH_NONE&&(s=Buffer.allocUnsafe(4*this.ins.length),o=new Se.BufferWriter(s,0),this.ins.forEach(p=>{o.writeUInt32(p.sequence)}),h=Me.hash256(s)),(i&31)!==J.SIGHASH_SINGLE&&(i&31)!==J.SIGHASH_NONE){const p=this.outs.reduce((v,y)=>v+8+ft(y.script),0);s=Buffer.allocUnsafe(p),o=new Se.BufferWriter(s,0),this.outs.forEach(v=>{o.writeUInt64(v.value),o.writeVarSlice(v.script)}),a=Me.hash256(s)}else if((i&31)===J.SIGHASH_SINGLE&&t<this.outs.length){const p=this.outs[t];s=Buffer.allocUnsafe(8+ft(p.script)),o=new Se.BufferWriter(s,0),o.writeUInt64(p.value),o.writeVarSlice(p.script),a=Me.hash256(s)}s=Buffer.allocUnsafe(156+ft(r)),o=new Se.BufferWriter(s,0);const d=this.ins[t];return o.writeInt32(this.version),o.writeSlice(u),o.writeSlice(h),o.writeSlice(d.hash),o.writeUInt32(d.index),o.writeVarSlice(r),o.writeUInt64(n),o.writeUInt32(d.sequence),o.writeSlice(a),o.writeUInt32(this.locktime),o.writeUInt32(i),Me.hash256(s)}getHash(t){return t&&this.isCoinbase()?Buffer.alloc(32,0):Me.hash256(this.__toBuffer(void 0,void 0,t))}getId(){return(0,Se.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(t,r){return this.__toBuffer(t,r,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(t,r){ot(te.tuple(te.Number,te.Buffer),arguments),this.ins[t].script=r}setWitness(t,r){ot(te.tuple(te.Number,[te.Buffer]),arguments),this.ins[t].witness=r}__toBuffer(t,r,n=!1){t||(t=Buffer.allocUnsafe(this.byteLength(n)));const i=new Se.BufferWriter(t,r||0);i.writeInt32(this.version);const s=n&&this.hasWitnesses();return s&&(i.writeUInt8(J.ADVANCED_TRANSACTION_MARKER),i.writeUInt8(J.ADVANCED_TRANSACTION_FLAG)),i.writeVarInt(this.ins.length),this.ins.forEach(o=>{i.writeSlice(o.hash),i.writeUInt32(o.index),i.writeVarSlice(o.script),i.writeUInt32(o.sequence)}),i.writeVarInt(this.outs.length),this.outs.forEach(o=>{Fu(o)?i.writeUInt64(o.value):i.writeSlice(o.valueBuffer),i.writeVarSlice(o.script)}),s&&this.ins.forEach(o=>{i.writeVector(o.witness)}),i.writeUInt32(this.locktime),r!==void 0?t.slice(r,i.offset):t}}gn.Transaction=J;J.DEFAULT_SEQUENCE=4294967295;J.SIGHASH_DEFAULT=0;J.SIGHASH_ALL=1;J.SIGHASH_NONE=2;J.SIGHASH_SINGLE=3;J.SIGHASH_ANYONECANPAY=128;J.SIGHASH_OUTPUT_MASK=3;J.SIGHASH_INPUT_MASK=128;J.ADVANCED_TRANSACTION_MARKER=0;J.ADVANCED_TRANSACTION_FLAG=1;var ae={},_n={};Object.defineProperty(_n,"__esModule",{value:!0});const Mu=9007199254740991;function Ds(e){if(e<0||e>Mu||e%1!==0)throw new RangeError("value out of range")}function an(e,t,r){if(Ds(e),t||(t=Buffer.allocUnsafe(Va(e))),!Buffer.isBuffer(t))throw new TypeError("buffer must be a Buffer instance");return r||(r=0),e<253?(t.writeUInt8(e,r),Object.assign(an,{bytes:1})):e<=65535?(t.writeUInt8(253,r),t.writeUInt16LE(e,r+1),Object.assign(an,{bytes:3})):e<=4294967295?(t.writeUInt8(254,r),t.writeUInt32LE(e,r+1),Object.assign(an,{bytes:5})):(t.writeUInt8(255,r),t.writeUInt32LE(e>>>0,r+1),t.writeUInt32LE(e/4294967296|0,r+5),Object.assign(an,{bytes:9})),t}_n.encode=an;function cn(e,t){if(!Buffer.isBuffer(e))throw new TypeError("buffer must be a Buffer instance");t||(t=0);const r=e.readUInt8(t);if(r<253)return Object.assign(cn,{bytes:1}),r;if(r===253)return Object.assign(cn,{bytes:3}),e.readUInt16LE(t+1);if(r===254)return Object.assign(cn,{bytes:5}),e.readUInt32LE(t+1);{Object.assign(cn,{bytes:9});const n=e.readUInt32LE(t+1),s=e.readUInt32LE(t+5)*4294967296+n;return Ds(s),s}}_n.decode=cn;function Va(e){return Ds(e),e<253?1:e<=65535?3:e<=4294967295?5:9}_n.encodingLength=Va;var Gi={},ui={},He={};Object.defineProperty(He,"__esModule",{value:!0});He.testnet=He.regtest=He.bitcoin=void 0;He.bitcoin={messagePrefix:`Bitcoin Signed Message:
|
|
7
7
|
`,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};He.regtest={messagePrefix:`Bitcoin Signed Message:
|
|
8
8
|
`,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};He.testnet={messagePrefix:`Bitcoin Signed Message:
|
|
9
|
-
`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Ye={};Object.defineProperty(Ye,"__esModule",{value:!0});Ye.value=Ye.prop=void 0;function ku(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[t]=n,n},set(n){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}Ye.prop=ku;function Bu(e){let t;return()=>(t!==void 0||(t=e()),t)}Ye.value=Bu;Object.defineProperty(ui,"__esModule",{value:!0});ui.p2data=void 0;const Iu=He,qn=Xe(),at=Fe,ho=Ye,po=qn.OPS;function Pu(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,at.typeforce)({network:at.typeforce.maybe(at.typeforce.Object),output:at.typeforce.maybe(at.typeforce.Buffer),data:at.typeforce.maybe(at.typeforce.arrayOf(at.typeforce.Buffer))},e);const n={name:"embed",network:e.network||Iu.bitcoin};if(ho.prop(n,"output",()=>{if(e.data)return qn.compile([po.OP_RETURN].concat(e.data))}),ho.prop(n,"data",()=>{if(e.output)return qn.decompile(e.output).slice(1)}),t.validate&&e.output){const i=qn.decompile(e.output);if(i[0]!==po.OP_RETURN)throw new TypeError("Output is invalid");if(!i.slice(1).every(at.typeforce.Buffer))throw new TypeError("Output is invalid");if(e.data&&!(0,at.stacksEqual)(e.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,e)}ui.p2data=Pu;var li={};Object.defineProperty(li,"__esModule",{value:!0});li.p2ms=void 0;const Ou=He,xr=Xe(),xe=Fe,Ht=Ye,Sr=xr.OPS,Cn=Sr.OP_RESERVED;function Ru(e,t){if(!e.input&&!e.output&&!(e.pubkeys&&e.m!==void 0)&&!e.signatures)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{});function r(u){return xr.isCanonicalScriptSignature(u)||(t.allowIncomplete&&u===Sr.OP_0)!==void 0}(0,xe.typeforce)({network:xe.typeforce.maybe(xe.typeforce.Object),m:xe.typeforce.maybe(xe.typeforce.Number),n:xe.typeforce.maybe(xe.typeforce.Number),output:xe.typeforce.maybe(xe.typeforce.Buffer),pubkeys:xe.typeforce.maybe(xe.typeforce.arrayOf(xe.isPoint)),signatures:xe.typeforce.maybe(xe.typeforce.arrayOf(r)),input:xe.typeforce.maybe(xe.typeforce.Buffer)},e);const i={network:e.network||Ou.bitcoin};let s=[],o=!1;function a(u){o||(o=!0,s=xr.decompile(u),i.m=s[0]-Cn,i.n=s[s.length-2]-Cn,i.pubkeys=s.slice(1,-2))}if(Ht.prop(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return xr.compile([].concat(Cn+e.m,e.pubkeys,Cn+i.n,Sr.OP_CHECKMULTISIG))}),Ht.prop(i,"m",()=>{if(i.output)return a(i.output),i.m}),Ht.prop(i,"n",()=>{if(i.pubkeys)return i.pubkeys.length}),Ht.prop(i,"pubkeys",()=>{if(e.output)return a(e.output),i.pubkeys}),Ht.prop(i,"signatures",()=>{if(e.input)return xr.decompile(e.input).slice(1)}),Ht.prop(i,"input",()=>{if(e.signatures)return xr.compile([Sr.OP_0].concat(e.signatures))}),Ht.prop(i,"witness",()=>{if(i.input)return[]}),Ht.prop(i,"name",()=>{if(!(!i.m||!i.n))return`p2ms(${i.m} of ${i.n})`}),t.validate){if(e.output){if(a(e.output),!xe.typeforce.Number(s[0]))throw new TypeError("Output is invalid");if(!xe.typeforce.Number(s[s.length-2]))throw new TypeError("Output is invalid");if(s[s.length-1]!==Sr.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(i.m<=0||i.n>16||i.m>i.n||i.n!==s.length-3)throw new TypeError("Output is invalid");if(!i.pubkeys.every(u=>(0,xe.isPoint)(u)))throw new TypeError("Output is invalid");if(e.m!==void 0&&e.m!==i.m)throw new TypeError("m mismatch");if(e.n!==void 0&&e.n!==i.n)throw new TypeError("n mismatch");if(e.pubkeys&&!(0,xe.stacksEqual)(e.pubkeys,i.pubkeys))throw new TypeError("Pubkeys mismatch")}if(e.pubkeys){if(e.n!==void 0&&e.n!==e.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(i.n=e.pubkeys.length,i.n<i.m)throw new TypeError("Pubkey count cannot be less than m")}if(e.signatures){if(e.signatures.length<i.m)throw new TypeError("Not enough signatures provided");if(e.signatures.length>i.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==Sr.OP_0)throw new TypeError("Input is invalid");if(i.signatures.length===0||!i.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!(0,xe.stacksEqual)(e.signatures,i.signatures))throw new TypeError("Signature mismatch");if(e.m!==void 0&&e.m!==e.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(i,e)}li.p2ms=Ru;var di={};Object.defineProperty(di,"__esModule",{value:!0});di.p2pk=void 0;const Cu=He,Tr=Xe(),nt=Fe,vr=Ye,yo=Tr.OPS;function Uu(e,t){if(!e.input&&!e.output&&!e.pubkey&&!e.input&&!e.signature)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,nt.typeforce)({network:nt.typeforce.maybe(nt.typeforce.Object),output:nt.typeforce.maybe(nt.typeforce.Buffer),pubkey:nt.typeforce.maybe(nt.isPoint),signature:nt.typeforce.maybe(Tr.isCanonicalScriptSignature),input:nt.typeforce.maybe(nt.typeforce.Buffer)},e);const r=vr.value(()=>Tr.decompile(e.input)),i={name:"p2pk",network:e.network||Cu.bitcoin};if(vr.prop(i,"output",()=>{if(e.pubkey)return Tr.compile([e.pubkey,yo.OP_CHECKSIG])}),vr.prop(i,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),vr.prop(i,"signature",()=>{if(e.input)return r()[0]}),vr.prop(i,"input",()=>{if(e.signature)return Tr.compile([e.signature])}),vr.prop(i,"witness",()=>{if(i.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==yo.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,nt.isPoint)(i.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(i.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(i.input))throw new TypeError("Signature mismatch");if(e.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!Tr.isCanonicalScriptSignature(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}di.p2pk=Uu;var hi={};function Lu(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var o=e.length,a=e.charAt(0),u=Math.log(o)/Math.log(256),d=Math.log(256)/Math.log(o);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var I=0,k=0,B=0,R=p.length;B!==R&&p[B]===0;)B++,I++;for(var U=(R-B)*d+1>>>0,x=new Uint8Array(U);B!==R;){for(var g=p[B],S=0,E=U-1;(g!==0||S<k)&&E!==-1;E--,S++)g+=256*x[E]>>>0,x[E]=g%o>>>0,g=g/o>>>0;if(g!==0)throw new Error("Non-zero carry");k=S,B++}for(var F=U-k;F!==U&&x[F]===0;)F++;for(var D=a.repeat(I);F<U;++F)D+=e.charAt(x[F]);return D}function y(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;for(var I=0,k=0,B=0;p[I]===a;)k++,I++;for(var R=(p.length-I)*u+1>>>0,U=new Uint8Array(R);p[I];){var x=p.charCodeAt(I);if(x>255)return;var g=t[x];if(g===255)return;for(var S=0,E=R-1;(g!==0||S<B)&&E!==-1;E--,S++)g+=o*U[E]>>>0,U[E]=g%256>>>0,g=g/256>>>0;if(g!==0)throw new Error("Non-zero carry");B=S,I++}for(var F=R-B;F!==R&&U[F]===0;)F++;for(var D=new Uint8Array(k+(R-F)),O=k;F!==R;)D[O++]=U[F++];return D}function v(p){var I=y(p);if(I)return I;throw new Error("Non-base"+o+" character")}return{encode:h,decodeUnsafe:y,decode:v}}var Nu=Lu;const Hu=Nu,Fu="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var Mu=Hu(Fu),Vi=Mu,Du=function(e){function t(s){var o=Uint8Array.from(s),a=e(o),u=o.length+4,d=new Uint8Array(u);return d.set(o,0),d.set(a.subarray(0,4),o.length),Vi.encode(d,u)}function r(s){var o=s.slice(0,-4),a=s.slice(-4),u=e(o);if(!(a[0]^u[0]|a[1]^u[1]|a[2]^u[2]|a[3]^u[3]))return o}function n(s){var o=Vi.decodeUnsafe(s);if(o)return r(o)}function i(s){var o=Vi.decode(s),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:i,decodeUnsafe:n}},{sha256:mo}=St,$u=Du;function ju(e){return mo(mo(e))}var Fs=$u(ju);Object.defineProperty(hi,"__esModule",{value:!0});hi.p2pkh=void 0;const zi=Wt,Gu=He,Ar=Xe(),De=Fe,bt=Ye,bo=Fs,Ft=Ar.OPS;function Vu(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,De.typeforce)({network:De.typeforce.maybe(De.typeforce.Object),address:De.typeforce.maybe(De.typeforce.String),hash:De.typeforce.maybe(De.typeforce.BufferN(20)),output:De.typeforce.maybe(De.typeforce.BufferN(25)),pubkey:De.typeforce.maybe(De.isPoint),signature:De.typeforce.maybe(Ar.isCanonicalScriptSignature),input:De.typeforce.maybe(De.typeforce.Buffer)},e);const r=bt.value(()=>{const o=Buffer.from(bo.decode(e.address)),a=o.readUInt8(0),u=o.slice(1);return{version:a,hash:u}}),n=bt.value(()=>Ar.decompile(e.input)),i=e.network||Gu.bitcoin,s={name:"p2pkh",network:i};if(bt.prop(s,"address",()=>{if(!s.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(i.pubKeyHash,0),s.hash.copy(o,1),bo.encode(o)}),bt.prop(s,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return r().hash;if(e.pubkey||s.pubkey)return zi.hash160(e.pubkey||s.pubkey)}),bt.prop(s,"output",()=>{if(s.hash)return Ar.compile([Ft.OP_DUP,Ft.OP_HASH160,s.hash,Ft.OP_EQUALVERIFY,Ft.OP_CHECKSIG])}),bt.prop(s,"pubkey",()=>{if(e.input)return n()[1]}),bt.prop(s,"signature",()=>{if(e.input)return n()[0]}),bt.prop(s,"input",()=>{if(e.pubkey&&e.signature)return Ar.compile([e.signature,e.pubkey])}),bt.prop(s,"witness",()=>{if(s.input)return[]}),t.validate){let o=Buffer.from([]);if(e.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");o=r().hash}if(e.hash){if(o.length>0&&!o.equals(e.hash))throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==25||e.output[0]!==Ft.OP_DUP||e.output[1]!==Ft.OP_HASH160||e.output[2]!==20||e.output[23]!==Ft.OP_EQUALVERIFY||e.output[24]!==Ft.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=e.output.slice(3,23);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.pubkey){const a=zi.hash160(e.pubkey);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!Ar.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,De.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const u=zi.hash160(a[1]);if(o.length>0&&!o.equals(u))throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}hi.p2pkh=Vu;var pi={};Object.defineProperty(pi,"__esModule",{value:!0});pi.p2sh=void 0;const wo=Wt,zu=He,ut=Xe(),fe=Fe,ct=Ye,go=Fs,Kr=ut.OPS;function qu(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,fe.typeforce)({network:fe.typeforce.maybe(fe.typeforce.Object),address:fe.typeforce.maybe(fe.typeforce.String),hash:fe.typeforce.maybe(fe.typeforce.BufferN(20)),output:fe.typeforce.maybe(fe.typeforce.BufferN(23)),redeem:fe.typeforce.maybe({network:fe.typeforce.maybe(fe.typeforce.Object),output:fe.typeforce.maybe(fe.typeforce.Buffer),input:fe.typeforce.maybe(fe.typeforce.Buffer),witness:fe.typeforce.maybe(fe.typeforce.arrayOf(fe.typeforce.Buffer))}),input:fe.typeforce.maybe(fe.typeforce.Buffer),witness:fe.typeforce.maybe(fe.typeforce.arrayOf(fe.typeforce.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||zu.bitcoin);const n={network:r},i=ct.value(()=>{const a=Buffer.from(go.decode(e.address)),u=a.readUInt8(0),d=a.slice(1);return{version:u,hash:d}}),s=ct.value(()=>ut.decompile(e.input)),o=ct.value(()=>{const a=s(),u=a[a.length-1];return{network:r,output:u===Kr.OP_FALSE?Buffer.from([]):u,input:ut.compile(a.slice(0,-1)),witness:e.witness||[]}});if(ct.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),go.encode(a)}),ct.prop(n,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return i().hash;if(n.redeem&&n.redeem.output)return wo.hash160(n.redeem.output)}),ct.prop(n,"output",()=>{if(n.hash)return ut.compile([Kr.OP_HASH160,n.hash,Kr.OP_EQUAL])}),ct.prop(n,"redeem",()=>{if(e.input)return o()}),ct.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return ut.compile([].concat(ut.decompile(e.redeem.input),e.redeem.output))}),ct.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),ct.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),t.validate){let a=Buffer.from([]);if(e.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(i().hash.length!==20)throw new TypeError("Invalid address");a=i().hash}if(e.hash){if(a.length>0&&!a.equals(e.hash))throw new TypeError("Hash mismatch");a=e.hash}if(e.output){if(e.output.length!==23||e.output[0]!==Kr.OP_HASH160||e.output[1]!==20||e.output[22]!==Kr.OP_EQUAL)throw new TypeError("Output is invalid");const d=e.output.slice(2,22);if(a.length>0&&!a.equals(d))throw new TypeError("Hash mismatch");a=d}const u=d=>{if(d.output){const h=ut.decompile(d.output);if(!h||h.length<1)throw new TypeError("Redeem.output too short");if(d.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(ut.countNonPushOnlyOPs(h)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const y=wo.hash160(d.output);if(a.length>0&&!a.equals(y))throw new TypeError("Hash mismatch");a=y}if(d.input){const h=d.input.length>0,y=d.witness&&d.witness.length>0;if(!h&&!y)throw new TypeError("Empty input");if(h&&y)throw new TypeError("Input and witness provided");if(h){const v=ut.decompile(d.input);if(!ut.isPushOnly(v))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const d=s();if(!d||d.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");u(o())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const d=o();if(e.redeem.output&&!e.redeem.output.equals(d.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(d.input))throw new TypeError("Redeem.input mismatch")}u(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!(0,fe.stacksEqual)(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,e)}pi.p2sh=qu;var yi={},kt={};Object.defineProperty(kt,"__esModule",{value:!0});kt.bech32m=kt.bech32=void 0;const ei="qpzry9x8gf2tvdw0s3jn54khce6mua7l",Da={};for(let e=0;e<ei.length;e++){const t=ei.charAt(e);Da[t]=e}function Ir(e){const t=e>>25;return(e&33554431)<<5^-(t>>0&1)&996825010^-(t>>1&1)&642813549^-(t>>2&1)&513874426^-(t>>3&1)&1027748829^-(t>>4&1)&705979059}function _o(e){let t=1;for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+e+")";t=Ir(t)^n>>5}t=Ir(t);for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);t=Ir(t)^n&31}return t}function Ms(e,t,r,n){let i=0,s=0;const o=(1<<r)-1,a=[];for(let u=0;u<e.length;++u)for(i=i<<t|e[u],s+=t;s>=r;)s-=r,a.push(i>>s&o);if(n)s>0&&a.push(i<<r-s&o);else{if(s>=t)return"Excess padding";if(i<<r-s&o)return"Non-zero padding"}return a}function Wu(e){return Ms(e,8,5,!0)}function Ku(e){const t=Ms(e,5,8,!1);if(Array.isArray(t))return t}function Yu(e){const t=Ms(e,5,8,!1);if(Array.isArray(t))return t;throw new Error(t)}function $a(e){let t;e==="bech32"?t=1:t=734539939;function r(o,a,u){if(u=u||90,o.length+7+a.length>u)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let d=_o(o);if(typeof d=="string")throw new Error(d);let h=o+"1";for(let y=0;y<a.length;++y){const v=a[y];if(v>>5)throw new Error("Non 5-bit word");d=Ir(d)^v,h+=ei.charAt(v)}for(let y=0;y<6;++y)d=Ir(d);d^=t;for(let y=0;y<6;++y){const v=d>>(5-y)*5&31;h+=ei.charAt(v)}return h}function n(o,a){if(a=a||90,o.length<8)return o+" too short";if(o.length>a)return"Exceeds length limit";const u=o.toLowerCase(),d=o.toUpperCase();if(o!==u&&o!==d)return"Mixed-case string "+o;o=u;const h=o.lastIndexOf("1");if(h===-1)return"No separator character for "+o;if(h===0)return"Missing prefix for "+o;const y=o.slice(0,h),v=o.slice(h+1);if(v.length<6)return"Data too short";let p=_o(y);if(typeof p=="string")return p;const I=[];for(let k=0;k<v.length;++k){const B=v.charAt(k),R=Da[B];if(R===void 0)return"Unknown character "+B;p=Ir(p)^R,!(k+6>=v.length)&&I.push(R)}return p!==t?"Invalid checksum for "+o:{prefix:y,words:I}}function i(o,a){const u=n(o,a);if(typeof u=="object")return u}function s(o,a){const u=n(o,a);if(typeof u=="object")return u;throw new Error(u)}return{decodeUnsafe:i,decode:s,encode:r,toWords:Wu,fromWordsUnsafe:Ku,fromWords:Yu}}kt.bech32=$a("bech32");kt.bech32m=$a("bech32m");Object.defineProperty(yi,"__esModule",{value:!0});yi.p2wpkh=void 0;const qi=Wt,Xu=He,Wn=Xe(),Ae=Fe,Mt=Ye,Un=kt,vo=Wn.OPS,Ju=Buffer.alloc(0);function Qu(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ae.typeforce)({address:Ae.typeforce.maybe(Ae.typeforce.String),hash:Ae.typeforce.maybe(Ae.typeforce.BufferN(20)),input:Ae.typeforce.maybe(Ae.typeforce.BufferN(0)),network:Ae.typeforce.maybe(Ae.typeforce.Object),output:Ae.typeforce.maybe(Ae.typeforce.BufferN(22)),pubkey:Ae.typeforce.maybe(Ae.isPoint),signature:Ae.typeforce.maybe(Wn.isCanonicalScriptSignature),witness:Ae.typeforce.maybe(Ae.typeforce.arrayOf(Ae.typeforce.Buffer))},e);const r=Mt.value(()=>{const s=Un.bech32.decode(e.address),o=s.words.shift(),a=Un.bech32.fromWords(s.words);return{version:o,prefix:s.prefix,data:Buffer.from(a)}}),n=e.network||Xu.bitcoin,i={name:"p2wpkh",network:n};if(Mt.prop(i,"address",()=>{if(!i.hash)return;const s=Un.bech32.toWords(i.hash);return s.unshift(0),Un.bech32.encode(n.bech32,s)}),Mt.prop(i,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return r().data;if(e.pubkey||i.pubkey)return qi.hash160(e.pubkey||i.pubkey)}),Mt.prop(i,"output",()=>{if(i.hash)return Wn.compile([vo.OP_0,i.hash])}),Mt.prop(i,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),Mt.prop(i,"signature",()=>{if(e.witness)return e.witness[0]}),Mt.prop(i,"input",()=>{if(i.witness)return Ju}),Mt.prop(i,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let s=Buffer.from([]);if(e.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");s=r().data}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==vo.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(s.length>0&&!s.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");s=e.output.slice(2)}if(e.pubkey){const o=qi.hash160(e.pubkey);if(s.length>0&&!s.equals(o))throw new TypeError("Hash mismatch");if(s=o,!(0,Ae.isPoint)(e.pubkey)||e.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(e.witness){if(e.witness.length!==2)throw new TypeError("Witness is invalid");if(!Wn.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,Ae.isPoint)(e.witness[1])||e.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(e.signature&&!e.signature.equals(e.witness[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(e.witness[1]))throw new TypeError("Pubkey mismatch");const o=qi.hash160(e.witness[1]);if(s.length>0&&!s.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}yi.p2wpkh=Qu;var mi={};Object.defineProperty(mi,"__esModule",{value:!0});mi.p2wsh=void 0;const Eo=Wt,Zu=He,vt=Xe(),ce=Fe,wt=Ye,Ln=kt,xo=vt.OPS,Wi=Buffer.alloc(0);function Nn(e){return!!(Buffer.isBuffer(e)&&e.length===65&&e[0]===4&&(0,ce.isPoint)(e))}function el(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,ce.typeforce)({network:ce.typeforce.maybe(ce.typeforce.Object),address:ce.typeforce.maybe(ce.typeforce.String),hash:ce.typeforce.maybe(ce.typeforce.BufferN(32)),output:ce.typeforce.maybe(ce.typeforce.BufferN(34)),redeem:ce.typeforce.maybe({input:ce.typeforce.maybe(ce.typeforce.Buffer),network:ce.typeforce.maybe(ce.typeforce.Object),output:ce.typeforce.maybe(ce.typeforce.Buffer),witness:ce.typeforce.maybe(ce.typeforce.arrayOf(ce.typeforce.Buffer))}),input:ce.typeforce.maybe(ce.typeforce.BufferN(0)),witness:ce.typeforce.maybe(ce.typeforce.arrayOf(ce.typeforce.Buffer))},e);const r=wt.value(()=>{const o=Ln.bech32.decode(e.address),a=o.words.shift(),u=Ln.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(u)}}),n=wt.value(()=>vt.decompile(e.redeem.input));let i=e.network;i||(i=e.redeem&&e.redeem.network||Zu.bitcoin);const s={network:i};if(wt.prop(s,"address",()=>{if(!s.hash)return;const o=Ln.bech32.toWords(s.hash);return o.unshift(0),Ln.bech32.encode(i.bech32,o)}),wt.prop(s,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return r().data;if(s.redeem&&s.redeem.output)return Eo.sha256(s.redeem.output)}),wt.prop(s,"output",()=>{if(s.hash)return vt.compile([xo.OP_0,s.hash])}),wt.prop(s,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:Wi,witness:e.witness.slice(0,-1)}}),wt.prop(s,"input",()=>{if(s.witness)return Wi}),wt.prop(s,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const o=vt.toStack(n());return s.redeem=Object.assign({witness:o},e.redeem),s.redeem.input=Wi,[].concat(o,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),wt.prop(s,"name",()=>{const o=["p2wsh"];return s.redeem!==void 0&&s.redeem.name!==void 0&&o.push(s.redeem.name),o.join("-")}),t.validate){let o=Buffer.from([]);if(e.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");o=r().data}if(e.hash){if(o.length>0&&!o.equals(e.hash))throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==34||e.output[0]!==xo.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const a=e.output.slice(2);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.redeem){if(e.redeem.network&&e.redeem.network!==i)throw new TypeError("Network mismatch");if(e.redeem.input&&e.redeem.input.length>0&&e.redeem.witness&&e.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(e.redeem.output){const a=vt.decompile(e.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(e.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(vt.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const u=Eo.sha256(e.redeem.output);if(o.length>0&&!o.equals(u))throw new TypeError("Hash mismatch");o=u}if(e.redeem.input&&!vt.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!(0,ce.stacksEqual)(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&n().some(Nn)||e.redeem.output&&(vt.decompile(e.redeem.output)||[]).some(Nn))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const a=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(Nn)||(vt.decompile(a)||[]).some(Nn))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(s,e)}mi.p2wsh=el;var Yr={},ar={};Object.defineProperty(ar,"__esModule",{value:!0});ar.getEccLib=ar.initEccLib=void 0;const ln={};function tl(e,t){e?e!==ln.eccLib&&(t!=null&&t.DANGER_DO_NOT_VERIFY_ECCLIB||nl(e),ln.eccLib=e):ln.eccLib=e}ar.initEccLib=tl;function rl(){if(!ln.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return ln.eccLib}ar.getEccLib=rl;const gt=e=>Buffer.from(e,"hex");function nl(e){Qe(typeof e.isXOnlyPoint=="function"),Qe(e.isXOnlyPoint(gt("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Qe(e.isXOnlyPoint(gt("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Qe(e.isXOnlyPoint(gt("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Qe(e.isXOnlyPoint(gt("0000000000000000000000000000000000000000000000000000000000000001"))),Qe(!e.isXOnlyPoint(gt("0000000000000000000000000000000000000000000000000000000000000000"))),Qe(!e.isXOnlyPoint(gt("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Qe(typeof e.xOnlyPointAddTweak=="function"),il.forEach(t=>{const r=e.xOnlyPointAddTweak(gt(t.pubkey),gt(t.tweak));t.result===null?Qe(r===null):(Qe(r!==null),Qe(r.parity===t.parity),Qe(Buffer.from(r.xOnlyPubkey).equals(gt(t.result))))})}function Qe(e){if(!e)throw new Error("ecc library invalid")}const il=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];var Ds={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.tweakKey=e.tapTweakHash=e.tapleafHash=e.findScriptPath=e.toHashTree=e.rootHashFromPath=e.MAX_TAPTREE_DEPTH=e.LEAF_VERSION_TAPSCRIPT=void 0;const t=It,r=ar,n=Wt,i=Pe,s=Fe;e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const o=k=>"left"in k&&"right"in k;function a(k,B){if(k.length<33)throw new TypeError(`The control-block length is too small. Got ${k.length}, expected min 33.`);const R=(k.length-33)/32;let U=B;for(let x=0;x<R;x++){const g=k.slice(33+32*x,65+32*x);U.compare(g)<0?U=p(U,g):U=p(g,U)}return U}e.rootHashFromPath=a;function u(k){if((0,s.isTapleaf)(k))return{hash:h(k)};const B=[u(k[0]),u(k[1])];B.sort((x,g)=>x.hash.compare(g.hash));const[R,U]=B;return{hash:p(R.hash,U.hash),left:R,right:U}}e.toHashTree=u;function d(k,B){if(o(k)){const R=d(k.left,B);if(R!==void 0)return[...R,k.right.hash];const U=d(k.right,B);if(U!==void 0)return[...U,k.left.hash]}else if(k.hash.equals(B))return[]}e.findScriptPath=d;function h(k){const B=k.version||e.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([B]),I(k.output)]))}e.tapleafHash=h;function y(k,B){return n.taggedHash("TapTweak",t.Buffer.concat(B?[k,B]:[k]))}e.tapTweakHash=y;function v(k,B){if(!t.Buffer.isBuffer(k)||k.length!==32||B&&B.length!==32)return null;const R=y(k,B),U=(0,r.getEccLib)().xOnlyPointAddTweak(k,R);return!U||U.xOnlyPubkey===null?null:{parity:U.parity,x:t.Buffer.from(U.xOnlyPubkey)}}e.tweakKey=v;function p(k,B){return n.taggedHash("TapBranch",t.Buffer.concat([k,B]))}function I(k){const B=i.varuint.encodingLength(k.length),R=t.Buffer.allocUnsafe(B);return i.varuint.encode(k.length,R),t.Buffer.concat([R,k])}})(Ds);var $e={},So;function sl(){if(So)return $e;So=1,Object.defineProperty($e,"__esModule",{value:!0}),$e.toOutputScript=$e.fromOutputScript=$e.toBech32=$e.toBase58Check=$e.fromBech32=$e.fromBase58Check=void 0;const e=He,t=$s(),r=Xe(),n=Fe,i=kt,s=Fs,o=40,a=2,u=16,d=2,h=80,y="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function v(x,g){const S=x.slice(2);if(S.length<a||S.length>o)throw new TypeError("Invalid program length for segwit address");const E=x[0]-h;if(E<d||E>u)throw new TypeError("Invalid version for segwit address");if(x[1]!==S.length)throw new TypeError("Invalid script for segwit address");return console.warn(y),B(S,E,g.bech32)}function p(x){const g=Buffer.from(s.decode(x));if(g.length<21)throw new TypeError(x+" is too short");if(g.length>21)throw new TypeError(x+" is too long");const S=g.readUInt8(0),E=g.slice(1);return{version:S,hash:E}}$e.fromBase58Check=p;function I(x){let g,S;try{g=i.bech32.decode(x)}catch{}if(g){if(S=g.words[0],S!==0)throw new TypeError(x+" uses wrong encoding")}else if(g=i.bech32m.decode(x),S=g.words[0],S===0)throw new TypeError(x+" uses wrong encoding");const E=i.bech32.fromWords(g.words.slice(1));return{version:S,prefix:g.prefix,data:Buffer.from(E)}}$e.fromBech32=I;function k(x,g){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const S=Buffer.allocUnsafe(21);return S.writeUInt8(g,0),x.copy(S,1),s.encode(S)}$e.toBase58Check=k;function B(x,g,S){const E=i.bech32.toWords(x);return E.unshift(g),g===0?i.bech32.encode(S,E):i.bech32m.encode(S,E)}$e.toBech32=B;function R(x,g){g=g||e.bitcoin;try{return t.p2pkh({output:x,network:g}).address}catch{}try{return t.p2sh({output:x,network:g}).address}catch{}try{return t.p2wpkh({output:x,network:g}).address}catch{}try{return t.p2wsh({output:x,network:g}).address}catch{}try{return t.p2tr({output:x,network:g}).address}catch{}try{return v(x,g)}catch{}throw new Error(r.toASM(x)+" has no matching Address")}$e.fromOutputScript=R;function U(x,g){g=g||e.bitcoin;let S,E;try{S=p(x)}catch{}if(S){if(S.version===g.pubKeyHash)return t.p2pkh({hash:S.hash}).output;if(S.version===g.scriptHash)return t.p2sh({hash:S.hash}).output}else{try{E=I(x)}catch{}if(E){if(E.prefix!==g.bech32)throw new Error(x+" has an invalid prefix");if(E.version===0){if(E.data.length===20)return t.p2wpkh({hash:E.data}).output;if(E.data.length===32)return t.p2wsh({hash:E.data}).output}else if(E.version===1){if(E.data.length===32)return t.p2tr({pubkey:E.data}).output}else if(E.version>=d&&E.version<=u&&E.data.length>=a&&E.data.length<=o)return console.warn(y),r.compile([E.version+h,E.data])}}throw new Error(x+" has no matching Script")}return $e.toOutputScript=U,$e}var To;function ol(){if(To)return Yr;To=1,Object.defineProperty(Yr,"__esModule",{value:!0}),Yr.p2tr=void 0;const e=It,t=He,r=Xe(),n=Fe,i=ar,s=Ds,o=Ye,a=kt,u=sl(),d=r.OPS,h=1,y=80;function v(p,I){if(!p.address&&!p.output&&!p.pubkey&&!p.internalPubkey&&!(p.witness&&p.witness.length>1))throw new TypeError("Not enough data");I=Object.assign({validate:!0},I||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},p);const k=o.value(()=>(0,u.fromBech32)(p.address)),B=o.value(()=>{if(!(!p.witness||!p.witness.length))return p.witness.length>=2&&p.witness[p.witness.length-1][0]===y?p.witness.slice(0,-1):p.witness.slice()}),R=o.value(()=>{if(p.scriptTree)return(0,s.toHashTree)(p.scriptTree);if(p.hash)return{hash:p.hash}}),U=p.network||t.bitcoin,x={name:"p2tr",network:U};if(o.prop(x,"address",()=>{if(!x.pubkey)return;const g=a.bech32m.toWords(x.pubkey);return g.unshift(h),a.bech32m.encode(U.bech32,g)}),o.prop(x,"hash",()=>{const g=R();if(g)return g.hash;const S=B();if(S&&S.length>1){const E=S[S.length-1],F=E[0]&n.TAPLEAF_VERSION_MASK,D=S[S.length-2],O=(0,s.tapleafHash)({output:D,version:F});return(0,s.rootHashFromPath)(E,O)}return null}),o.prop(x,"output",()=>{if(x.pubkey)return r.compile([d.OP_1,x.pubkey])}),o.prop(x,"redeemVersion",()=>p.redeemVersion?p.redeemVersion:p.redeem&&p.redeem.redeemVersion!==void 0&&p.redeem.redeemVersion!==null?p.redeem.redeemVersion:s.LEAF_VERSION_TAPSCRIPT),o.prop(x,"redeem",()=>{const g=B();if(!(!g||g.length<2))return{output:g[g.length-2],witness:g.slice(0,-2),redeemVersion:g[g.length-1][0]&n.TAPLEAF_VERSION_MASK}}),o.prop(x,"pubkey",()=>{if(p.pubkey)return p.pubkey;if(p.output)return p.output.slice(2);if(p.address)return k().data;if(x.internalPubkey){const g=(0,s.tweakKey)(x.internalPubkey,x.hash);if(g)return g.x}}),o.prop(x,"internalPubkey",()=>{if(p.internalPubkey)return p.internalPubkey;const g=B();if(g&&g.length>1)return g[g.length-1].slice(1,33)}),o.prop(x,"signature",()=>{if(p.signature)return p.signature;const g=B();if(!(!g||g.length!==1))return g[0]}),o.prop(x,"witness",()=>{if(p.witness)return p.witness;const g=R();if(g&&p.redeem&&p.redeem.output&&p.internalPubkey){const S=(0,s.tapleafHash)({output:p.redeem.output,version:x.redeemVersion}),E=(0,s.findScriptPath)(g,S);if(!E)return;const F=(0,s.tweakKey)(p.internalPubkey,g.hash);if(!F)return;const D=e.Buffer.concat([e.Buffer.from([x.redeemVersion|F.parity]),p.internalPubkey].concat(E));return[p.redeem.output,D]}if(p.signature)return[p.signature]}),I.validate){let g=e.Buffer.from([]);if(p.address){if(U&&U.bech32!==k().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(k().version!==h)throw new TypeError("Invalid address version");if(k().data.length!==32)throw new TypeError("Invalid address data");g=k().data}if(p.pubkey){if(g.length>0&&!g.equals(p.pubkey))throw new TypeError("Pubkey mismatch");g=p.pubkey}if(p.output){if(p.output.length!==34||p.output[0]!==d.OP_1||p.output[1]!==32)throw new TypeError("Output is invalid");if(g.length>0&&!g.equals(p.output.slice(2)))throw new TypeError("Pubkey mismatch");g=p.output.slice(2)}if(p.internalPubkey){const F=(0,s.tweakKey)(p.internalPubkey,x.hash);if(g.length>0&&!g.equals(F.x))throw new TypeError("Pubkey mismatch");g=F.x}if(g&&g.length&&!(0,i.getEccLib)().isXOnlyPoint(g))throw new TypeError("Invalid pubkey for p2tr");const S=R();if(p.hash&&S&&!p.hash.equals(S.hash))throw new TypeError("Hash mismatch");if(p.redeem&&p.redeem.output&&S){const F=(0,s.tapleafHash)({output:p.redeem.output,version:x.redeemVersion});if(!(0,s.findScriptPath)(S,F))throw new TypeError("Redeem script not in tree")}const E=B();if(p.redeem&&x.redeem){if(p.redeem.redeemVersion&&p.redeem.redeemVersion!==x.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(p.redeem.output){if(r.decompile(p.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(x.redeem.output&&!p.redeem.output.equals(x.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(p.redeem.witness&&x.redeem.witness&&!(0,n.stacksEqual)(p.redeem.witness,x.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(E&&E.length)if(E.length===1){if(p.signature&&!p.signature.equals(E[0]))throw new TypeError("Signature mismatch")}else{const F=E[E.length-1];if(F.length<33)throw new TypeError(`The control-block length is too small. Got ${F.length}, expected min 33.`);if((F.length-33)%32!==0)throw new TypeError(`The control-block length of ${F.length} is incorrect!`);const D=(F.length-33)/32;if(D>128)throw new TypeError(`The script path is too long. Got ${D}, expected max 128.`);const O=F.slice(1,33);if(p.internalPubkey&&!p.internalPubkey.equals(O))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(O))throw new TypeError("Invalid internalPubkey for p2tr witness");const K=F[0]&n.TAPLEAF_VERSION_MASK,C=E[E.length-2],G=(0,s.tapleafHash)({output:C,version:K}),V=(0,s.rootHashFromPath)(F,G),z=(0,s.tweakKey)(O,V);if(!z)throw new TypeError("Invalid outputKey for p2tr witness");if(g.length&&!g.equals(z.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(z.parity!==(F[0]&1))throw new Error("Incorrect parity")}}return Object.assign(x,p)}return Yr.p2tr=v,Yr}var Ao;function $s(){return Ao||(Ao=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.p2tr=e.p2wsh=e.p2wpkh=e.p2sh=e.p2pkh=e.p2pk=e.p2ms=e.embed=void 0;const t=ui;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=li;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=di;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const i=hi;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const s=pi;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return s.p2sh}});const o=yi;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=mi;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const u=ol();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return u.p2tr}})}(Gi)),Gi}Object.defineProperty(ae,"__esModule",{value:!0});ae.signatureBlocksAction=ae.checkInputForSig=ae.pubkeyInScript=ae.pubkeyPositionInScript=ae.witnessStackToScriptWitness=ae.isP2TR=ae.isP2SHScript=ae.isP2WSHScript=ae.isP2WPKH=ae.isP2PKH=ae.isP2PK=ae.isP2MS=void 0;const ko=En,dn=Xe(),Hn=_n,al=Wt,hr=$s();function pr(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}ae.isP2MS=pr(hr.p2ms);ae.isP2PK=pr(hr.p2pk);ae.isP2PKH=pr(hr.p2pkh);ae.isP2WPKH=pr(hr.p2wpkh);ae.isP2WSHScript=pr(hr.p2wsh);ae.isP2SHScript=pr(hr.p2sh);ae.isP2TR=pr(hr.p2tr);function cl(e){let t=Buffer.allocUnsafe(0);function r(o){t=Buffer.concat([t,Buffer.from(o)])}function n(o){const a=t.length,u=ko.encodingLength(o);t=Buffer.concat([t,Buffer.allocUnsafe(u)]),ko.encode(o,t,a)}function i(o){n(o.length),r(o)}function s(o){n(o.length),o.forEach(i)}return s(e),t}ae.witnessStackToScriptWitness=cl;function ja(e,t){const r=(0,al.hash160)(e),n=e.slice(1,33),i=dn.decompile(t);if(i===null)throw new Error("Unknown script error");return i.findIndex(s=>typeof s=="number"?!1:s.equals(e)||s.equals(r)||s.equals(n))}ae.pubkeyPositionInScript=ja;function fl(e,t){return ja(e,t)!==-1}ae.pubkeyInScript=fl;function ul(e,t){return ll(e).some(n=>Ga(n,dn.signature.decode,t))}ae.checkInputForSig=ul;function Ga(e,t,r){const{hashType:n}=t(e),i=[];switch(n&Hn.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput"),n&31){case Hn.Transaction.SIGHASH_ALL:break;case Hn.Transaction.SIGHASH_SINGLE:case Hn.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence");break}return i.indexOf(r)===-1}ae.signatureBlocksAction=Ga;function ll(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=dl(e)}else t=e.partialSig;return t.map(r=>r.signature)}function dl(e){const t=e.finalScriptSig?dn.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?dn.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>Buffer.isBuffer(n)&&dn.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(we,"__esModule",{value:!0});we.checkTaprootInputForSigs=we.tapTreeFromList=we.tapTreeToList=we.tweakInternalPubKey=we.checkTaprootOutputFields=we.checkTaprootInputFields=we.isTaprootOutput=we.isTaprootInput=Kn=we.serializeTaprootSignature=we.tapScriptFinalizer=we.toXOnly=void 0;const js=Fe,hl=_n,bi=ae,qt=Ds,pl=$s(),yl=ae,ml=e=>e.length===32?e:e.slice(1,33);we.toXOnly=ml;function bl(e,t,r){const n=Ll(t,e,r);try{const s=Cl(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,bi.witnessStackToScriptWitness)(s)}}catch(i){throw new Error(`Can not finalize taproot input #${e}: ${i}`)}}we.tapScriptFinalizer=bl;function wl(e,t){const r=t?Buffer.from([t]):Buffer.from([]);return Buffer.concat([e,r])}var Kn=we.serializeTaprootSignature=wl;function Yn(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,bi.isP2TR)(e.witnessUtxo.script))}we.isTaprootInput=Yn;function Xn(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,bi.isP2TR)(t))}we.isTaprootOutput=Xn;function gl(e,t,r){Pl(e,t,r),Rl(e,t,r)}we.checkTaprootInputFields=gl;function _l(e,t,r){Ol(e,t,r),vl(e,t)}we.checkTaprootOutputFields=_l;function vl(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const r=t.tapInternalKey||e.tapInternalKey,n=t.tapTree||e.tapTree;if(r){const{script:i}=e,s=El(r,n);if(i&&!i.equals(s))throw new Error("Error adding output. Script or address missmatch.")}}function El(e,t){const r=t&&Va(t.leaves),{output:n}=(0,pl.p2tr)({internalPubkey:e,scriptTree:r});return n}function xl(e,t){const r=t.tapInternalKey,n=r&&(0,qt.tweakKey)(r,t.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${e}. Public key: ${r&&r.toString("hex")}`);return n.x}we.tweakInternalPubKey=xl;function Sl(e){if(!(0,js.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return ys(e)}we.tapTreeToList=Sl;function Va(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:Il(e)}we.tapTreeFromList=Va;function Tl(e,t){return kl(e).some(n=>(0,yl.signatureBlocksAction)(n,Al,t))}we.checkTaprootInputForSigs=Tl;function Al(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||hl.Transaction.SIGHASH_DEFAULT}}function kl(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=Bl(e.finalScriptWitness);r&&t.push(r)}return t}function Bl(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function ys(e,t=[],r=0){if(r>qt.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,js.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||qt.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&ys(e[0],t,r+1),e[1]&&ys(e[1],t,r+1),t):[]}function Il(e){let t;for(const r of e)if(t=ms(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function ms(e,t,r=0){if(r>qt.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(e.depth===r)return t?void 0:{output:e.script,version:e.leafVersion};if((0,js.isTapleaf)(t))return;const n=ms(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const i=ms(e,t&&t[1],r+1);if(i)return[t&&t[0],i]}function Pl(e,t,r){const n=Yn(e)&&Pr(t),i=Pr(e)&&Yn(t),s=e===t&&Yn(t)&&Pr(t);if(n||i||s)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function Ol(e,t,r){const n=Xn(e)&&Pr(t),i=Pr(e)&&Xn(t),s=e===t&&Xn(t)&&Pr(t);if(n||i||s)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function Rl(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(s=>Ki(s,t.tapMerkleRoot)),i=(e.tapLeafScript||[]).every(s=>Ki(s,t.tapMerkleRoot));if(!n||!i)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(i=>Ki(i,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function Ki(e,t){if(!t)return!0;const r=(0,qt.tapleafHash)({output:e.script,version:e.leafVersion});return(0,qt.rootHashFromPath)(e.controlBlock,r).equals(t)}function Cl(e,t){const r=(0,qt.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>Ul(t.script,n)).sort((n,i)=>i.positionInScript-n.positionInScript).map(n=>n.signature)}function Ul(e,t){return Object.assign({positionInScript:(0,bi.pubkeyPositionInScript)(t.pubkey,e)},t)}function Ll(e,t,r){if(!e.tapScriptSig||!e.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${t}. No tapleaf script signature provided.`);const n=(e.tapLeafScript||[]).sort((i,s)=>i.controlBlock.length-s.controlBlock.length).find(i=>Nl(i,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function Nl(e,t,r){const n=(0,qt.tapleafHash)({output:e.script,version:e.leafVersion});return(!r||r.equals(n))&&t.find(s=>s.leafHash.equals(n))!==void 0}function Pr(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const Be={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:e=>"counterparty signature not found for utxo "+e,invalidCounterpartySigForUTXO:e=>"invalid counterparty signature for utxo "+e,htlcNotExpired:e=>`HTLC not expired, need more ${e} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},Fn=192;ie.initEccLib(sr);class hn{constructor(t,r,n,i,s,o,a,u){this.secretHash=n,this.redeemerPubkey=i,this.initiatorPubkey=s,this.expiry=o,this.signer=t,this.network=a,this.internalPubkey=Pf(),this.initiateAmount=r,this.utxoHashes=u}static async from(t,r,n,i,s,o,a){n=n.startsWith("0x")?n.slice(2):n,er(n.length===64,Be.secretHashLenMismatch),er(i.length===64||i.length===66,`initiator ${Be.pubkeyLenMismatch}`),er(s.length===64||s.length===66,`redeemer ${Be.pubkeyLenMismatch}`),er(o>0,Be.zeroOrNegativeExpiry);const u=await t.getNetwork();return new hn(t,r,n,ls(s).toString("hex"),ls(i).toString("hex"),o,u,a)}address(){const{address:t}=ie.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(Be.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const n=new ie.Transaction;n.version=2;const i=this.address(),s=await this.signer.getProvider();let o=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const u of this.utxoHashes){const d=await s.getTransaction(u);for(let h=0;h<d.vout.length;h++){const y=d.vout[h];y.scriptpubkey_address===i&&o.push({txid:d.txid,vout:h,value:y.value,status:{confirmed:!1}})}}else o=await s.getUTXOs(i);const a=o.reduce((u,d)=>u+d.value,0);if(a===0)throw new Error(`${i} ${Be.notFunded}`);for(let u=0;u<o.length;u++)n.addInput(Buffer.from(o[u].txid,"hex").reverse(),o[u].vout);return r??(r=await s.suggestFee(i,a,Rr.Urgency.MEDIUM)),n.addOutput(ie.address.toOutputScript(t,this.network),a-r),{tx:n,usedUtxos:o}}async _tempBuildRawTx(t,r){const n=new ie.Transaction;n.version=2;const i=this.address(),s=await this.signer.getProvider();let o=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const u of this.utxoHashes){const d=await s.getTransaction(u);for(let h=0;h<d.vout.length;h++){const y=d.vout[h];y.scriptpubkey_address===i&&o.push({txid:d.txid,vout:h,value:y.value,status:{confirmed:!1}})}}else o=await s.getUTXOs(i);const a=o.reduce((u,d)=>u+d.value,0);if(a===0)throw new Error(`${i} ${Be.notFunded}`);for(let u=0;u<o.length;u++)n.addInput(Buffer.from(o[u].txid,"hex").reverse(),o[u].vout);if(n.addOutput(ie.address.toOutputScript(t,this.network),a),r){const u=await s.getFeeRates(),d=Math.ceil(u.hourFee*r),h=a-d;n.outs[0].value=h}return{tx:n,usedUtxos:o}}async buildRawTx(t){return await this._buildRawTx(await this.signer.getAddress(),t)}getOutputScript(){return ie.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,Rr.Urgency.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async generateRedeemSACP(t,r,n){const{tx:i,usedUtxos:s}=await this._buildRawTx(r,n),o=this.getOutputScript(),a=ie.Transaction.SIGHASH_SINGLE|ie.Transaction.SIGHASH_ANYONECANPAY,u=this.leafHash(1),d=s.map(y=>y.value),h=Er(o,s.length);for(let y=0;y<i.ins.length;y++){const v=i.hashForWitnessV1(y,h,d,a,u),p=await this.signer.signSchnorr(v);i.setWitness(y,[Kn(p,a),Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return i.toHex()}async generateInstantRefundSACP(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t,r),s=this.getOutputScript(),o=ie.Transaction.SIGHASH_SINGLE|ie.Transaction.SIGHASH_ANYONECANPAY,a=this.leafHash(2),u=i.map(h=>h.value),d=Er(s,i.length);for(let h=0;h<n.ins.length;h++){const y=n.hashForWitnessV1(h,d,u,o,a),v=await this.signer.signSchnorr(y);n.setWitness(h,[Kn(v,o),Kn(v,o),this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return n.toHex()}async instantRefund(t,r){er(t.length>0,Be.noCounterpartySigs);const{tx:n,usedUtxos:i}=await this.buildRawTx(r);for(const y of i)if(!t.find(v=>v.utxo===y.txid))throw new Error(Be.counterPartySigNotFound(y.txid));const s=this.getOutputScript(),o=ie.Transaction.SIGHASH_DEFAULT,a=this.leafHash(2),u=i.map(y=>y.value),d=Er(s,i.length);for(let y=0;y<n.ins.length;y++){const v=n.hashForWitnessV1(y,d,u,o,a);if(!sr.verifySchnorr(v,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[y].sig,"hex")))throw new Error(Be.invalidCounterpartySigForUTXO(t[y].utxo));const p=await this.signer.signSchnorr(v),I=Buffer.from(n.ins[y].hash).reverse().toString("hex"),k=t.find(B=>B.utxo===I);if(!k)throw new Error(Be.counterPartySigNotFound(I));n.setWitness(y,[Buffer.from(k.sig,"hex"),p,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async redeem(t,r){er(ie.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,Be.secretMismatch);const n=r??await this.signer.getAddress(),{tx:i,usedUtxos:s}=await this._tempBuildRawTx(n),o=this.leafHash(1),a=s.map(v=>v.value),u=Er(this.getOutputScript(),s.length),d=ie.Transaction.SIGHASH_DEFAULT;for(let v=0;v<i.ins.length;v++){const p=i.hashForWitnessV1(v,u,a,d,o),I=await this.signer.signSchnorr(p);i.setWitness(v,[I,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:h}=await this._tempBuildRawTx(n,i.virtualSize());for(let v=0;v<h.ins.length;v++){const p=h.hashForWitnessV1(v,u,a,d,o),I=await this.signer.signSchnorr(p);h.setWitness(v,[I,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return await(await this.signer.getProvider()).broadcast(h.toHex())}async getRedeemHex(t,r){er(ie.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,Be.secretMismatch);const n=r??await this.signer.getAddress(),{tx:i,usedUtxos:s}=await this._tempBuildRawTx(n),o=this.leafHash(1),a=s.map(y=>y.value),u=Er(this.getOutputScript(),s.length),d=ie.Transaction.SIGHASH_DEFAULT;for(let y=0;y<i.ins.length;y++){const v=i.hashForWitnessV1(y,u,a,d,o),p=await this.signer.signSchnorr(v);i.setWitness(y,[p,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:h}=await this._tempBuildRawTx(n,i.virtualSize());for(let y=0;y<h.ins.length;y++){const v=h.hashForWitnessV1(y,u,a,d,o),p=await this.signer.signSchnorr(v);h.setWitness(y,[p,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return h.toHex()}async refund(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t??await this.signer.getAddress(),r),[s,o]=await this.canRefund(i);if(!s)throw new Error(Be.htlcNotExpired(o));const a=this.leafHash(0),u=i.map(v=>v.value),d=Er(this.getOutputScript(),i.length),h=ie.Transaction.SIGHASH_DEFAULT;for(let v=0;v<n.ins.length;v++){n.ins[v].sequence=this.expiry;const p=n.hashForWitnessV1(v,d,u,h,a),I=await this.signer.signSchnorr(p);n.setWitness(v,[I,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async canRefund(t){const n=await(await this.signer.getProvider()).getLatestTip();for(const i of t){let s=0;if(i.status.confirmed&&i.status.block_height+this.expiry>n?s=i.status.block_height+this.expiry-n+1:i.status.confirmed||(s=this.expiry+1),s>0)return[!1,s]}return[!0,0]}generateControlBlockFor(t){let r;switch(t){case 1:r=this.redeemLeaf();break;case 0:r=this.refundLeaf();break;case 2:r=this.instantRefundLeaf();break;default:throw new Error(Be.invalidLeaf)}const n=ie.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:Fn}});if(!n.witness)throw new Error(Be.controlBlockGenerationFailed);return n.witness[n.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),ie.crypto.taggedHash("TapLeaf",mf(r))}refundLeaf(){return ie.script.fromASM(`
|
|
9
|
+
`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Ye={};Object.defineProperty(Ye,"__esModule",{value:!0});Ye.value=Ye.prop=void 0;function Du(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const n=r.call(this);return this[t]=n,n},set(n){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:n,writable:!0})}})}Ye.prop=Du;function $u(e){let t;return()=>(t!==void 0||(t=e()),t)}Ye.value=$u;Object.defineProperty(ui,"__esModule",{value:!0});ui.p2data=void 0;const ju=He,Vn=Xe(),at=Fe,wo=Ye,go=Vn.OPS;function Gu(e,t){if(!e.data&&!e.output)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,at.typeforce)({network:at.typeforce.maybe(at.typeforce.Object),output:at.typeforce.maybe(at.typeforce.Buffer),data:at.typeforce.maybe(at.typeforce.arrayOf(at.typeforce.Buffer))},e);const n={name:"embed",network:e.network||ju.bitcoin};if(wo.prop(n,"output",()=>{if(e.data)return Vn.compile([go.OP_RETURN].concat(e.data))}),wo.prop(n,"data",()=>{if(e.output)return Vn.decompile(e.output).slice(1)}),t.validate&&e.output){const i=Vn.decompile(e.output);if(i[0]!==go.OP_RETURN)throw new TypeError("Output is invalid");if(!i.slice(1).every(at.typeforce.Buffer))throw new TypeError("Output is invalid");if(e.data&&!(0,at.stacksEqual)(e.data,n.data))throw new TypeError("Data mismatch")}return Object.assign(n,e)}ui.p2data=Gu;var li={};Object.defineProperty(li,"__esModule",{value:!0});li.p2ms=void 0;const Vu=He,Er=Xe(),xe=Fe,Lt=Ye,xr=Er.OPS,On=xr.OP_RESERVED;function zu(e,t){if(!e.input&&!e.output&&!(e.pubkeys&&e.m!==void 0)&&!e.signatures)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{});function r(u){return Er.isCanonicalScriptSignature(u)||(t.allowIncomplete&&u===xr.OP_0)!==void 0}(0,xe.typeforce)({network:xe.typeforce.maybe(xe.typeforce.Object),m:xe.typeforce.maybe(xe.typeforce.Number),n:xe.typeforce.maybe(xe.typeforce.Number),output:xe.typeforce.maybe(xe.typeforce.Buffer),pubkeys:xe.typeforce.maybe(xe.typeforce.arrayOf(xe.isPoint)),signatures:xe.typeforce.maybe(xe.typeforce.arrayOf(r)),input:xe.typeforce.maybe(xe.typeforce.Buffer)},e);const i={network:e.network||Vu.bitcoin};let s=[],o=!1;function a(u){o||(o=!0,s=Er.decompile(u),i.m=s[0]-On,i.n=s[s.length-2]-On,i.pubkeys=s.slice(1,-2))}if(Lt.prop(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return Er.compile([].concat(On+e.m,e.pubkeys,On+i.n,xr.OP_CHECKMULTISIG))}),Lt.prop(i,"m",()=>{if(i.output)return a(i.output),i.m}),Lt.prop(i,"n",()=>{if(i.pubkeys)return i.pubkeys.length}),Lt.prop(i,"pubkeys",()=>{if(e.output)return a(e.output),i.pubkeys}),Lt.prop(i,"signatures",()=>{if(e.input)return Er.decompile(e.input).slice(1)}),Lt.prop(i,"input",()=>{if(e.signatures)return Er.compile([xr.OP_0].concat(e.signatures))}),Lt.prop(i,"witness",()=>{if(i.input)return[]}),Lt.prop(i,"name",()=>{if(!(!i.m||!i.n))return`p2ms(${i.m} of ${i.n})`}),t.validate){if(e.output){if(a(e.output),!xe.typeforce.Number(s[0]))throw new TypeError("Output is invalid");if(!xe.typeforce.Number(s[s.length-2]))throw new TypeError("Output is invalid");if(s[s.length-1]!==xr.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(i.m<=0||i.n>16||i.m>i.n||i.n!==s.length-3)throw new TypeError("Output is invalid");if(!i.pubkeys.every(u=>(0,xe.isPoint)(u)))throw new TypeError("Output is invalid");if(e.m!==void 0&&e.m!==i.m)throw new TypeError("m mismatch");if(e.n!==void 0&&e.n!==i.n)throw new TypeError("n mismatch");if(e.pubkeys&&!(0,xe.stacksEqual)(e.pubkeys,i.pubkeys))throw new TypeError("Pubkeys mismatch")}if(e.pubkeys){if(e.n!==void 0&&e.n!==e.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(i.n=e.pubkeys.length,i.n<i.m)throw new TypeError("Pubkey count cannot be less than m")}if(e.signatures){if(e.signatures.length<i.m)throw new TypeError("Not enough signatures provided");if(e.signatures.length>i.m)throw new TypeError("Too many signatures provided")}if(e.input){if(e.input[0]!==xr.OP_0)throw new TypeError("Input is invalid");if(i.signatures.length===0||!i.signatures.every(r))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!(0,xe.stacksEqual)(e.signatures,i.signatures))throw new TypeError("Signature mismatch");if(e.m!==void 0&&e.m!==e.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(i,e)}li.p2ms=zu;var hi={};Object.defineProperty(hi,"__esModule",{value:!0});hi.p2pk=void 0;const qu=He,Sr=Xe(),rt=Fe,_r=Ye,_o=Sr.OPS;function Wu(e,t){if(!e.input&&!e.output&&!e.pubkey&&!e.input&&!e.signature)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,rt.typeforce)({network:rt.typeforce.maybe(rt.typeforce.Object),output:rt.typeforce.maybe(rt.typeforce.Buffer),pubkey:rt.typeforce.maybe(rt.isPoint),signature:rt.typeforce.maybe(Sr.isCanonicalScriptSignature),input:rt.typeforce.maybe(rt.typeforce.Buffer)},e);const r=_r.value(()=>Sr.decompile(e.input)),i={name:"p2pk",network:e.network||qu.bitcoin};if(_r.prop(i,"output",()=>{if(e.pubkey)return Sr.compile([e.pubkey,_o.OP_CHECKSIG])}),_r.prop(i,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),_r.prop(i,"signature",()=>{if(e.input)return r()[0]}),_r.prop(i,"input",()=>{if(e.signature)return Sr.compile([e.signature])}),_r.prop(i,"witness",()=>{if(i.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==_o.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,rt.isPoint)(i.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&!e.pubkey.equals(i.pubkey))throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&!e.input.equals(i.input))throw new TypeError("Signature mismatch");if(e.input){if(r().length!==1)throw new TypeError("Input is invalid");if(!Sr.isCanonicalScriptSignature(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}hi.p2pk=Wu;var di={};function Ku(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var o=e.length,a=e.charAt(0),u=Math.log(o)/Math.log(256),h=Math.log(256)/Math.log(o);function d(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var I=0,k=0,B=0,R=y.length;B!==R&&y[B]===0;)B++,I++;for(var U=(R-B)*h+1>>>0,x=new Uint8Array(U);B!==R;){for(var g=y[B],S=0,E=U-1;(g!==0||S<k)&&E!==-1;E--,S++)g+=256*x[E]>>>0,x[E]=g%o>>>0,g=g/o>>>0;if(g!==0)throw new Error("Non-zero carry");k=S,B++}for(var F=U-k;F!==U&&x[F]===0;)F++;for(var D=a.repeat(I);F<U;++F)D+=e.charAt(x[F]);return D}function p(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;for(var I=0,k=0,B=0;y[I]===a;)k++,I++;for(var R=(y.length-I)*u+1>>>0,U=new Uint8Array(R);y[I];){var x=y.charCodeAt(I);if(x>255)return;var g=t[x];if(g===255)return;for(var S=0,E=R-1;(g!==0||S<B)&&E!==-1;E--,S++)g+=o*U[E]>>>0,U[E]=g%256>>>0,g=g/256>>>0;if(g!==0)throw new Error("Non-zero carry");B=S,I++}for(var F=R-B;F!==R&&U[F]===0;)F++;for(var D=new Uint8Array(k+(R-F)),O=k;F!==R;)D[O++]=U[F++];return D}function v(y){var I=p(y);if(I)return I;throw new Error("Non-base"+o+" character")}return{encode:d,decodeUnsafe:p,decode:v}}var Yu=Ku;const Xu=Yu,Ju="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";var Qu=Xu(Ju),Vi=Qu,Zu=function(e){function t(s){var o=Uint8Array.from(s),a=e(o),u=o.length+4,h=new Uint8Array(u);return h.set(o,0),h.set(a.subarray(0,4),o.length),Vi.encode(h,u)}function r(s){var o=s.slice(0,-4),a=s.slice(-4),u=e(o);if(!(a[0]^u[0]|a[1]^u[1]|a[2]^u[2]|a[3]^u[3]))return o}function n(s){var o=Vi.decodeUnsafe(s);if(o)return r(o)}function i(s){var o=Vi.decode(s),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:i,decodeUnsafe:n}},{sha256:vo}=$a,el=Zu;function tl(e){return vo(vo(e))}var $s=el(tl);Object.defineProperty(di,"__esModule",{value:!0});di.p2pkh=void 0;const zi=zt,rl=He,Tr=Xe(),De=Fe,bt=Ye,Eo=$s,Nt=Tr.OPS;function nl(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,De.typeforce)({network:De.typeforce.maybe(De.typeforce.Object),address:De.typeforce.maybe(De.typeforce.String),hash:De.typeforce.maybe(De.typeforce.BufferN(20)),output:De.typeforce.maybe(De.typeforce.BufferN(25)),pubkey:De.typeforce.maybe(De.isPoint),signature:De.typeforce.maybe(Tr.isCanonicalScriptSignature),input:De.typeforce.maybe(De.typeforce.Buffer)},e);const r=bt.value(()=>{const o=Buffer.from(Eo.decode(e.address)),a=o.readUInt8(0),u=o.slice(1);return{version:a,hash:u}}),n=bt.value(()=>Tr.decompile(e.input)),i=e.network||rl.bitcoin,s={name:"p2pkh",network:i};if(bt.prop(s,"address",()=>{if(!s.hash)return;const o=Buffer.allocUnsafe(21);return o.writeUInt8(i.pubKeyHash,0),s.hash.copy(o,1),Eo.encode(o)}),bt.prop(s,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return r().hash;if(e.pubkey||s.pubkey)return zi.hash160(e.pubkey||s.pubkey)}),bt.prop(s,"output",()=>{if(s.hash)return Tr.compile([Nt.OP_DUP,Nt.OP_HASH160,s.hash,Nt.OP_EQUALVERIFY,Nt.OP_CHECKSIG])}),bt.prop(s,"pubkey",()=>{if(e.input)return n()[1]}),bt.prop(s,"signature",()=>{if(e.input)return n()[0]}),bt.prop(s,"input",()=>{if(e.pubkey&&e.signature)return Tr.compile([e.signature,e.pubkey])}),bt.prop(s,"witness",()=>{if(s.input)return[]}),t.validate){let o=Buffer.from([]);if(e.address){if(r().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(r().hash.length!==20)throw new TypeError("Invalid address");o=r().hash}if(e.hash){if(o.length>0&&!o.equals(e.hash))throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==25||e.output[0]!==Nt.OP_DUP||e.output[1]!==Nt.OP_HASH160||e.output[2]!==20||e.output[23]!==Nt.OP_EQUALVERIFY||e.output[24]!==Nt.OP_CHECKSIG)throw new TypeError("Output is invalid");const a=e.output.slice(3,23);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.pubkey){const a=zi.hash160(e.pubkey);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.input){const a=n();if(a.length!==2)throw new TypeError("Input is invalid");if(!Tr.isCanonicalScriptSignature(a[0]))throw new TypeError("Input has invalid signature");if(!(0,De.isPoint)(a[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&!e.signature.equals(a[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(a[1]))throw new TypeError("Pubkey mismatch");const u=zi.hash160(a[1]);if(o.length>0&&!o.equals(u))throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}di.p2pkh=nl;var pi={};Object.defineProperty(pi,"__esModule",{value:!0});pi.p2sh=void 0;const xo=zt,il=He,ut=Xe(),fe=Fe,ct=Ye,So=$s,Wr=ut.OPS;function sl(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.input)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,fe.typeforce)({network:fe.typeforce.maybe(fe.typeforce.Object),address:fe.typeforce.maybe(fe.typeforce.String),hash:fe.typeforce.maybe(fe.typeforce.BufferN(20)),output:fe.typeforce.maybe(fe.typeforce.BufferN(23)),redeem:fe.typeforce.maybe({network:fe.typeforce.maybe(fe.typeforce.Object),output:fe.typeforce.maybe(fe.typeforce.Buffer),input:fe.typeforce.maybe(fe.typeforce.Buffer),witness:fe.typeforce.maybe(fe.typeforce.arrayOf(fe.typeforce.Buffer))}),input:fe.typeforce.maybe(fe.typeforce.Buffer),witness:fe.typeforce.maybe(fe.typeforce.arrayOf(fe.typeforce.Buffer))},e);let r=e.network;r||(r=e.redeem&&e.redeem.network||il.bitcoin);const n={network:r},i=ct.value(()=>{const a=Buffer.from(So.decode(e.address)),u=a.readUInt8(0),h=a.slice(1);return{version:u,hash:h}}),s=ct.value(()=>ut.decompile(e.input)),o=ct.value(()=>{const a=s(),u=a[a.length-1];return{network:r,output:u===Wr.OP_FALSE?Buffer.from([]):u,input:ut.compile(a.slice(0,-1)),witness:e.witness||[]}});if(ct.prop(n,"address",()=>{if(!n.hash)return;const a=Buffer.allocUnsafe(21);return a.writeUInt8(n.network.scriptHash,0),n.hash.copy(a,1),So.encode(a)}),ct.prop(n,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return i().hash;if(n.redeem&&n.redeem.output)return xo.hash160(n.redeem.output)}),ct.prop(n,"output",()=>{if(n.hash)return ut.compile([Wr.OP_HASH160,n.hash,Wr.OP_EQUAL])}),ct.prop(n,"redeem",()=>{if(e.input)return o()}),ct.prop(n,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return ut.compile([].concat(ut.decompile(e.redeem.input),e.redeem.output))}),ct.prop(n,"witness",()=>{if(n.redeem&&n.redeem.witness)return n.redeem.witness;if(n.input)return[]}),ct.prop(n,"name",()=>{const a=["p2sh"];return n.redeem!==void 0&&n.redeem.name!==void 0&&a.push(n.redeem.name),a.join("-")}),t.validate){let a=Buffer.from([]);if(e.address){if(i().version!==r.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(i().hash.length!==20)throw new TypeError("Invalid address");a=i().hash}if(e.hash){if(a.length>0&&!a.equals(e.hash))throw new TypeError("Hash mismatch");a=e.hash}if(e.output){if(e.output.length!==23||e.output[0]!==Wr.OP_HASH160||e.output[1]!==20||e.output[22]!==Wr.OP_EQUAL)throw new TypeError("Output is invalid");const h=e.output.slice(2,22);if(a.length>0&&!a.equals(h))throw new TypeError("Hash mismatch");a=h}const u=h=>{if(h.output){const d=ut.decompile(h.output);if(!d||d.length<1)throw new TypeError("Redeem.output too short");if(h.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(ut.countNonPushOnlyOPs(d)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const p=xo.hash160(h.output);if(a.length>0&&!a.equals(p))throw new TypeError("Hash mismatch");a=p}if(h.input){const d=h.input.length>0,p=h.witness&&h.witness.length>0;if(!d&&!p)throw new TypeError("Empty input");if(d&&p)throw new TypeError("Input and witness provided");if(d){const v=ut.decompile(h.input);if(!ut.isPushOnly(v))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const h=s();if(!h||h.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(o().output))throw new TypeError("Input is invalid");u(o())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==r)throw new TypeError("Network mismatch");if(e.input){const h=o();if(e.redeem.output&&!e.redeem.output.equals(h.output))throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&!e.redeem.input.equals(h.input))throw new TypeError("Redeem.input mismatch")}u(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!(0,fe.stacksEqual)(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(n,e)}pi.p2sh=sl;var yi={},At={};Object.defineProperty(At,"__esModule",{value:!0});At.bech32m=At.bech32=void 0;const Zn="qpzry9x8gf2tvdw0s3jn54khce6mua7l",za={};for(let e=0;e<Zn.length;e++){const t=Zn.charAt(e);za[t]=e}function Br(e){const t=e>>25;return(e&33554431)<<5^-(t>>0&1)&996825010^-(t>>1&1)&642813549^-(t>>2&1)&513874426^-(t>>3&1)&1027748829^-(t>>4&1)&705979059}function To(e){let t=1;for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);if(n<33||n>126)return"Invalid prefix ("+e+")";t=Br(t)^n>>5}t=Br(t);for(let r=0;r<e.length;++r){const n=e.charCodeAt(r);t=Br(t)^n&31}return t}function js(e,t,r,n){let i=0,s=0;const o=(1<<r)-1,a=[];for(let u=0;u<e.length;++u)for(i=i<<t|e[u],s+=t;s>=r;)s-=r,a.push(i>>s&o);if(n)s>0&&a.push(i<<r-s&o);else{if(s>=t)return"Excess padding";if(i<<r-s&o)return"Non-zero padding"}return a}function ol(e){return js(e,8,5,!0)}function al(e){const t=js(e,5,8,!1);if(Array.isArray(t))return t}function cl(e){const t=js(e,5,8,!1);if(Array.isArray(t))return t;throw new Error(t)}function qa(e){let t;e==="bech32"?t=1:t=734539939;function r(o,a,u){if(u=u||90,o.length+7+a.length>u)throw new TypeError("Exceeds length limit");o=o.toLowerCase();let h=To(o);if(typeof h=="string")throw new Error(h);let d=o+"1";for(let p=0;p<a.length;++p){const v=a[p];if(v>>5)throw new Error("Non 5-bit word");h=Br(h)^v,d+=Zn.charAt(v)}for(let p=0;p<6;++p)h=Br(h);h^=t;for(let p=0;p<6;++p){const v=h>>(5-p)*5&31;d+=Zn.charAt(v)}return d}function n(o,a){if(a=a||90,o.length<8)return o+" too short";if(o.length>a)return"Exceeds length limit";const u=o.toLowerCase(),h=o.toUpperCase();if(o!==u&&o!==h)return"Mixed-case string "+o;o=u;const d=o.lastIndexOf("1");if(d===-1)return"No separator character for "+o;if(d===0)return"Missing prefix for "+o;const p=o.slice(0,d),v=o.slice(d+1);if(v.length<6)return"Data too short";let y=To(p);if(typeof y=="string")return y;const I=[];for(let k=0;k<v.length;++k){const B=v.charAt(k),R=za[B];if(R===void 0)return"Unknown character "+B;y=Br(y)^R,!(k+6>=v.length)&&I.push(R)}return y!==t?"Invalid checksum for "+o:{prefix:p,words:I}}function i(o,a){const u=n(o,a);if(typeof u=="object")return u}function s(o,a){const u=n(o,a);if(typeof u=="object")return u;throw new Error(u)}return{decodeUnsafe:i,decode:s,encode:r,toWords:ol,fromWordsUnsafe:al,fromWords:cl}}At.bech32=qa("bech32");At.bech32m=qa("bech32m");Object.defineProperty(yi,"__esModule",{value:!0});yi.p2wpkh=void 0;const qi=zt,fl=He,zn=Xe(),Ae=Fe,Ht=Ye,Rn=At,Ao=zn.OPS,ul=Buffer.alloc(0);function ll(e,t){if(!e.address&&!e.hash&&!e.output&&!e.pubkey&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,Ae.typeforce)({address:Ae.typeforce.maybe(Ae.typeforce.String),hash:Ae.typeforce.maybe(Ae.typeforce.BufferN(20)),input:Ae.typeforce.maybe(Ae.typeforce.BufferN(0)),network:Ae.typeforce.maybe(Ae.typeforce.Object),output:Ae.typeforce.maybe(Ae.typeforce.BufferN(22)),pubkey:Ae.typeforce.maybe(Ae.isPoint),signature:Ae.typeforce.maybe(zn.isCanonicalScriptSignature),witness:Ae.typeforce.maybe(Ae.typeforce.arrayOf(Ae.typeforce.Buffer))},e);const r=Ht.value(()=>{const s=Rn.bech32.decode(e.address),o=s.words.shift(),a=Rn.bech32.fromWords(s.words);return{version:o,prefix:s.prefix,data:Buffer.from(a)}}),n=e.network||fl.bitcoin,i={name:"p2wpkh",network:n};if(Ht.prop(i,"address",()=>{if(!i.hash)return;const s=Rn.bech32.toWords(i.hash);return s.unshift(0),Rn.bech32.encode(n.bech32,s)}),Ht.prop(i,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return r().data;if(e.pubkey||i.pubkey)return qi.hash160(e.pubkey||i.pubkey)}),Ht.prop(i,"output",()=>{if(i.hash)return zn.compile([Ao.OP_0,i.hash])}),Ht.prop(i,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),Ht.prop(i,"signature",()=>{if(e.witness)return e.witness[0]}),Ht.prop(i,"input",()=>{if(i.witness)return ul}),Ht.prop(i,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let s=Buffer.from([]);if(e.address){if(n&&n.bech32!==r().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==20)throw new TypeError("Invalid address data");s=r().data}if(e.hash){if(s.length>0&&!s.equals(e.hash))throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==Ao.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(s.length>0&&!s.equals(e.output.slice(2)))throw new TypeError("Hash mismatch");s=e.output.slice(2)}if(e.pubkey){const o=qi.hash160(e.pubkey);if(s.length>0&&!s.equals(o))throw new TypeError("Hash mismatch");if(s=o,!(0,Ae.isPoint)(e.pubkey)||e.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(e.witness){if(e.witness.length!==2)throw new TypeError("Witness is invalid");if(!zn.isCanonicalScriptSignature(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,Ae.isPoint)(e.witness[1])||e.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(e.signature&&!e.signature.equals(e.witness[0]))throw new TypeError("Signature mismatch");if(e.pubkey&&!e.pubkey.equals(e.witness[1]))throw new TypeError("Pubkey mismatch");const o=qi.hash160(e.witness[1]);if(s.length>0&&!s.equals(o))throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}yi.p2wpkh=ll;var mi={};Object.defineProperty(mi,"__esModule",{value:!0});mi.p2wsh=void 0;const ko=zt,hl=He,vt=Xe(),ce=Fe,wt=Ye,Cn=At,Bo=vt.OPS,Wi=Buffer.alloc(0);function Un(e){return!!(Buffer.isBuffer(e)&&e.length===65&&e[0]===4&&(0,ce.isPoint)(e))}function dl(e,t){if(!e.address&&!e.hash&&!e.output&&!e.redeem&&!e.witness)throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),(0,ce.typeforce)({network:ce.typeforce.maybe(ce.typeforce.Object),address:ce.typeforce.maybe(ce.typeforce.String),hash:ce.typeforce.maybe(ce.typeforce.BufferN(32)),output:ce.typeforce.maybe(ce.typeforce.BufferN(34)),redeem:ce.typeforce.maybe({input:ce.typeforce.maybe(ce.typeforce.Buffer),network:ce.typeforce.maybe(ce.typeforce.Object),output:ce.typeforce.maybe(ce.typeforce.Buffer),witness:ce.typeforce.maybe(ce.typeforce.arrayOf(ce.typeforce.Buffer))}),input:ce.typeforce.maybe(ce.typeforce.BufferN(0)),witness:ce.typeforce.maybe(ce.typeforce.arrayOf(ce.typeforce.Buffer))},e);const r=wt.value(()=>{const o=Cn.bech32.decode(e.address),a=o.words.shift(),u=Cn.bech32.fromWords(o.words);return{version:a,prefix:o.prefix,data:Buffer.from(u)}}),n=wt.value(()=>vt.decompile(e.redeem.input));let i=e.network;i||(i=e.redeem&&e.redeem.network||hl.bitcoin);const s={network:i};if(wt.prop(s,"address",()=>{if(!s.hash)return;const o=Cn.bech32.toWords(s.hash);return o.unshift(0),Cn.bech32.encode(i.bech32,o)}),wt.prop(s,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return r().data;if(s.redeem&&s.redeem.output)return ko.sha256(s.redeem.output)}),wt.prop(s,"output",()=>{if(s.hash)return vt.compile([Bo.OP_0,s.hash])}),wt.prop(s,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:Wi,witness:e.witness.slice(0,-1)}}),wt.prop(s,"input",()=>{if(s.witness)return Wi}),wt.prop(s,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const o=vt.toStack(n());return s.redeem=Object.assign({witness:o},e.redeem),s.redeem.input=Wi,[].concat(o,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),wt.prop(s,"name",()=>{const o=["p2wsh"];return s.redeem!==void 0&&s.redeem.name!==void 0&&o.push(s.redeem.name),o.join("-")}),t.validate){let o=Buffer.from([]);if(e.address){if(r().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(r().version!==0)throw new TypeError("Invalid address version");if(r().data.length!==32)throw new TypeError("Invalid address data");o=r().data}if(e.hash){if(o.length>0&&!o.equals(e.hash))throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==34||e.output[0]!==Bo.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const a=e.output.slice(2);if(o.length>0&&!o.equals(a))throw new TypeError("Hash mismatch");o=a}if(e.redeem){if(e.redeem.network&&e.redeem.network!==i)throw new TypeError("Network mismatch");if(e.redeem.input&&e.redeem.input.length>0&&e.redeem.witness&&e.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(e.redeem.output){const a=vt.decompile(e.redeem.output);if(!a||a.length<1)throw new TypeError("Redeem.output is invalid");if(e.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(vt.countNonPushOnlyOPs(a)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const u=ko.sha256(e.redeem.output);if(o.length>0&&!o.equals(u))throw new TypeError("Hash mismatch");o=u}if(e.redeem.input&&!vt.isPushOnly(n()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!(0,ce.stacksEqual)(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&n().some(Un)||e.redeem.output&&(vt.decompile(e.redeem.output)||[]).some(Un))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const a=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&!e.redeem.output.equals(a))throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(Un)||(vt.decompile(a)||[]).some(Un))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(s,e)}mi.p2wsh=dl;var Kr={},or={};Object.defineProperty(or,"__esModule",{value:!0});or.getEccLib=or.initEccLib=void 0;const un={};function pl(e,t){e?e!==un.eccLib&&(t!=null&&t.DANGER_DO_NOT_VERIFY_ECCLIB||ml(e),un.eccLib=e):un.eccLib=e}or.initEccLib=pl;function yl(){if(!un.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return un.eccLib}or.getEccLib=yl;const gt=e=>Buffer.from(e,"hex");function ml(e){Qe(typeof e.isXOnlyPoint=="function"),Qe(e.isXOnlyPoint(gt("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Qe(e.isXOnlyPoint(gt("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Qe(e.isXOnlyPoint(gt("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Qe(e.isXOnlyPoint(gt("0000000000000000000000000000000000000000000000000000000000000001"))),Qe(!e.isXOnlyPoint(gt("0000000000000000000000000000000000000000000000000000000000000000"))),Qe(!e.isXOnlyPoint(gt("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Qe(typeof e.xOnlyPointAddTweak=="function"),bl.forEach(t=>{const r=e.xOnlyPointAddTweak(gt(t.pubkey),gt(t.tweak));t.result===null?Qe(r===null):(Qe(r!==null),Qe(r.parity===t.parity),Qe(Buffer.from(r.xOnlyPubkey).equals(gt(t.result))))})}function Qe(e){if(!e)throw new Error("ecc library invalid")}const bl=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];var Gs={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.tweakKey=e.tapTweakHash=e.tapleafHash=e.findScriptPath=e.toHashTree=e.rootHashFromPath=e.MAX_TAPTREE_DEPTH=e.LEAF_VERSION_TAPSCRIPT=void 0;const t=Bt,r=or,n=zt,i=Pe,s=Fe;e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const o=k=>"left"in k&&"right"in k;function a(k,B){if(k.length<33)throw new TypeError(`The control-block length is too small. Got ${k.length}, expected min 33.`);const R=(k.length-33)/32;let U=B;for(let x=0;x<R;x++){const g=k.slice(33+32*x,65+32*x);U.compare(g)<0?U=y(U,g):U=y(g,U)}return U}e.rootHashFromPath=a;function u(k){if((0,s.isTapleaf)(k))return{hash:d(k)};const B=[u(k[0]),u(k[1])];B.sort((x,g)=>x.hash.compare(g.hash));const[R,U]=B;return{hash:y(R.hash,U.hash),left:R,right:U}}e.toHashTree=u;function h(k,B){if(o(k)){const R=h(k.left,B);if(R!==void 0)return[...R,k.right.hash];const U=h(k.right,B);if(U!==void 0)return[...U,k.left.hash]}else if(k.hash.equals(B))return[]}e.findScriptPath=h;function d(k){const B=k.version||e.LEAF_VERSION_TAPSCRIPT;return n.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([B]),I(k.output)]))}e.tapleafHash=d;function p(k,B){return n.taggedHash("TapTweak",t.Buffer.concat(B?[k,B]:[k]))}e.tapTweakHash=p;function v(k,B){if(!t.Buffer.isBuffer(k)||k.length!==32||B&&B.length!==32)return null;const R=p(k,B),U=(0,r.getEccLib)().xOnlyPointAddTweak(k,R);return!U||U.xOnlyPubkey===null?null:{parity:U.parity,x:t.Buffer.from(U.xOnlyPubkey)}}e.tweakKey=v;function y(k,B){return n.taggedHash("TapBranch",t.Buffer.concat([k,B]))}function I(k){const B=i.varuint.encodingLength(k.length),R=t.Buffer.allocUnsafe(B);return i.varuint.encode(k.length,R),t.Buffer.concat([R,k])}})(Gs);var $e={},Io;function wl(){if(Io)return $e;Io=1,Object.defineProperty($e,"__esModule",{value:!0}),$e.toOutputScript=$e.fromOutputScript=$e.toBech32=$e.toBase58Check=$e.fromBech32=$e.fromBase58Check=void 0;const e=He,t=Vs(),r=Xe(),n=Fe,i=At,s=$s,o=40,a=2,u=16,h=2,d=80,p="WARNING: Sending to a future segwit version address can lead to loss of funds. End users MUST be warned carefully in the GUI and asked if they wish to proceed with caution. Wallets should verify the segwit version from the output of fromBech32, then decide when it is safe to use which version of segwit.";function v(x,g){const S=x.slice(2);if(S.length<a||S.length>o)throw new TypeError("Invalid program length for segwit address");const E=x[0]-d;if(E<h||E>u)throw new TypeError("Invalid version for segwit address");if(x[1]!==S.length)throw new TypeError("Invalid script for segwit address");return console.warn(p),B(S,E,g.bech32)}function y(x){const g=Buffer.from(s.decode(x));if(g.length<21)throw new TypeError(x+" is too short");if(g.length>21)throw new TypeError(x+" is too long");const S=g.readUInt8(0),E=g.slice(1);return{version:S,hash:E}}$e.fromBase58Check=y;function I(x){let g,S;try{g=i.bech32.decode(x)}catch{}if(g){if(S=g.words[0],S!==0)throw new TypeError(x+" uses wrong encoding")}else if(g=i.bech32m.decode(x),S=g.words[0],S===0)throw new TypeError(x+" uses wrong encoding");const E=i.bech32.fromWords(g.words.slice(1));return{version:S,prefix:g.prefix,data:Buffer.from(E)}}$e.fromBech32=I;function k(x,g){(0,n.typeforce)((0,n.tuple)(n.Hash160bit,n.UInt8),arguments);const S=Buffer.allocUnsafe(21);return S.writeUInt8(g,0),x.copy(S,1),s.encode(S)}$e.toBase58Check=k;function B(x,g,S){const E=i.bech32.toWords(x);return E.unshift(g),g===0?i.bech32.encode(S,E):i.bech32m.encode(S,E)}$e.toBech32=B;function R(x,g){g=g||e.bitcoin;try{return t.p2pkh({output:x,network:g}).address}catch{}try{return t.p2sh({output:x,network:g}).address}catch{}try{return t.p2wpkh({output:x,network:g}).address}catch{}try{return t.p2wsh({output:x,network:g}).address}catch{}try{return t.p2tr({output:x,network:g}).address}catch{}try{return v(x,g)}catch{}throw new Error(r.toASM(x)+" has no matching Address")}$e.fromOutputScript=R;function U(x,g){g=g||e.bitcoin;let S,E;try{S=y(x)}catch{}if(S){if(S.version===g.pubKeyHash)return t.p2pkh({hash:S.hash}).output;if(S.version===g.scriptHash)return t.p2sh({hash:S.hash}).output}else{try{E=I(x)}catch{}if(E){if(E.prefix!==g.bech32)throw new Error(x+" has an invalid prefix");if(E.version===0){if(E.data.length===20)return t.p2wpkh({hash:E.data}).output;if(E.data.length===32)return t.p2wsh({hash:E.data}).output}else if(E.version===1){if(E.data.length===32)return t.p2tr({pubkey:E.data}).output}else if(E.version>=h&&E.version<=u&&E.data.length>=a&&E.data.length<=o)return console.warn(p),r.compile([E.version+d,E.data])}}throw new Error(x+" has no matching Script")}return $e.toOutputScript=U,$e}var Po;function gl(){if(Po)return Kr;Po=1,Object.defineProperty(Kr,"__esModule",{value:!0}),Kr.p2tr=void 0;const e=Bt,t=He,r=Xe(),n=Fe,i=or,s=Gs,o=Ye,a=At,u=wl(),h=r.OPS,d=1,p=80;function v(y,I){if(!y.address&&!y.output&&!y.pubkey&&!y.internalPubkey&&!(y.witness&&y.witness.length>1))throw new TypeError("Not enough data");I=Object.assign({validate:!0},I||{}),(0,n.typeforce)({address:n.typeforce.maybe(n.typeforce.String),input:n.typeforce.maybe(n.typeforce.BufferN(0)),network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.BufferN(34)),internalPubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),hash:n.typeforce.maybe(n.typeforce.BufferN(32)),pubkey:n.typeforce.maybe(n.typeforce.BufferN(32)),signature:n.typeforce.maybe(n.typeforce.anyOf(n.typeforce.BufferN(64),n.typeforce.BufferN(65))),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer)),scriptTree:n.typeforce.maybe(n.isTaptree),redeem:n.typeforce.maybe({output:n.typeforce.maybe(n.typeforce.Buffer),redeemVersion:n.typeforce.maybe(n.typeforce.Number),witness:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))}),redeemVersion:n.typeforce.maybe(n.typeforce.Number)},y);const k=o.value(()=>(0,u.fromBech32)(y.address)),B=o.value(()=>{if(!(!y.witness||!y.witness.length))return y.witness.length>=2&&y.witness[y.witness.length-1][0]===p?y.witness.slice(0,-1):y.witness.slice()}),R=o.value(()=>{if(y.scriptTree)return(0,s.toHashTree)(y.scriptTree);if(y.hash)return{hash:y.hash}}),U=y.network||t.bitcoin,x={name:"p2tr",network:U};if(o.prop(x,"address",()=>{if(!x.pubkey)return;const g=a.bech32m.toWords(x.pubkey);return g.unshift(d),a.bech32m.encode(U.bech32,g)}),o.prop(x,"hash",()=>{const g=R();if(g)return g.hash;const S=B();if(S&&S.length>1){const E=S[S.length-1],F=E[0]&n.TAPLEAF_VERSION_MASK,D=S[S.length-2],O=(0,s.tapleafHash)({output:D,version:F});return(0,s.rootHashFromPath)(E,O)}return null}),o.prop(x,"output",()=>{if(x.pubkey)return r.compile([h.OP_1,x.pubkey])}),o.prop(x,"redeemVersion",()=>y.redeemVersion?y.redeemVersion:y.redeem&&y.redeem.redeemVersion!==void 0&&y.redeem.redeemVersion!==null?y.redeem.redeemVersion:s.LEAF_VERSION_TAPSCRIPT),o.prop(x,"redeem",()=>{const g=B();if(!(!g||g.length<2))return{output:g[g.length-2],witness:g.slice(0,-2),redeemVersion:g[g.length-1][0]&n.TAPLEAF_VERSION_MASK}}),o.prop(x,"pubkey",()=>{if(y.pubkey)return y.pubkey;if(y.output)return y.output.slice(2);if(y.address)return k().data;if(x.internalPubkey){const g=(0,s.tweakKey)(x.internalPubkey,x.hash);if(g)return g.x}}),o.prop(x,"internalPubkey",()=>{if(y.internalPubkey)return y.internalPubkey;const g=B();if(g&&g.length>1)return g[g.length-1].slice(1,33)}),o.prop(x,"signature",()=>{if(y.signature)return y.signature;const g=B();if(!(!g||g.length!==1))return g[0]}),o.prop(x,"witness",()=>{if(y.witness)return y.witness;const g=R();if(g&&y.redeem&&y.redeem.output&&y.internalPubkey){const S=(0,s.tapleafHash)({output:y.redeem.output,version:x.redeemVersion}),E=(0,s.findScriptPath)(g,S);if(!E)return;const F=(0,s.tweakKey)(y.internalPubkey,g.hash);if(!F)return;const D=e.Buffer.concat([e.Buffer.from([x.redeemVersion|F.parity]),y.internalPubkey].concat(E));return[y.redeem.output,D]}if(y.signature)return[y.signature]}),I.validate){let g=e.Buffer.from([]);if(y.address){if(U&&U.bech32!==k().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(k().version!==d)throw new TypeError("Invalid address version");if(k().data.length!==32)throw new TypeError("Invalid address data");g=k().data}if(y.pubkey){if(g.length>0&&!g.equals(y.pubkey))throw new TypeError("Pubkey mismatch");g=y.pubkey}if(y.output){if(y.output.length!==34||y.output[0]!==h.OP_1||y.output[1]!==32)throw new TypeError("Output is invalid");if(g.length>0&&!g.equals(y.output.slice(2)))throw new TypeError("Pubkey mismatch");g=y.output.slice(2)}if(y.internalPubkey){const F=(0,s.tweakKey)(y.internalPubkey,x.hash);if(g.length>0&&!g.equals(F.x))throw new TypeError("Pubkey mismatch");g=F.x}if(g&&g.length&&!(0,i.getEccLib)().isXOnlyPoint(g))throw new TypeError("Invalid pubkey for p2tr");const S=R();if(y.hash&&S&&!y.hash.equals(S.hash))throw new TypeError("Hash mismatch");if(y.redeem&&y.redeem.output&&S){const F=(0,s.tapleafHash)({output:y.redeem.output,version:x.redeemVersion});if(!(0,s.findScriptPath)(S,F))throw new TypeError("Redeem script not in tree")}const E=B();if(y.redeem&&x.redeem){if(y.redeem.redeemVersion&&y.redeem.redeemVersion!==x.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(y.redeem.output){if(r.decompile(y.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(x.redeem.output&&!y.redeem.output.equals(x.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(y.redeem.witness&&x.redeem.witness&&!(0,n.stacksEqual)(y.redeem.witness,x.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(E&&E.length)if(E.length===1){if(y.signature&&!y.signature.equals(E[0]))throw new TypeError("Signature mismatch")}else{const F=E[E.length-1];if(F.length<33)throw new TypeError(`The control-block length is too small. Got ${F.length}, expected min 33.`);if((F.length-33)%32!==0)throw new TypeError(`The control-block length of ${F.length} is incorrect!`);const D=(F.length-33)/32;if(D>128)throw new TypeError(`The script path is too long. Got ${D}, expected max 128.`);const O=F.slice(1,33);if(y.internalPubkey&&!y.internalPubkey.equals(O))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(O))throw new TypeError("Invalid internalPubkey for p2tr witness");const K=F[0]&n.TAPLEAF_VERSION_MASK,C=E[E.length-2],G=(0,s.tapleafHash)({output:C,version:K}),V=(0,s.rootHashFromPath)(F,G),z=(0,s.tweakKey)(O,V);if(!z)throw new TypeError("Invalid outputKey for p2tr witness");if(g.length&&!g.equals(z.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(z.parity!==(F[0]&1))throw new Error("Incorrect parity")}}return Object.assign(x,y)}return Kr.p2tr=v,Kr}var Oo;function Vs(){return Oo||(Oo=1,function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.p2tr=e.p2wsh=e.p2wpkh=e.p2sh=e.p2pkh=e.p2pk=e.p2ms=e.embed=void 0;const t=ui;Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const r=li;Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return r.p2ms}});const n=hi;Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return n.p2pk}});const i=di;Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const s=pi;Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return s.p2sh}});const o=yi;Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const a=mi;Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return a.p2wsh}});const u=gl();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return u.p2tr}})}(Gi)),Gi}Object.defineProperty(ae,"__esModule",{value:!0});ae.signatureBlocksAction=ae.checkInputForSig=ae.pubkeyInScript=ae.pubkeyPositionInScript=ae.witnessStackToScriptWitness=ae.isP2TR=ae.isP2SHScript=ae.isP2WSHScript=ae.isP2WPKH=ae.isP2PKH=ae.isP2PK=ae.isP2MS=void 0;const Ro=_n,ln=Xe(),Ln=gn,_l=zt,hr=Vs();function dr(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}ae.isP2MS=dr(hr.p2ms);ae.isP2PK=dr(hr.p2pk);ae.isP2PKH=dr(hr.p2pkh);ae.isP2WPKH=dr(hr.p2wpkh);ae.isP2WSHScript=dr(hr.p2wsh);ae.isP2SHScript=dr(hr.p2sh);ae.isP2TR=dr(hr.p2tr);function vl(e){let t=Buffer.allocUnsafe(0);function r(o){t=Buffer.concat([t,Buffer.from(o)])}function n(o){const a=t.length,u=Ro.encodingLength(o);t=Buffer.concat([t,Buffer.allocUnsafe(u)]),Ro.encode(o,t,a)}function i(o){n(o.length),r(o)}function s(o){n(o.length),o.forEach(i)}return s(e),t}ae.witnessStackToScriptWitness=vl;function Wa(e,t){const r=(0,_l.hash160)(e),n=e.slice(1,33),i=ln.decompile(t);if(i===null)throw new Error("Unknown script error");return i.findIndex(s=>typeof s=="number"?!1:s.equals(e)||s.equals(r)||s.equals(n))}ae.pubkeyPositionInScript=Wa;function El(e,t){return Wa(e,t)!==-1}ae.pubkeyInScript=El;function xl(e,t){return Sl(e).some(n=>Ka(n,ln.signature.decode,t))}ae.checkInputForSig=xl;function Ka(e,t,r){const{hashType:n}=t(e),i=[];switch(n&Ln.Transaction.SIGHASH_ANYONECANPAY&&i.push("addInput"),n&31){case Ln.Transaction.SIGHASH_ALL:break;case Ln.Transaction.SIGHASH_SINGLE:case Ln.Transaction.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence");break}return i.indexOf(r)===-1}ae.signatureBlocksAction=Ka;function Sl(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=Tl(e)}else t=e.partialSig;return t.map(r=>r.signature)}function Tl(e){const t=e.finalScriptSig?ln.decompile(e.finalScriptSig)||[]:[],r=e.finalScriptWitness?ln.decompile(e.finalScriptWitness)||[]:[];return t.concat(r).filter(n=>Buffer.isBuffer(n)&&ln.isCanonicalScriptSignature(n)).map(n=>({signature:n}))}Object.defineProperty(we,"__esModule",{value:!0});we.checkTaprootInputForSigs=we.tapTreeFromList=we.tapTreeToList=we.tweakInternalPubKey=we.checkTaprootOutputFields=we.checkTaprootInputFields=we.isTaprootOutput=we.isTaprootInput=qn=we.serializeTaprootSignature=we.tapScriptFinalizer=we.toXOnly=void 0;const zs=Fe,Al=gn,bi=ae,Vt=Gs,kl=Vs(),Bl=ae,Il=e=>e.length===32?e:e.slice(1,33);we.toXOnly=Il;function Pl(e,t,r){const n=Kl(t,e,r);try{const s=ql(t,n).concat(n.script).concat(n.controlBlock);return{finalScriptWitness:(0,bi.witnessStackToScriptWitness)(s)}}catch(i){throw new Error(`Can not finalize taproot input #${e}: ${i}`)}}we.tapScriptFinalizer=Pl;function Ol(e,t){const r=t?Buffer.from([t]):Buffer.from([]);return Buffer.concat([e,r])}var qn=we.serializeTaprootSignature=Ol;function Wn(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&(0,bi.isP2TR)(e.witnessUtxo.script))}we.isTaprootInput=Wn;function Kn(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t&&(0,bi.isP2TR)(t))}we.isTaprootOutput=Kn;function Rl(e,t,r){Gl(e,t,r),zl(e,t,r)}we.checkTaprootInputFields=Rl;function Cl(e,t,r){Vl(e,t,r),Ul(e,t)}we.checkTaprootOutputFields=Cl;function Ul(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const r=t.tapInternalKey||e.tapInternalKey,n=t.tapTree||e.tapTree;if(r){const{script:i}=e,s=Ll(r,n);if(i&&!i.equals(s))throw new Error("Error adding output. Script or address missmatch.")}}function Ll(e,t){const r=t&&Ya(t.leaves),{output:n}=(0,kl.p2tr)({internalPubkey:e,scriptTree:r});return n}function Nl(e,t){const r=t.tapInternalKey,n=r&&(0,Vt.tweakKey)(r,t.tapMerkleRoot);if(!n)throw new Error(`Cannot tweak tap internal key for input #${e}. Public key: ${r&&r.toString("hex")}`);return n.x}we.tweakInternalPubKey=Nl;function Hl(e){if(!(0,zs.isTaptree)(e))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return ys(e)}we.tapTreeToList=Hl;function Ya(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:jl(e)}we.tapTreeFromList=Ya;function Fl(e,t){return Dl(e).some(n=>(0,Bl.signatureBlocksAction)(n,Ml,t))}we.checkTaprootInputForSigs=Fl;function Ml(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||Al.Transaction.SIGHASH_DEFAULT}}function Dl(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(r=>r.signature)),!t.length){const r=$l(e.finalScriptWitness);r&&t.push(r)}return t}function $l(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function ys(e,t=[],r=0){if(r>Vt.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return e?(0,zs.isTapleaf)(e)?(t.push({depth:r,leafVersion:e.version||Vt.LEAF_VERSION_TAPSCRIPT,script:e.output}),t):(e[0]&&ys(e[0],t,r+1),e[1]&&ys(e[1],t,r+1),t):[]}function jl(e){let t;for(const r of e)if(t=ms(r,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function ms(e,t,r=0){if(r>Vt.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(e.depth===r)return t?void 0:{output:e.script,version:e.leafVersion};if((0,zs.isTapleaf)(t))return;const n=ms(e,t&&t[0],r+1);if(n)return[n,t&&t[1]];const i=ms(e,t&&t[1],r+1);if(i)return[t&&t[0],i]}function Gl(e,t,r){const n=Wn(e)&&Ir(t),i=Ir(e)&&Wn(t),s=e===t&&Wn(t)&&Ir(t);if(n||i||s)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function Vl(e,t,r){const n=Kn(e)&&Ir(t),i=Ir(e)&&Kn(t),s=e===t&&Kn(t)&&Ir(t);if(n||i||s)throw new Error(`Invalid arguments for Psbt.${r}. Cannot use both taproot and non-taproot fields.`)}function zl(e,t,r){if(t.tapMerkleRoot){const n=(t.tapLeafScript||[]).every(s=>Ki(s,t.tapMerkleRoot)),i=(e.tapLeafScript||[]).every(s=>Ki(s,t.tapMerkleRoot));if(!n||!i)throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(i=>Ki(i,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${r}. Tapleaf not part of taptree.`)}function Ki(e,t){if(!t)return!0;const r=(0,Vt.tapleafHash)({output:e.script,version:e.leafVersion});return(0,Vt.rootHashFromPath)(e.controlBlock,r).equals(t)}function ql(e,t){const r=(0,Vt.tapleafHash)({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(n=>n.leafHash.equals(r)).map(n=>Wl(t.script,n)).sort((n,i)=>i.positionInScript-n.positionInScript).map(n=>n.signature)}function Wl(e,t){return Object.assign({positionInScript:(0,bi.pubkeyPositionInScript)(t.pubkey,e)},t)}function Kl(e,t,r){if(!e.tapScriptSig||!e.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${t}. No tapleaf script signature provided.`);const n=(e.tapLeafScript||[]).sort((i,s)=>i.controlBlock.length-s.controlBlock.length).find(i=>Yl(i,e.tapScriptSig,r));if(!n)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return n}function Yl(e,t,r){const n=(0,Vt.tapleafHash)({output:e.script,version:e.leafVersion});return(!r||r.equals(n))&&t.find(s=>s.leafHash.equals(n))!==void 0}function Ir(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const Be={secretMismatch:"invalid secret",secretHashLenMismatch:"secret hash should be 32 bytes",pubkeyLenMismatch:"pubkey should be 32 bytes",zeroOrNegativeExpiry:"expiry should be greater than 0",htlcAddressGenerationFailed:"failed to generate htlc address",notFunded:"address not funded",noCounterpartySigs:"counterparty signatures are required",counterPartySigNotFound:e=>"counterparty signature not found for utxo "+e,invalidCounterpartySigForUTXO:e=>"invalid counterparty signature for utxo "+e,htlcNotExpired:e=>`HTLC not expired, need more ${e} blocks`,controlBlockGenerationFailed:"failed to generate control block",invalidLeaf:"invalid leaf"},Nn=192;ie.initEccLib(ir);class hn{constructor(t,r,n,i,s,o,a,u){this.secretHash=n,this.redeemerPubkey=i,this.initiatorPubkey=s,this.expiry=o,this.signer=t,this.network=a,this.internalPubkey=Uf(),this.initiateAmount=r,this.utxoHashes=u}static async from(t,r,n,i,s,o,a){n=n.startsWith("0x")?n.slice(2):n,Zt(n.length===64,Be.secretHashLenMismatch),Zt(i.length===64||i.length===66,`initiator ${Be.pubkeyLenMismatch}`),Zt(s.length===64||s.length===66,`redeemer ${Be.pubkeyLenMismatch}`),Zt(o>0,Be.zeroOrNegativeExpiry);const u=await t.getNetwork();return new hn(t,r,n,ls(s).toString("hex"),ls(i).toString("hex"),o,u,a)}address(){const{address:t}=ie.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves()});if(!t)throw new Error(Be.htlcAddressGenerationFailed);return t}id(){return this.address()}async _buildRawTx(t,r){const n=new ie.Transaction;n.version=2;const i=this.address(),s=await this.signer.getProvider();let o=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const u of this.utxoHashes){const h=await s.getTransaction(u);for(let d=0;d<h.vout.length;d++){const p=h.vout[d];p.scriptpubkey_address===i&&o.push({txid:h.txid,vout:d,value:p.value,status:{confirmed:!1}})}}else o=await s.getUTXOs(i);const a=o.reduce((u,h)=>u+h.value,0);if(a===0)throw new Error(`${i} ${Be.notFunded}`);for(let u=0;u<o.length;u++)n.addInput(Buffer.from(o[u].txid,"hex").reverse(),o[u].vout);return r??(r=await s.suggestFee(i,a,Or.Urgency.MEDIUM)),n.addOutput(ie.address.toOutputScript(t,this.network),a-r),{tx:n,usedUtxos:o}}async _tempBuildRawTx(t,r){const n=new ie.Transaction;n.version=2;const i=this.address(),s=await this.signer.getProvider();let o=[];if(this.utxoHashes&&this.utxoHashes.length>0)for(const u of this.utxoHashes){const h=await s.getTransaction(u);for(let d=0;d<h.vout.length;d++){const p=h.vout[d];p.scriptpubkey_address===i&&o.push({txid:h.txid,vout:d,value:p.value,status:{confirmed:!1}})}}else o=await s.getUTXOs(i);const a=o.reduce((u,h)=>u+h.value,0);if(a===0)throw new Error(`${i} ${Be.notFunded}`);for(let u=0;u<o.length;u++)n.addInput(Buffer.from(o[u].txid,"hex").reverse(),o[u].vout);if(n.addOutput(ie.address.toOutputScript(t,this.network),a),r){const u=await s.getFeeRates(),h=Math.ceil(u.hourFee*r),d=a-h;n.outs[0].value=d}return{tx:n,usedUtxos:o}}async buildRawTx(t){return await this._buildRawTx(await this.signer.getAddress(),t)}getOutputScript(){return ie.address.toOutputScript(this.address(),this.network)}async init(t){return t??(t=await(await this.signer.getProvider()).suggestFee(await this.signer.getAddress(),this.initiateAmount,Or.Urgency.MEDIUM)),await this.signer.send(this.address(),this.initiateAmount,t)}async generateRedeemSACP(t,r,n){const{tx:i,usedUtxos:s}=await this._buildRawTx(r,n),o=this.getOutputScript(),a=ie.Transaction.SIGHASH_SINGLE|ie.Transaction.SIGHASH_ANYONECANPAY,u=this.leafHash(1),h=s.map(p=>p.value),d=vr(o,s.length);for(let p=0;p<i.ins.length;p++){const v=i.hashForWitnessV1(p,d,h,a,u),y=await this.signer.signSchnorr(v);i.setWitness(p,[qn(y,a),Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return i.toHex()}async generateInstantRefundSACP(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t,r),s=this.getOutputScript(),o=ie.Transaction.SIGHASH_SINGLE|ie.Transaction.SIGHASH_ANYONECANPAY,a=this.leafHash(2),u=i.map(d=>d.value),h=vr(s,i.length);for(let d=0;d<n.ins.length;d++){const p=n.hashForWitnessV1(d,h,u,o,a),v=await this.signer.signSchnorr(p);n.setWitness(d,[qn(v,o),qn(v,o),this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return n.toHex()}async instantRefund(t,r){Zt(t.length>0,Be.noCounterpartySigs);const{tx:n,usedUtxos:i}=await this.buildRawTx(r);for(const p of i)if(!t.find(v=>v.utxo===p.txid))throw new Error(Be.counterPartySigNotFound(p.txid));const s=this.getOutputScript(),o=ie.Transaction.SIGHASH_DEFAULT,a=this.leafHash(2),u=i.map(p=>p.value),h=vr(s,i.length);for(let p=0;p<n.ins.length;p++){const v=n.hashForWitnessV1(p,h,u,o,a);if(!ir.verifySchnorr(v,Buffer.from(this.redeemerPubkey,"hex"),Buffer.from(t[p].sig,"hex")))throw new Error(Be.invalidCounterpartySigForUTXO(t[p].utxo));const y=await this.signer.signSchnorr(v),I=Buffer.from(n.ins[p].hash).reverse().toString("hex"),k=t.find(B=>B.utxo===I);if(!k)throw new Error(Be.counterPartySigNotFound(I));n.setWitness(p,[Buffer.from(k.sig,"hex"),y,this.instantRefundLeaf(),this.generateControlBlockFor(2)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async redeem(t,r){Zt(ie.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,Be.secretMismatch);const n=r??await this.signer.getAddress(),{tx:i,usedUtxos:s}=await this._tempBuildRawTx(n),o=this.leafHash(1),a=s.map(v=>v.value),u=vr(this.getOutputScript(),s.length),h=ie.Transaction.SIGHASH_DEFAULT;for(let v=0;v<i.ins.length;v++){const y=i.hashForWitnessV1(v,u,a,h,o),I=await this.signer.signSchnorr(y);i.setWitness(v,[I,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:d}=await this._tempBuildRawTx(n,i.virtualSize());for(let v=0;v<d.ins.length;v++){const y=d.hashForWitnessV1(v,u,a,h,o),I=await this.signer.signSchnorr(y);d.setWitness(v,[I,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return await(await this.signer.getProvider()).broadcast(d.toHex())}async getRedeemHex(t,r){Zt(ie.crypto.sha256(Buffer.from(t,"hex")).toString("hex")===this.secretHash,Be.secretMismatch);const n=r??await this.signer.getAddress(),{tx:i,usedUtxos:s}=await this._tempBuildRawTx(n),o=this.leafHash(1),a=s.map(p=>p.value),u=vr(this.getOutputScript(),s.length),h=ie.Transaction.SIGHASH_DEFAULT;for(let p=0;p<i.ins.length;p++){const v=i.hashForWitnessV1(p,u,a,h,o),y=await this.signer.signSchnorr(v);i.setWitness(p,[y,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}const{tx:d}=await this._tempBuildRawTx(n,i.virtualSize());for(let p=0;p<d.ins.length;p++){const v=d.hashForWitnessV1(p,u,a,h,o),y=await this.signer.signSchnorr(v);d.setWitness(p,[y,Buffer.from(t,"hex"),this.redeemLeaf(),this.generateControlBlockFor(1)])}return d.toHex()}async refund(t,r){const{tx:n,usedUtxos:i}=await this._buildRawTx(t??await this.signer.getAddress(),r),[s,o]=await this.canRefund(i);if(!s)throw new Error(Be.htlcNotExpired(o));const a=this.leafHash(0),u=i.map(v=>v.value),h=vr(this.getOutputScript(),i.length),d=ie.Transaction.SIGHASH_DEFAULT;for(let v=0;v<n.ins.length;v++){n.ins[v].sequence=this.expiry;const y=n.hashForWitnessV1(v,h,u,d,a),I=await this.signer.signSchnorr(y);n.setWitness(v,[I,this.refundLeaf(),this.generateControlBlockFor(0)])}return await(await this.signer.getProvider()).broadcast(n.toHex())}async canRefund(t){const n=await(await this.signer.getProvider()).getLatestTip();for(const i of t){let s=0;if(i.status.confirmed&&i.status.block_height+this.expiry>n?s=i.status.block_height+this.expiry-n+1:i.status.confirmed||(s=this.expiry+1),s>0)return[!1,s]}return[!0,0]}generateControlBlockFor(t){let r;switch(t){case 1:r=this.redeemLeaf();break;case 0:r=this.refundLeaf();break;case 2:r=this.instantRefundLeaf();break;default:throw new Error(Be.invalidLeaf)}const n=ie.payments.p2tr({internalPubkey:this.internalPubkey,network:this.network,scriptTree:this.leaves(),redeem:{output:r,redeemVersion:Nn}});if(!n.witness)throw new Error(Be.controlBlockGenerationFailed);return n.witness[n.witness.length-1]}leafHash(t){let r=this.redeemLeaf();return t===0&&(r=this.refundLeaf()),t===2&&(r=this.instantRefundLeaf()),ie.crypto.taggedHash("TapLeaf",_f(r))}refundLeaf(){return ie.script.fromASM(`
|
|
10
10
|
${ie.script.number.encode(this.expiry).toString("hex")}
|
|
11
11
|
OP_CHECKSEQUENCEVERIFY
|
|
12
12
|
OP_DROP
|
|
@@ -25,10 +25,10 @@
|
|
|
25
25
|
OP_CHECKSIGADD
|
|
26
26
|
OP_2
|
|
27
27
|
OP_NUMEQUAL
|
|
28
|
-
`.trim().replace(/\s+/g," "))}leaves(){return[{version:
|
|
29
|
-
`,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};
|
|
30
|
-
`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var
|
|
31
|
-
Use Chrome, Firefox or Internet Explorer 11`)}var $l=Ve.Buffer,ti=zt.crypto||zt.msCrypto;ti&&ti.getRandomValues?bs.exports=jl:bs.exports=Dl;function jl(e,t){if(e>Ml)throw new RangeError("requested too many random bytes");var r=$l.allocUnsafe(e);if(e>0)if(e>Yi)for(var n=0;n<e;n+=Yi)ti.getRandomValues(r.slice(n,n+Yi));else ti.getRandomValues(r);return typeof t=="function"?process.nextTick(function(){t(null,r)}):r}var Gl=bs.exports,gs={exports:{}};typeof Object.create=="function"?gs.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:gs.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}};var Oe=gs.exports,_s={exports:{}},Gs={exports:{}},Or=typeof Reflect=="object"?Reflect:null,Bo=Or&&typeof Or.apply=="function"?Or.apply:function(t,r,n){return Function.prototype.apply.call(t,r,n)},Jn;Or&&typeof Or.ownKeys=="function"?Jn=Or.ownKeys:Object.getOwnPropertySymbols?Jn=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Jn=function(t){return Object.getOwnPropertyNames(t)};function Vl(e){console&&console.warn&&console.warn(e)}var Ya=Number.isNaN||function(t){return t!==t};function se(){se.init.call(this)}Gs.exports=se;Gs.exports.once=Kl;se.EventEmitter=se;se.prototype._events=void 0;se.prototype._eventsCount=0;se.prototype._maxListeners=void 0;var Io=10;function wi(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(se,"defaultMaxListeners",{enumerable:!0,get:function(){return Io},set:function(e){if(typeof e!="number"||e<0||Ya(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Io=e}});se.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};se.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||Ya(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function Xa(e){return e._maxListeners===void 0?se.defaultMaxListeners:e._maxListeners}se.prototype.getMaxListeners=function(){return Xa(this)};se.prototype.emit=function(t){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=t==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var u=s[t];if(u===void 0)return!1;if(typeof u=="function")Bo(u,this,r);else for(var d=u.length,h=tc(u,d),n=0;n<d;++n)Bo(h[n],this,r);return!0};function Ja(e,t,r,n){var i,s,o;if(wi(r),s=e._events,s===void 0?(s=e._events=Object.create(null),e._eventsCount=0):(s.newListener!==void 0&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),o===void 0)o=s[t]=r,++e._eventsCount;else if(typeof o=="function"?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=Xa(e),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,Vl(a)}return e}se.prototype.addListener=function(t,r){return Ja(this,t,r,!1)};se.prototype.on=se.prototype.addListener;se.prototype.prependListener=function(t,r){return Ja(this,t,r,!0)};function zl(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Qa(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=zl.bind(n);return i.listener=r,n.wrapFn=i,i}se.prototype.once=function(t,r){return wi(r),this.on(t,Qa(this,t,r)),this};se.prototype.prependOnceListener=function(t,r){return wi(r),this.prependListener(t,Qa(this,t,r)),this};se.prototype.removeListener=function(t,r){var n,i,s,o,a;if(wi(r),i=this._events,i===void 0)return this;if(n=i[t],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():ql(n,s),n.length===1&&(i[t]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",t,a||r)}return this};se.prototype.off=se.prototype.removeListener;se.prototype.removeAllListeners=function(t){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[t],typeof r=="function")this.removeListener(t,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(t,r[i]);return this};function Za(e,t,r){var n=e._events;if(n===void 0)return[];var i=n[t];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?Wl(i):tc(i,i.length)}se.prototype.listeners=function(t){return Za(this,t,!0)};se.prototype.rawListeners=function(t){return Za(this,t,!1)};se.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):ec.call(e,t)};se.prototype.listenerCount=ec;function ec(e){var t=this._events;if(t!==void 0){var r=t[e];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}se.prototype.eventNames=function(){return this._eventsCount>0?Jn(this._events):[]};function tc(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function ql(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function Wl(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}function Kl(e,t){return new Promise(function(r,n){function i(o){e.removeListener(t,s),n(o)}function s(){typeof e.removeListener=="function"&&e.removeListener("error",i),r([].slice.call(arguments))}rc(e,t,s,{once:!0}),t!=="error"&&Yl(e,i,{once:!0})})}function Yl(e,t,r){typeof e.on=="function"&&rc(e,"error",t,r)}function rc(e,t,r,n){if(typeof e.on=="function")n.once?e.once(t,r):e.on(t,r);else if(typeof e.addEventListener=="function")e.addEventListener(t,function i(s){n.once&&e.removeEventListener(t,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}var nc=Gs.exports,ic=nc.EventEmitter;const Xl={},Jl=Object.freeze(Object.defineProperty({__proto__:null,default:Xl},Symbol.toStringTag,{value:"Module"})),Vs=Rf(Jl);var Xi,Po;function Ql(){if(Po)return Xi;Po=1;function e(I,k){var B=Object.keys(I);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(I);k&&(R=R.filter(function(U){return Object.getOwnPropertyDescriptor(I,U).enumerable})),B.push.apply(B,R)}return B}function t(I){for(var k=1;k<arguments.length;k++){var B=arguments[k]!=null?arguments[k]:{};k%2?e(Object(B),!0).forEach(function(R){r(I,R,B[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(I,Object.getOwnPropertyDescriptors(B)):e(Object(B)).forEach(function(R){Object.defineProperty(I,R,Object.getOwnPropertyDescriptor(B,R))})}return I}function r(I,k,B){return k=o(k),k in I?Object.defineProperty(I,k,{value:B,enumerable:!0,configurable:!0,writable:!0}):I[k]=B,I}function n(I,k){if(!(I instanceof k))throw new TypeError("Cannot call a class as a function")}function i(I,k){for(var B=0;B<k.length;B++){var R=k[B];R.enumerable=R.enumerable||!1,R.configurable=!0,"value"in R&&(R.writable=!0),Object.defineProperty(I,o(R.key),R)}}function s(I,k,B){return k&&i(I.prototype,k),Object.defineProperty(I,"prototype",{writable:!1}),I}function o(I){var k=a(I,"string");return typeof k=="symbol"?k:String(k)}function a(I,k){if(typeof I!="object"||I===null)return I;var B=I[Symbol.toPrimitive];if(B!==void 0){var R=B.call(I,k);if(typeof R!="object")return R;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(I)}var u=It,d=u.Buffer,h=Vs,y=h.inspect,v=y&&y.custom||"inspect";function p(I,k,B){d.prototype.copy.call(I,k,B)}return Xi=function(){function I(){n(this,I),this.head=null,this.tail=null,this.length=0}return s(I,[{key:"push",value:function(B){var R={data:B,next:null};this.length>0?this.tail.next=R:this.head=R,this.tail=R,++this.length}},{key:"unshift",value:function(B){var R={data:B,next:this.head};this.length===0&&(this.tail=R),this.head=R,++this.length}},{key:"shift",value:function(){if(this.length!==0){var B=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,B}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(B){if(this.length===0)return"";for(var R=this.head,U=""+R.data;R=R.next;)U+=B+R.data;return U}},{key:"concat",value:function(B){if(this.length===0)return d.alloc(0);for(var R=d.allocUnsafe(B>>>0),U=this.head,x=0;U;)p(U.data,R,x),x+=U.data.length,U=U.next;return R}},{key:"consume",value:function(B,R){var U;return B<this.head.data.length?(U=this.head.data.slice(0,B),this.head.data=this.head.data.slice(B)):B===this.head.data.length?U=this.shift():U=R?this._getString(B):this._getBuffer(B),U}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(B){var R=this.head,U=1,x=R.data;for(B-=x.length;R=R.next;){var g=R.data,S=B>g.length?g.length:B;if(S===g.length?x+=g:x+=g.slice(0,B),B-=S,B===0){S===g.length?(++U,R.next?this.head=R.next:this.head=this.tail=null):(this.head=R,R.data=g.slice(S));break}++U}return this.length-=U,x}},{key:"_getBuffer",value:function(B){var R=d.allocUnsafe(B),U=this.head,x=1;for(U.data.copy(R),B-=U.data.length;U=U.next;){var g=U.data,S=B>g.length?g.length:B;if(g.copy(R,R.length-B,0,S),B-=S,B===0){S===g.length?(++x,U.next?this.head=U.next:this.head=this.tail=null):(this.head=U,U.data=g.slice(S));break}++x}return this.length-=x,R}},{key:v,value:function(B,R){return y(this,t(t({},R),{},{depth:0,customInspect:!1}))}}]),I}(),Xi}function Zl(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(vs,this,e)):process.nextTick(vs,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(s){!t&&s?r._writableState?r._writableState.errorEmitted?process.nextTick(Qn,r):(r._writableState.errorEmitted=!0,process.nextTick(Oo,r,s)):process.nextTick(Oo,r,s):t?(process.nextTick(Qn,r),t(s)):process.nextTick(Qn,r)}),this)}function Oo(e,t){vs(e,t),Qn(e)}function Qn(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function ed(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function vs(e,t){e.emit("error",t)}function td(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}var sc={destroy:Zl,undestroy:ed,errorOrDestroy:td},yr={};function rd(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var oc={};function tt(e,t,r){r||(r=Error);function n(s,o,a){return typeof t=="string"?t:t(s,o,a)}var i=function(s){rd(o,s);function o(a,u,d){return s.call(this,n(a,u,d))||this}return o}(r);i.prototype.name=r.name,i.prototype.code=e,oc[e]=i}function Ro(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map(function(n){return String(n)}),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:r===2?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}else return"of ".concat(t," ").concat(String(e))}function nd(e,t,r){return e.substr(0,t.length)===t}function id(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function sd(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?!1:e.indexOf(t,r)!==-1}tt("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError);tt("ERR_INVALID_ARG_TYPE",function(e,t,r){var n;typeof t=="string"&&nd(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be";var i;if(id(e," argument"))i="The ".concat(e," ").concat(n," ").concat(Ro(t,"type"));else{var s=sd(e,".")?"property":"argument";i='The "'.concat(e,'" ').concat(s," ").concat(n," ").concat(Ro(t,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);tt("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");tt("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"});tt("ERR_STREAM_PREMATURE_CLOSE","Premature close");tt("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"});tt("ERR_MULTIPLE_CALLBACK","Callback called multiple times");tt("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");tt("ERR_STREAM_WRITE_AFTER_END","write after end");tt("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);tt("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError);tt("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");yr.codes=oc;var od=yr.codes.ERR_INVALID_OPT_VALUE;function ad(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function cd(e,t,r,n){var i=ad(t,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new od(s,i)}return Math.floor(i)}return e.objectMode?16:16*1024}var ac={getHighWaterMark:cd},fd=ud;function ud(e,t){if(Ji("noDeprecation"))return e;var r=!1;function n(){if(!r){if(Ji("throwDeprecation"))throw new Error(t);Ji("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}return n}function Ji(e){try{if(!zt.localStorage)return!1}catch{return!1}var t=zt.localStorage[e];return t==null?!1:String(t).toLowerCase()==="true"}var Qi,Co;function cc(){if(Co)return Qi;Co=1,Qi=D;function e(A){var T=this;this.next=null,this.entry=null,this.finish=function(){yt(T,A)}}var t;D.WritableState=E;var r={deprecate:fd},n=ic,i=It.Buffer,s=(typeof zt<"u"?zt:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function o(A){return i.from(A)}function a(A){return i.isBuffer(A)||A instanceof s}var u=sc,d=ac,h=d.getHighWaterMark,y=yr.codes,v=y.ERR_INVALID_ARG_TYPE,p=y.ERR_METHOD_NOT_IMPLEMENTED,I=y.ERR_MULTIPLE_CALLBACK,k=y.ERR_STREAM_CANNOT_PIPE,B=y.ERR_STREAM_DESTROYED,R=y.ERR_STREAM_NULL_VALUES,U=y.ERR_STREAM_WRITE_AFTER_END,x=y.ERR_UNKNOWN_ENCODING,g=u.errorOrDestroy;Oe(D,n);function S(){}function E(A,T,H){t=t||Fr(),A=A||{},typeof H!="boolean"&&(H=T instanceof t),this.objectMode=!!A.objectMode,H&&(this.objectMode=this.objectMode||!!A.writableObjectMode),this.highWaterMark=h(this,A,"writableHighWaterMark",H),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var q=A.decodeStrings===!1;this.decodeStrings=!q,this.defaultEncoding=A.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(Y){ve(T,Y)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=A.emitClose!==!1,this.autoDestroy=!!A.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}E.prototype.getBuffer=function(){for(var T=this.bufferedRequest,H=[];T;)H.push(T),T=T.next;return H},function(){try{Object.defineProperty(E.prototype,"buffer",{get:r.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var F;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(F=Function.prototype[Symbol.hasInstance],Object.defineProperty(D,Symbol.hasInstance,{value:function(T){return F.call(this,T)?!0:this!==D?!1:T&&T._writableState instanceof E}})):F=function(T){return T instanceof this};function D(A){t=t||Fr();var T=this instanceof t;if(!T&&!F.call(D,this))return new D(A);this._writableState=new E(A,this,T),this.writable=!0,A&&(typeof A.write=="function"&&(this._write=A.write),typeof A.writev=="function"&&(this._writev=A.writev),typeof A.destroy=="function"&&(this._destroy=A.destroy),typeof A.final=="function"&&(this._final=A.final)),n.call(this)}D.prototype.pipe=function(){g(this,new k)};function O(A,T){var H=new U;g(A,H),process.nextTick(T,H)}function K(A,T,H,q){var Y;return H===null?Y=new R:typeof H!="string"&&!T.objectMode&&(Y=new v("chunk",["string","Buffer"],H)),Y?(g(A,Y),process.nextTick(q,Y),!1):!0}D.prototype.write=function(A,T,H){var q=this._writableState,Y=!1,b=!q.objectMode&&a(A);return b&&!i.isBuffer(A)&&(A=o(A)),typeof T=="function"&&(H=T,T=null),b?T="buffer":T||(T=q.defaultEncoding),typeof H!="function"&&(H=S),q.ending?O(this,H):(b||K(this,q,A,H))&&(q.pendingcb++,Y=G(this,q,b,A,T,H)),Y},D.prototype.cork=function(){this._writableState.corked++},D.prototype.uncork=function(){var A=this._writableState;A.corked&&(A.corked--,!A.writing&&!A.corked&&!A.bufferProcessing&&A.bufferedRequest&&qe(this,A))},D.prototype.setDefaultEncoding=function(T){if(typeof T=="string"&&(T=T.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((T+"").toLowerCase())>-1))throw new x(T);return this._writableState.defaultEncoding=T,this},Object.defineProperty(D.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function C(A,T,H){return!A.objectMode&&A.decodeStrings!==!1&&typeof T=="string"&&(T=i.from(T,H)),T}Object.defineProperty(D.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function G(A,T,H,q,Y,b){if(!H){var w=C(T,q,Y);q!==w&&(H=!0,Y="buffer",q=w)}var N=T.objectMode?1:q.length;T.length+=N;var $=T.length<T.highWaterMark;if($||(T.needDrain=!0),T.writing||T.corked){var ye=T.lastBufferedRequest;T.lastBufferedRequest={chunk:q,encoding:Y,isBuf:H,callback:b,next:null},ye?ye.next=T.lastBufferedRequest:T.bufferedRequest=T.lastBufferedRequest,T.bufferedRequestCount+=1}else V(A,T,!1,N,q,Y,b);return $}function V(A,T,H,q,Y,b,w){T.writelen=q,T.writecb=w,T.writing=!0,T.sync=!0,T.destroyed?T.onwrite(new B("write")):H?A._writev(Y,T.onwrite):A._write(Y,b,T.onwrite),T.sync=!1}function z(A,T,H,q,Y){--T.pendingcb,H?(process.nextTick(Y,q),process.nextTick(We,A,T),A._writableState.errorEmitted=!0,g(A,q)):(Y(q),A._writableState.errorEmitted=!0,g(A,q),We(A,T))}function ee(A){A.writing=!1,A.writecb=null,A.length-=A.writelen,A.writelen=0}function ve(A,T){var H=A._writableState,q=H.sync,Y=H.writecb;if(typeof Y!="function")throw new I;if(ee(H),T)z(A,H,q,T,Y);else{var b=Ot(H)||A.destroyed;!b&&!H.corked&&!H.bufferProcessing&&H.bufferedRequest&&qe(A,H),q?process.nextTick(ze,A,H,b,Y):ze(A,H,b,Y)}}function ze(A,T,H,q){H||rt(A,T),T.pendingcb--,q(),We(A,T)}function rt(A,T){T.length===0&&T.needDrain&&(T.needDrain=!1,A.emit("drain"))}function qe(A,T){T.bufferProcessing=!0;var H=T.bufferedRequest;if(A._writev&&H&&H.next){var q=T.bufferedRequestCount,Y=new Array(q),b=T.corkedRequestsFree;b.entry=H;for(var w=0,N=!0;H;)Y[w]=H,H.isBuf||(N=!1),H=H.next,w+=1;Y.allBuffers=N,V(A,T,!0,T.length,Y,"",b.finish),T.pendingcb++,T.lastBufferedRequest=null,b.next?(T.corkedRequestsFree=b.next,b.next=null):T.corkedRequestsFree=new e(T),T.bufferedRequestCount=0}else{for(;H;){var $=H.chunk,ye=H.encoding,X=H.callback,ne=T.objectMode?1:$.length;if(V(A,T,!1,ne,$,ye,X),H=H.next,T.bufferedRequestCount--,T.writing)break}H===null&&(T.lastBufferedRequest=null)}T.bufferedRequest=H,T.bufferProcessing=!1}D.prototype._write=function(A,T,H){H(new p("_write()"))},D.prototype._writev=null,D.prototype.end=function(A,T,H){var q=this._writableState;return typeof A=="function"?(H=A,A=null,T=null):typeof T=="function"&&(H=T,T=null),A!=null&&this.write(A,T),q.corked&&(q.corked=1,this.uncork()),q.ending||Rt(this,q,H),this},Object.defineProperty(D.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function Ot(A){return A.ending&&A.length===0&&A.bufferedRequest===null&&!A.finished&&!A.writing}function pe(A,T){A._final(function(H){T.pendingcb--,H&&g(A,H),T.prefinished=!0,A.emit("prefinish"),We(A,T)})}function Ee(A,T){!T.prefinished&&!T.finalCalled&&(typeof A._final=="function"&&!T.destroyed?(T.pendingcb++,T.finalCalled=!0,process.nextTick(pe,A,T)):(T.prefinished=!0,A.emit("prefinish")))}function We(A,T){var H=Ot(T);if(H&&(Ee(A,T),T.pendingcb===0&&(T.finished=!0,A.emit("finish"),T.autoDestroy))){var q=A._readableState;(!q||q.autoDestroy&&q.endEmitted)&&A.destroy()}return H}function Rt(A,T,H){T.ending=!0,We(A,T),H&&(T.finished?process.nextTick(H):A.once("finish",H)),T.ended=!0,A.writable=!1}function yt(A,T,H){var q=A.entry;for(A.entry=null;q;){var Y=q.callback;T.pendingcb--,Y(H),q=q.next}T.corkedRequestsFree.next=A}return Object.defineProperty(D.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(T){this._writableState&&(this._writableState.destroyed=T)}}),D.prototype.destroy=u.destroy,D.prototype._undestroy=u.undestroy,D.prototype._destroy=function(A,T){T(A)},Qi}var Zi,Uo;function Fr(){if(Uo)return Zi;Uo=1;var e=Object.keys||function(d){var h=[];for(var y in d)h.push(y);return h};Zi=o;var t=uc(),r=cc();Oe(o,t);for(var n=e(r.prototype),i=0;i<n.length;i++){var s=n[i];o.prototype[s]||(o.prototype[s]=r.prototype[s])}function o(d){if(!(this instanceof o))return new o(d);t.call(this,d),r.call(this,d),this.allowHalfOpen=!0,d&&(d.readable===!1&&(this.readable=!1),d.writable===!1&&(this.writable=!1),d.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",a)))}Object.defineProperty(o.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(o.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(o.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function a(){this._writableState.ended||process.nextTick(u,this)}function u(d){d.end()}return Object.defineProperty(o.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(h){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=h,this._writableState.destroyed=h)}}),Zi}var ri={},zs=Ve.Buffer,Lo=zs.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function ld(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function dd(e){var t=ld(e);if(typeof t!="string"&&(zs.isEncoding===Lo||!Lo(e)))throw new Error("Unknown encoding: "+e);return t||e}ri.StringDecoder=xn;function xn(e){this.encoding=dd(e);var t;switch(this.encoding){case"utf16le":this.text=wd,this.end=gd,t=4;break;case"utf8":this.fillLast=yd,t=4;break;case"base64":this.text=_d,this.end=vd,t=3;break;default:this.write=Ed,this.end=xd;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=zs.allocUnsafe(t)}xn.prototype.write=function(e){if(e.length===0)return"";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""};xn.prototype.end=bd;xn.prototype.text=md;xn.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function es(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function hd(e,t,r){var n=t.length-1;if(n<r)return 0;var i=es(t[n]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--n<r||i===-2?0:(i=es(t[n]),i>=0?(i>0&&(e.lastNeed=i-2),i):--n<r||i===-2?0:(i=es(t[n]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function pd(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"�"}}function yd(e){var t=this.lastTotal-this.lastNeed,r=pd(this,e);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function md(e,t){var r=hd(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function bd(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function wd(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function gd(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function _d(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function vd(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function Ed(e){return e.toString(this.encoding)}function xd(e){return e&&e.length?this.write(e):""}var No=yr.codes.ERR_STREAM_PREMATURE_CLOSE;function Sd(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];e.apply(this,n)}}}function Td(){}function Ad(e){return e.setHeader&&typeof e.abort=="function"}function fc(e,t,r){if(typeof t=="function")return fc(e,null,t);t||(t={}),r=Sd(r||Td);var n=t.readable||t.readable!==!1&&e.readable,i=t.writable||t.writable!==!1&&e.writable,s=function(){e.writable||a()},o=e._writableState&&e._writableState.finished,a=function(){i=!1,o=!0,n||r.call(e)},u=e._readableState&&e._readableState.endEmitted,d=function(){n=!1,u=!0,i||r.call(e)},h=function(I){r.call(e,I)},y=function(){var I;if(n&&!u)return(!e._readableState||!e._readableState.ended)&&(I=new No),r.call(e,I);if(i&&!o)return(!e._writableState||!e._writableState.ended)&&(I=new No),r.call(e,I)},v=function(){e.req.on("finish",a)};return Ad(e)?(e.on("complete",a),e.on("abort",y),e.req?v():e.on("request",v)):i&&!e._writableState&&(e.on("end",s),e.on("close",s)),e.on("end",d),e.on("finish",a),t.error!==!1&&e.on("error",h),e.on("close",y),function(){e.removeListener("complete",a),e.removeListener("abort",y),e.removeListener("request",v),e.req&&e.req.removeListener("finish",a),e.removeListener("end",s),e.removeListener("close",s),e.removeListener("finish",a),e.removeListener("end",d),e.removeListener("error",h),e.removeListener("close",y)}}var qs=fc,ts,Ho;function kd(){if(Ho)return ts;Ho=1;var e;function t(x,g,S){return g=r(g),g in x?Object.defineProperty(x,g,{value:S,enumerable:!0,configurable:!0,writable:!0}):x[g]=S,x}function r(x){var g=n(x,"string");return typeof g=="symbol"?g:String(g)}function n(x,g){if(typeof x!="object"||x===null)return x;var S=x[Symbol.toPrimitive];if(S!==void 0){var E=S.call(x,g);if(typeof E!="object")return E;throw new TypeError("@@toPrimitive must return a primitive value.")}return(g==="string"?String:Number)(x)}var i=qs,s=Symbol("lastResolve"),o=Symbol("lastReject"),a=Symbol("error"),u=Symbol("ended"),d=Symbol("lastPromise"),h=Symbol("handlePromise"),y=Symbol("stream");function v(x,g){return{value:x,done:g}}function p(x){var g=x[s];if(g!==null){var S=x[y].read();S!==null&&(x[d]=null,x[s]=null,x[o]=null,g(v(S,!1)))}}function I(x){process.nextTick(p,x)}function k(x,g){return function(S,E){x.then(function(){if(g[u]){S(v(void 0,!0));return}g[h](S,E)},E)}}var B=Object.getPrototypeOf(function(){}),R=Object.setPrototypeOf((e={get stream(){return this[y]},next:function(){var g=this,S=this[a];if(S!==null)return Promise.reject(S);if(this[u])return Promise.resolve(v(void 0,!0));if(this[y].destroyed)return new Promise(function(O,K){process.nextTick(function(){g[a]?K(g[a]):O(v(void 0,!0))})});var E=this[d],F;if(E)F=new Promise(k(E,this));else{var D=this[y].read();if(D!==null)return Promise.resolve(v(D,!1));F=new Promise(this[h])}return this[d]=F,F}},t(e,Symbol.asyncIterator,function(){return this}),t(e,"return",function(){var g=this;return new Promise(function(S,E){g[y].destroy(null,function(F){if(F){E(F);return}S(v(void 0,!0))})})}),e),B),U=function(g){var S,E=Object.create(R,(S={},t(S,y,{value:g,writable:!0}),t(S,s,{value:null,writable:!0}),t(S,o,{value:null,writable:!0}),t(S,a,{value:null,writable:!0}),t(S,u,{value:g._readableState.endEmitted,writable:!0}),t(S,h,{value:function(D,O){var K=E[y].read();K?(E[d]=null,E[s]=null,E[o]=null,D(v(K,!1))):(E[s]=D,E[o]=O)},writable:!0}),S));return E[d]=null,i(g,function(F){if(F&&F.code!=="ERR_STREAM_PREMATURE_CLOSE"){var D=E[o];D!==null&&(E[d]=null,E[s]=null,E[o]=null,D(F)),E[a]=F;return}var O=E[s];O!==null&&(E[d]=null,E[s]=null,E[o]=null,O(v(void 0,!0))),E[u]=!0}),g.on("readable",I.bind(null,E)),E};return ts=U,ts}var rs,Fo;function Bd(){return Fo||(Fo=1,rs=function(){throw new Error("Readable.from is not available in the browser")}),rs}var ns,Mo;function uc(){if(Mo)return ns;Mo=1,ns=O;var e;O.ReadableState=D,nc.EventEmitter;var t=function(w,N){return w.listeners(N).length},r=ic,n=It.Buffer,i=(typeof zt<"u"?zt:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function s(b){return n.from(b)}function o(b){return n.isBuffer(b)||b instanceof i}var a=Vs,u;a&&a.debuglog?u=a.debuglog("stream"):u=function(){};var d=Ql(),h=sc,y=ac,v=y.getHighWaterMark,p=yr.codes,I=p.ERR_INVALID_ARG_TYPE,k=p.ERR_STREAM_PUSH_AFTER_EOF,B=p.ERR_METHOD_NOT_IMPLEMENTED,R=p.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,U,x,g;Oe(O,r);var S=h.errorOrDestroy,E=["error","close","destroy","pause","resume"];function F(b,w,N){if(typeof b.prependListener=="function")return b.prependListener(w,N);!b._events||!b._events[w]?b.on(w,N):Array.isArray(b._events[w])?b._events[w].unshift(N):b._events[w]=[N,b._events[w]]}function D(b,w,N){e=e||Fr(),b=b||{},typeof N!="boolean"&&(N=w instanceof e),this.objectMode=!!b.objectMode,N&&(this.objectMode=this.objectMode||!!b.readableObjectMode),this.highWaterMark=v(this,b,"readableHighWaterMark",N),this.buffer=new d,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=b.emitClose!==!1,this.autoDestroy=!!b.autoDestroy,this.destroyed=!1,this.defaultEncoding=b.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,b.encoding&&(U||(U=ri.StringDecoder),this.decoder=new U(b.encoding),this.encoding=b.encoding)}function O(b){if(e=e||Fr(),!(this instanceof O))return new O(b);var w=this instanceof e;this._readableState=new D(b,this,w),this.readable=!0,b&&(typeof b.read=="function"&&(this._read=b.read),typeof b.destroy=="function"&&(this._destroy=b.destroy)),r.call(this)}Object.defineProperty(O.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(w){this._readableState&&(this._readableState.destroyed=w)}}),O.prototype.destroy=h.destroy,O.prototype._undestroy=h.undestroy,O.prototype._destroy=function(b,w){w(b)},O.prototype.push=function(b,w){var N=this._readableState,$;return N.objectMode?$=!0:typeof b=="string"&&(w=w||N.defaultEncoding,w!==N.encoding&&(b=n.from(b,w),w=""),$=!0),K(this,b,w,!1,$)},O.prototype.unshift=function(b){return K(this,b,null,!0,!1)};function K(b,w,N,$,ye){u("readableAddChunk",w);var X=b._readableState;if(w===null)X.reading=!1,ve(b,X);else{var ne;if(ye||(ne=G(X,w)),ne)S(b,ne);else if(X.objectMode||w&&w.length>0)if(typeof w!="string"&&!X.objectMode&&Object.getPrototypeOf(w)!==n.prototype&&(w=s(w)),$)X.endEmitted?S(b,new R):C(b,X,w,!0);else if(X.ended)S(b,new k);else{if(X.destroyed)return!1;X.reading=!1,X.decoder&&!N?(w=X.decoder.write(w),X.objectMode||w.length!==0?C(b,X,w,!1):qe(b,X)):C(b,X,w,!1)}else $||(X.reading=!1,qe(b,X))}return!X.ended&&(X.length<X.highWaterMark||X.length===0)}function C(b,w,N,$){w.flowing&&w.length===0&&!w.sync?(w.awaitDrain=0,b.emit("data",N)):(w.length+=w.objectMode?1:N.length,$?w.buffer.unshift(N):w.buffer.push(N),w.needReadable&&ze(b)),qe(b,w)}function G(b,w){var N;return!o(w)&&typeof w!="string"&&w!==void 0&&!b.objectMode&&(N=new I("chunk",["string","Buffer","Uint8Array"],w)),N}O.prototype.isPaused=function(){return this._readableState.flowing===!1},O.prototype.setEncoding=function(b){U||(U=ri.StringDecoder);var w=new U(b);this._readableState.decoder=w,this._readableState.encoding=this._readableState.decoder.encoding;for(var N=this._readableState.buffer.head,$="";N!==null;)$+=w.write(N.data),N=N.next;return this._readableState.buffer.clear(),$!==""&&this._readableState.buffer.push($),this._readableState.length=$.length,this};var V=1073741824;function z(b){return b>=V?b=V:(b--,b|=b>>>1,b|=b>>>2,b|=b>>>4,b|=b>>>8,b|=b>>>16,b++),b}function ee(b,w){return b<=0||w.length===0&&w.ended?0:w.objectMode?1:b!==b?w.flowing&&w.length?w.buffer.head.data.length:w.length:(b>w.highWaterMark&&(w.highWaterMark=z(b)),b<=w.length?b:w.ended?w.length:(w.needReadable=!0,0))}O.prototype.read=function(b){u("read",b),b=parseInt(b,10);var w=this._readableState,N=b;if(b!==0&&(w.emittedReadable=!1),b===0&&w.needReadable&&((w.highWaterMark!==0?w.length>=w.highWaterMark:w.length>0)||w.ended))return u("read: emitReadable",w.length,w.ended),w.length===0&&w.ended?H(this):ze(this),null;if(b=ee(b,w),b===0&&w.ended)return w.length===0&&H(this),null;var $=w.needReadable;u("need readable",$),(w.length===0||w.length-b<w.highWaterMark)&&($=!0,u("length less than watermark",$)),w.ended||w.reading?($=!1,u("reading or ended",$)):$&&(u("do read"),w.reading=!0,w.sync=!0,w.length===0&&(w.needReadable=!0),this._read(w.highWaterMark),w.sync=!1,w.reading||(b=ee(N,w)));var ye;return b>0?ye=T(b,w):ye=null,ye===null?(w.needReadable=w.length<=w.highWaterMark,b=0):(w.length-=b,w.awaitDrain=0),w.length===0&&(w.ended||(w.needReadable=!0),N!==b&&w.ended&&H(this)),ye!==null&&this.emit("data",ye),ye};function ve(b,w){if(u("onEofChunk"),!w.ended){if(w.decoder){var N=w.decoder.end();N&&N.length&&(w.buffer.push(N),w.length+=w.objectMode?1:N.length)}w.ended=!0,w.sync?ze(b):(w.needReadable=!1,w.emittedReadable||(w.emittedReadable=!0,rt(b)))}}function ze(b){var w=b._readableState;u("emitReadable",w.needReadable,w.emittedReadable),w.needReadable=!1,w.emittedReadable||(u("emitReadable",w.flowing),w.emittedReadable=!0,process.nextTick(rt,b))}function rt(b){var w=b._readableState;u("emitReadable_",w.destroyed,w.length,w.ended),!w.destroyed&&(w.length||w.ended)&&(b.emit("readable"),w.emittedReadable=!1),w.needReadable=!w.flowing&&!w.ended&&w.length<=w.highWaterMark,A(b)}function qe(b,w){w.readingMore||(w.readingMore=!0,process.nextTick(Ot,b,w))}function Ot(b,w){for(;!w.reading&&!w.ended&&(w.length<w.highWaterMark||w.flowing&&w.length===0);){var N=w.length;if(u("maybeReadMore read 0"),b.read(0),N===w.length)break}w.readingMore=!1}O.prototype._read=function(b){S(this,new B("_read()"))},O.prototype.pipe=function(b,w){var N=this,$=this._readableState;switch($.pipesCount){case 0:$.pipes=b;break;case 1:$.pipes=[$.pipes,b];break;default:$.pipes.push(b);break}$.pipesCount+=1,u("pipe count=%d opts=%j",$.pipesCount,w);var ye=(!w||w.end!==!1)&&b!==process.stdout&&b!==process.stderr,X=ye?Ct:Zt;$.endEmitted?process.nextTick(X):N.once("end",X),b.on("unpipe",ne);function ne(l,c){u("onunpipe"),l===N&&c&&c.hasUnpiped===!1&&(c.hasUnpiped=!0,wr())}function Ct(){u("onend"),b.end()}var br=pe(N);b.on("drain",br);var Gr=!1;function wr(){u("cleanup"),b.removeListener("close",Vr),b.removeListener("finish",Je),b.removeListener("drain",br),b.removeListener("error",Qt),b.removeListener("unpipe",ne),N.removeListener("end",Ct),N.removeListener("end",Zt),N.removeListener("data",Ke),Gr=!0,$.awaitDrain&&(!b._writableState||b._writableState.needDrain)&&br()}N.on("data",Ke);function Ke(l){u("ondata");var c=b.write(l);u("dest.write",c),c===!1&&(($.pipesCount===1&&$.pipes===b||$.pipesCount>1&&Y($.pipes,b)!==-1)&&!Gr&&(u("false write response, pause",$.awaitDrain),$.awaitDrain++),N.pause())}function Qt(l){u("onerror",l),Zt(),b.removeListener("error",Qt),t(b,"error")===0&&S(b,l)}F(b,"error",Qt);function Vr(){b.removeListener("finish",Je),Zt()}b.once("close",Vr);function Je(){u("onfinish"),b.removeListener("close",Vr),Zt()}b.once("finish",Je);function Zt(){u("unpipe"),N.unpipe(b)}return b.emit("pipe",N),$.flowing||(u("pipe resume"),N.resume()),b};function pe(b){return function(){var N=b._readableState;u("pipeOnDrain",N.awaitDrain),N.awaitDrain&&N.awaitDrain--,N.awaitDrain===0&&t(b,"data")&&(N.flowing=!0,A(b))}}O.prototype.unpipe=function(b){var w=this._readableState,N={hasUnpiped:!1};if(w.pipesCount===0)return this;if(w.pipesCount===1)return b&&b!==w.pipes?this:(b||(b=w.pipes),w.pipes=null,w.pipesCount=0,w.flowing=!1,b&&b.emit("unpipe",this,N),this);if(!b){var $=w.pipes,ye=w.pipesCount;w.pipes=null,w.pipesCount=0,w.flowing=!1;for(var X=0;X<ye;X++)$[X].emit("unpipe",this,{hasUnpiped:!1});return this}var ne=Y(w.pipes,b);return ne===-1?this:(w.pipes.splice(ne,1),w.pipesCount-=1,w.pipesCount===1&&(w.pipes=w.pipes[0]),b.emit("unpipe",this,N),this)},O.prototype.on=function(b,w){var N=r.prototype.on.call(this,b,w),$=this._readableState;return b==="data"?($.readableListening=this.listenerCount("readable")>0,$.flowing!==!1&&this.resume()):b==="readable"&&!$.endEmitted&&!$.readableListening&&($.readableListening=$.needReadable=!0,$.flowing=!1,$.emittedReadable=!1,u("on readable",$.length,$.reading),$.length?ze(this):$.reading||process.nextTick(We,this)),N},O.prototype.addListener=O.prototype.on,O.prototype.removeListener=function(b,w){var N=r.prototype.removeListener.call(this,b,w);return b==="readable"&&process.nextTick(Ee,this),N},O.prototype.removeAllListeners=function(b){var w=r.prototype.removeAllListeners.apply(this,arguments);return(b==="readable"||b===void 0)&&process.nextTick(Ee,this),w};function Ee(b){var w=b._readableState;w.readableListening=b.listenerCount("readable")>0,w.resumeScheduled&&!w.paused?w.flowing=!0:b.listenerCount("data")>0&&b.resume()}function We(b){u("readable nexttick read 0"),b.read(0)}O.prototype.resume=function(){var b=this._readableState;return b.flowing||(u("resume"),b.flowing=!b.readableListening,Rt(this,b)),b.paused=!1,this};function Rt(b,w){w.resumeScheduled||(w.resumeScheduled=!0,process.nextTick(yt,b,w))}function yt(b,w){u("resume",w.reading),w.reading||b.read(0),w.resumeScheduled=!1,b.emit("resume"),A(b),w.flowing&&!w.reading&&b.read(0)}O.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function A(b){var w=b._readableState;for(u("flow",w.flowing);w.flowing&&b.read()!==null;);}O.prototype.wrap=function(b){var w=this,N=this._readableState,$=!1;b.on("end",function(){if(u("wrapped end"),N.decoder&&!N.ended){var ne=N.decoder.end();ne&&ne.length&&w.push(ne)}w.push(null)}),b.on("data",function(ne){if(u("wrapped data"),N.decoder&&(ne=N.decoder.write(ne)),!(N.objectMode&&ne==null)&&!(!N.objectMode&&(!ne||!ne.length))){var Ct=w.push(ne);Ct||($=!0,b.pause())}});for(var ye in b)this[ye]===void 0&&typeof b[ye]=="function"&&(this[ye]=function(Ct){return function(){return b[Ct].apply(b,arguments)}}(ye));for(var X=0;X<E.length;X++)b.on(E[X],this.emit.bind(this,E[X]));return this._read=function(ne){u("wrapped _read",ne),$&&($=!1,b.resume())},this},typeof Symbol=="function"&&(O.prototype[Symbol.asyncIterator]=function(){return x===void 0&&(x=kd()),x(this)}),Object.defineProperty(O.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(O.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(O.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(w){this._readableState&&(this._readableState.flowing=w)}}),O._fromList=T,Object.defineProperty(O.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function T(b,w){if(w.length===0)return null;var N;return w.objectMode?N=w.buffer.shift():!b||b>=w.length?(w.decoder?N=w.buffer.join(""):w.buffer.length===1?N=w.buffer.first():N=w.buffer.concat(w.length),w.buffer.clear()):N=w.buffer.consume(b,w.decoder),N}function H(b){var w=b._readableState;u("endReadable",w.endEmitted),w.endEmitted||(w.ended=!0,process.nextTick(q,w,b))}function q(b,w){if(u("endReadableNT",b.endEmitted,b.length),!b.endEmitted&&b.length===0&&(b.endEmitted=!0,w.readable=!1,w.emit("end"),b.autoDestroy)){var N=w._writableState;(!N||N.autoDestroy&&N.finished)&&w.destroy()}}typeof Symbol=="function"&&(O.from=function(b,w){return g===void 0&&(g=Bd()),g(O,b,w)});function Y(b,w){for(var N=0,$=b.length;N<$;N++)if(b[N]===w)return N;return-1}return ns}var lc=Bt,gi=yr.codes,Id=gi.ERR_METHOD_NOT_IMPLEMENTED,Pd=gi.ERR_MULTIPLE_CALLBACK,Od=gi.ERR_TRANSFORM_ALREADY_TRANSFORMING,Rd=gi.ERR_TRANSFORM_WITH_LENGTH_0,_i=Fr();Oe(Bt,_i);function Cd(e,t){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new Pd);r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function Bt(e){if(!(this instanceof Bt))return new Bt(e);_i.call(this,e),this._transformState={afterTransform:Cd.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",Ud)}function Ud(){var e=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(t,r){Do(e,t,r)}):Do(this,null,null)}Bt.prototype.push=function(e,t){return this._transformState.needTransform=!1,_i.prototype.push.call(this,e,t)};Bt.prototype._transform=function(e,t,r){r(new Id("_transform()"))};Bt.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}};Bt.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};Bt.prototype._destroy=function(e,t){_i.prototype._destroy.call(this,e,function(r){t(r)})};function Do(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new Rd;if(e._transformState.transforming)throw new Od;return e.push(null)}var Ld=bn,dc=lc;Oe(bn,dc);function bn(e){if(!(this instanceof bn))return new bn(e);dc.call(this,e)}bn.prototype._transform=function(e,t,r){r(null,e)};var is;function Nd(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var hc=yr.codes,Hd=hc.ERR_MISSING_ARGS,Fd=hc.ERR_STREAM_DESTROYED;function $o(e){if(e)throw e}function Md(e){return e.setHeader&&typeof e.abort=="function"}function Dd(e,t,r,n){n=Nd(n);var i=!1;e.on("close",function(){i=!0}),is===void 0&&(is=qs),is(e,{readable:t,writable:r},function(o){if(o)return n(o);i=!0,n()});var s=!1;return function(o){if(!i&&!s){if(s=!0,Md(e))return e.abort();if(typeof e.destroy=="function")return e.destroy();n(o||new Fd("pipe"))}}}function jo(e){e()}function $d(e,t){return e.pipe(t)}function jd(e){return!e.length||typeof e[e.length-1]!="function"?$o:e.pop()}function Gd(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=jd(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new Hd("streams");var i,s=t.map(function(o,a){var u=a<t.length-1,d=a>0;return Dd(o,u,d,function(h){i||(i=h),h&&s.forEach(jo),!u&&(s.forEach(jo),n(i))})});return t.reduce($d)}var Vd=Gd;(function(e,t){t=e.exports=uc(),t.Stream=t,t.Readable=t,t.Writable=cc(),t.Duplex=Fr(),t.Transform=lc,t.PassThrough=Ld,t.finished=qs,t.pipeline=Vd})(_s,_s.exports);var pc=_s.exports,ni=Ve.Buffer,yc=pc.Transform,zd=Oe;function qd(e,t){if(!ni.isBuffer(e)&&typeof e!="string")throw new TypeError(t+" must be a string or a buffer")}function Yt(e){yc.call(this),this._block=ni.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}zd(Yt,yc);Yt.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(i){n=i}r(n)};Yt.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(r){t=r}e(t)};Yt.prototype.update=function(e,t){if(qd(e,"Data"),this._finalized)throw new Error("Digest already called");ni.isBuffer(e)||(e=ni.from(e,t));for(var r=this._block,n=0;this._blockOffset+e.length-n>=this._blockSize;){for(var i=this._blockOffset;i<this._blockSize;)r[i++]=e[n++];this._update(),this._blockOffset=0}for(;n<e.length;)r[this._blockOffset++]=e[n++];for(var s=0,o=e.length*8;o>0;++s)this._length[s]+=o,o=this._length[s]/4294967296|0,o>0&&(this._length[s]-=4294967296*o);return this};Yt.prototype._update=function(){throw new Error("_update is not implemented")};Yt.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();e!==void 0&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t};Yt.prototype._digest=function(){throw new Error("_digest is not implemented")};var Wd=Yt,Kd=Oe,mc=Wd,Yd=Ve.Buffer,Xd=new Array(16);function vi(){mc.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}Kd(vi,mc);vi.prototype._update=function(){for(var e=Xd,t=0;t<16;++t)e[t]=this._block.readInt32LE(t*4);var r=this._a,n=this._b,i=this._c,s=this._d;r=Re(r,n,i,s,e[0],3614090360,7),s=Re(s,r,n,i,e[1],3905402710,12),i=Re(i,s,r,n,e[2],606105819,17),n=Re(n,i,s,r,e[3],3250441966,22),r=Re(r,n,i,s,e[4],4118548399,7),s=Re(s,r,n,i,e[5],1200080426,12),i=Re(i,s,r,n,e[6],2821735955,17),n=Re(n,i,s,r,e[7],4249261313,22),r=Re(r,n,i,s,e[8],1770035416,7),s=Re(s,r,n,i,e[9],2336552879,12),i=Re(i,s,r,n,e[10],4294925233,17),n=Re(n,i,s,r,e[11],2304563134,22),r=Re(r,n,i,s,e[12],1804603682,7),s=Re(s,r,n,i,e[13],4254626195,12),i=Re(i,s,r,n,e[14],2792965006,17),n=Re(n,i,s,r,e[15],1236535329,22),r=Ce(r,n,i,s,e[1],4129170786,5),s=Ce(s,r,n,i,e[6],3225465664,9),i=Ce(i,s,r,n,e[11],643717713,14),n=Ce(n,i,s,r,e[0],3921069994,20),r=Ce(r,n,i,s,e[5],3593408605,5),s=Ce(s,r,n,i,e[10],38016083,9),i=Ce(i,s,r,n,e[15],3634488961,14),n=Ce(n,i,s,r,e[4],3889429448,20),r=Ce(r,n,i,s,e[9],568446438,5),s=Ce(s,r,n,i,e[14],3275163606,9),i=Ce(i,s,r,n,e[3],4107603335,14),n=Ce(n,i,s,r,e[8],1163531501,20),r=Ce(r,n,i,s,e[13],2850285829,5),s=Ce(s,r,n,i,e[2],4243563512,9),i=Ce(i,s,r,n,e[7],1735328473,14),n=Ce(n,i,s,r,e[12],2368359562,20),r=Ue(r,n,i,s,e[5],4294588738,4),s=Ue(s,r,n,i,e[8],2272392833,11),i=Ue(i,s,r,n,e[11],1839030562,16),n=Ue(n,i,s,r,e[14],4259657740,23),r=Ue(r,n,i,s,e[1],2763975236,4),s=Ue(s,r,n,i,e[4],1272893353,11),i=Ue(i,s,r,n,e[7],4139469664,16),n=Ue(n,i,s,r,e[10],3200236656,23),r=Ue(r,n,i,s,e[13],681279174,4),s=Ue(s,r,n,i,e[0],3936430074,11),i=Ue(i,s,r,n,e[3],3572445317,16),n=Ue(n,i,s,r,e[6],76029189,23),r=Ue(r,n,i,s,e[9],3654602809,4),s=Ue(s,r,n,i,e[12],3873151461,11),i=Ue(i,s,r,n,e[15],530742520,16),n=Ue(n,i,s,r,e[2],3299628645,23),r=Le(r,n,i,s,e[0],4096336452,6),s=Le(s,r,n,i,e[7],1126891415,10),i=Le(i,s,r,n,e[14],2878612391,15),n=Le(n,i,s,r,e[5],4237533241,21),r=Le(r,n,i,s,e[12],1700485571,6),s=Le(s,r,n,i,e[3],2399980690,10),i=Le(i,s,r,n,e[10],4293915773,15),n=Le(n,i,s,r,e[1],2240044497,21),r=Le(r,n,i,s,e[8],1873313359,6),s=Le(s,r,n,i,e[15],4264355552,10),i=Le(i,s,r,n,e[6],2734768916,15),n=Le(n,i,s,r,e[13],1309151649,21),r=Le(r,n,i,s,e[4],4149444226,6),s=Le(s,r,n,i,e[11],3174756917,10),i=Le(i,s,r,n,e[2],718787259,15),n=Le(n,i,s,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+s|0};vi.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=Yd.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e};function Ei(e,t){return e<<t|e>>>32-t}function Re(e,t,r,n,i,s,o){return Ei(e+(t&r|~t&n)+i+s|0,o)+t|0}function Ce(e,t,r,n,i,s,o){return Ei(e+(t&n|r&~n)+i+s|0,o)+t|0}function Ue(e,t,r,n,i,s,o){return Ei(e+(t^r^n)+i+s|0,o)+t|0}function Le(e,t,r,n,i,s,o){return Ei(e+(r^(t|~n))+i+s|0,o)+t|0}var Jd=vi,ii=Ve.Buffer,bc=pc.Transform,Qd=Oe;function Zd(e,t){if(!ii.isBuffer(e)&&typeof e!="string")throw new TypeError(t+" must be a string or a buffer")}function Xt(e){bc.call(this),this._block=ii.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}Qd(Xt,bc);Xt.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(i){n=i}r(n)};Xt.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(r){t=r}e(t)};Xt.prototype.update=function(e,t){if(Zd(e,"Data"),this._finalized)throw new Error("Digest already called");ii.isBuffer(e)||(e=ii.from(e,t));for(var r=this._block,n=0;this._blockOffset+e.length-n>=this._blockSize;){for(var i=this._blockOffset;i<this._blockSize;)r[i++]=e[n++];this._update(),this._blockOffset=0}for(;n<e.length;)r[this._blockOffset++]=e[n++];for(var s=0,o=e.length*8;o>0;++s)this._length[s]+=o,o=this._length[s]/4294967296|0,o>0&&(this._length[s]-=4294967296*o);return this};Xt.prototype._update=function(){throw new Error("_update is not implemented")};Xt.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();e!==void 0&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t};Xt.prototype._digest=function(){throw new Error("_digest is not implemented")};var eh=Xt,ss=It.Buffer,th=Oe,wc=eh,rh=new Array(16),Xr=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],Jr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],Qr=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],Zr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],en=[0,1518500249,1859775393,2400959708,2840853838],tn=[1352829926,1548603684,1836072691,2053994217,0];function xi(){wc.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}th(xi,wc);xi.prototype._update=function(){for(var e=rh,t=0;t<16;++t)e[t]=this._block.readInt32LE(t*4);for(var r=this._a|0,n=this._b|0,i=this._c|0,s=this._d|0,o=this._e|0,a=this._a|0,u=this._b|0,d=this._c|0,h=this._d|0,y=this._e|0,v=0;v<80;v+=1){var p,I;v<16?(p=Go(r,n,i,s,o,e[Xr[v]],en[0],Qr[v]),I=Wo(a,u,d,h,y,e[Jr[v]],tn[0],Zr[v])):v<32?(p=Vo(r,n,i,s,o,e[Xr[v]],en[1],Qr[v]),I=qo(a,u,d,h,y,e[Jr[v]],tn[1],Zr[v])):v<48?(p=zo(r,n,i,s,o,e[Xr[v]],en[2],Qr[v]),I=zo(a,u,d,h,y,e[Jr[v]],tn[2],Zr[v])):v<64?(p=qo(r,n,i,s,o,e[Xr[v]],en[3],Qr[v]),I=Vo(a,u,d,h,y,e[Jr[v]],tn[3],Zr[v])):(p=Wo(r,n,i,s,o,e[Xr[v]],en[4],Qr[v]),I=Go(a,u,d,h,y,e[Jr[v]],tn[4],Zr[v])),r=o,o=s,s=cr(i,10),i=n,n=p,a=y,y=h,h=cr(d,10),d=u,u=I}var k=this._b+i+h|0;this._b=this._c+s+y|0,this._c=this._d+o+a|0,this._d=this._e+r+u|0,this._e=this._a+n+d|0,this._a=k};xi.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=ss.alloc?ss.alloc(20):new ss(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e};function cr(e,t){return e<<t|e>>>32-t}function Go(e,t,r,n,i,s,o,a){return cr(e+(t^r^n)+s+o|0,a)+i|0}function Vo(e,t,r,n,i,s,o,a){return cr(e+(t&r|~t&n)+s+o|0,a)+i|0}function zo(e,t,r,n,i,s,o,a){return cr(e+((t|~r)^n)+s+o|0,a)+i|0}function qo(e,t,r,n,i,s,o,a){return cr(e+(t&n|r&~n)+s+o|0,a)+i|0}function Wo(e,t,r,n,i,s,o,a){return cr(e+(t^(r|~n))+s+o|0,a)+i|0}var nh=xi,gc={exports:{}},_c=Ve.Buffer;function Si(e,t){this._block=_c.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}Si.prototype.update=function(e,t){typeof e=="string"&&(t=t||"utf8",e=_c.from(e,t));for(var r=this._block,n=this._blockSize,i=e.length,s=this._len,o=0;o<i;){for(var a=s%n,u=Math.min(i-o,n-a),d=0;d<u;d++)r[a+d]=e[o+d];s+=u,o+=u,s%n===0&&this._update(r)}return this._len+=i,this};Si.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=this._len*8;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(r&4294967295)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var s=this._hash();return e?s.toString(e):s};Si.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var Dr=Si,ih=Oe,vc=Dr,sh=Ve.Buffer,oh=[1518500249,1859775393,-1894007588,-899497514],ah=new Array(80);function Sn(){this.init(),this._w=ah,vc.call(this,64,56)}ih(Sn,vc);Sn.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function ch(e){return e<<5|e>>>27}function fh(e){return e<<30|e>>>2}function uh(e,t,r,n){return e===0?t&r|~t&n:e===2?t&r|t&n|r&n:t^r^n}Sn.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,s=this._d|0,o=this._e|0,a=0;a<16;++a)t[a]=e.readInt32BE(a*4);for(;a<80;++a)t[a]=t[a-3]^t[a-8]^t[a-14]^t[a-16];for(var u=0;u<80;++u){var d=~~(u/20),h=ch(r)+uh(d,n,i,s)+o+t[u]+oh[d]|0;o=s,s=i,i=fh(n),n=r,r=h}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=o+this._e|0};Sn.prototype._hash=function(){var e=sh.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};var lh=Sn,dh=Oe,Ec=Dr,hh=Ve.Buffer,ph=[1518500249,1859775393,-1894007588,-899497514],yh=new Array(80);function Tn(){this.init(),this._w=yh,Ec.call(this,64,56)}dh(Tn,Ec);Tn.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function mh(e){return e<<1|e>>>31}function bh(e){return e<<5|e>>>27}function wh(e){return e<<30|e>>>2}function gh(e,t,r,n){return e===0?t&r|~t&n:e===2?t&r|t&n|r&n:t^r^n}Tn.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,s=this._d|0,o=this._e|0,a=0;a<16;++a)t[a]=e.readInt32BE(a*4);for(;a<80;++a)t[a]=mh(t[a-3]^t[a-8]^t[a-14]^t[a-16]);for(var u=0;u<80;++u){var d=~~(u/20),h=bh(r)+gh(d,n,i,s)+o+t[u]+ph[d]|0;o=s,s=i,i=wh(n),n=r,r=h}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=o+this._e|0};Tn.prototype._hash=function(){var e=hh.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};var _h=Tn,vh=Oe,xc=Dr,Eh=Ve.Buffer,xh=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Sh=new Array(64);function An(){this.init(),this._w=Sh,xc.call(this,64,56)}vh(An,xc);An.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function Th(e,t,r){return r^e&(t^r)}function Ah(e,t,r){return e&t|r&(e|t)}function kh(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function Bh(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function Ih(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}function Ph(e){return(e>>>17|e<<15)^(e>>>19|e<<13)^e>>>10}An.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,s=this._d|0,o=this._e|0,a=this._f|0,u=this._g|0,d=this._h|0,h=0;h<16;++h)t[h]=e.readInt32BE(h*4);for(;h<64;++h)t[h]=Ph(t[h-2])+t[h-7]+Ih(t[h-15])+t[h-16]|0;for(var y=0;y<64;++y){var v=d+Bh(o)+Th(o,a,u)+xh[y]+t[y]|0,p=kh(r)+Ah(r,n,i)|0;d=u,u=a,a=o,o=s+v|0,s=i,i=n,n=r,r=v+p|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=o+this._e|0,this._f=a+this._f|0,this._g=u+this._g|0,this._h=d+this._h|0};An.prototype._hash=function(){var e=Eh.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e};var Sc=An,Oh=Oe,Rh=Sc,Ch=Dr,Uh=Ve.Buffer,Lh=new Array(64);function Ti(){this.init(),this._w=Lh,Ch.call(this,64,56)}Oh(Ti,Rh);Ti.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this};Ti.prototype._hash=function(){var e=Uh.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e};var Nh=Ti,Hh=Oe,Tc=Dr,Fh=Ve.Buffer,Ko=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],Mh=new Array(160);function kn(){this.init(),this._w=Mh,Tc.call(this,128,112)}Hh(kn,Tc);kn.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function Yo(e,t,r){return r^e&(t^r)}function Xo(e,t,r){return e&t|r&(e|t)}function Jo(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function Qo(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function Dh(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function $h(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function jh(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function Gh(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function ke(e,t){return e>>>0<t>>>0?1:0}kn.prototype._update=function(e){for(var t=this._w,r=this._ah|0,n=this._bh|0,i=this._ch|0,s=this._dh|0,o=this._eh|0,a=this._fh|0,u=this._gh|0,d=this._hh|0,h=this._al|0,y=this._bl|0,v=this._cl|0,p=this._dl|0,I=this._el|0,k=this._fl|0,B=this._gl|0,R=this._hl|0,U=0;U<32;U+=2)t[U]=e.readInt32BE(U*4),t[U+1]=e.readInt32BE(U*4+4);for(;U<160;U+=2){var x=t[U-30],g=t[U-15*2+1],S=Dh(x,g),E=$h(g,x);x=t[U-2*2],g=t[U-2*2+1];var F=jh(x,g),D=Gh(g,x),O=t[U-7*2],K=t[U-7*2+1],C=t[U-16*2],G=t[U-16*2+1],V=E+K|0,z=S+O+ke(V,E)|0;V=V+D|0,z=z+F+ke(V,D)|0,V=V+G|0,z=z+C+ke(V,G)|0,t[U]=z,t[U+1]=V}for(var ee=0;ee<160;ee+=2){z=t[ee],V=t[ee+1];var ve=Xo(r,n,i),ze=Xo(h,y,v),rt=Jo(r,h),qe=Jo(h,r),Ot=Qo(o,I),pe=Qo(I,o),Ee=Ko[ee],We=Ko[ee+1],Rt=Yo(o,a,u),yt=Yo(I,k,B),A=R+pe|0,T=d+Ot+ke(A,R)|0;A=A+yt|0,T=T+Rt+ke(A,yt)|0,A=A+We|0,T=T+Ee+ke(A,We)|0,A=A+V|0,T=T+z+ke(A,V)|0;var H=qe+ze|0,q=rt+ve+ke(H,qe)|0;d=u,R=B,u=a,B=k,a=o,k=I,I=p+A|0,o=s+T+ke(I,p)|0,s=i,p=v,i=n,v=y,n=r,y=h,h=A+H|0,r=T+q+ke(h,A)|0}this._al=this._al+h|0,this._bl=this._bl+y|0,this._cl=this._cl+v|0,this._dl=this._dl+p|0,this._el=this._el+I|0,this._fl=this._fl+k|0,this._gl=this._gl+B|0,this._hl=this._hl+R|0,this._ah=this._ah+r+ke(this._al,h)|0,this._bh=this._bh+n+ke(this._bl,y)|0,this._ch=this._ch+i+ke(this._cl,v)|0,this._dh=this._dh+s+ke(this._dl,p)|0,this._eh=this._eh+o+ke(this._el,I)|0,this._fh=this._fh+a+ke(this._fl,k)|0,this._gh=this._gh+u+ke(this._gl,B)|0,this._hh=this._hh+d+ke(this._hl,R)|0};kn.prototype._hash=function(){var e=Fh.allocUnsafe(64);function t(r,n,i){e.writeInt32BE(r,i),e.writeInt32BE(n,i+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e};var Ac=kn,Vh=Oe,zh=Ac,qh=Dr,Wh=Ve.Buffer,Kh=new Array(160);function Ai(){this.init(),this._w=Kh,qh.call(this,128,112)}Vh(Ai,zh);Ai.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this};Ai.prototype._hash=function(){var e=Wh.allocUnsafe(48);function t(r,n,i){e.writeInt32BE(r,i),e.writeInt32BE(n,i+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e};var Yh=Ai,mr=gc.exports=function(t){t=t.toLowerCase();var r=mr[t];if(!r)throw new Error(t+" is not supported (we accept pull requests)");return new r};mr.sha=lh;mr.sha1=_h;mr.sha224=Nh;mr.sha256=Sc;mr.sha384=Yh;mr.sha512=Ac;var Xh=gc.exports,dt=Ve.Buffer,kc=Vs.Transform,Jh=ri.StringDecoder,Qh=Oe;function st(e){kc.call(this),this.hashMode=typeof e=="string",this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}Qh(st,kc);var Zh=typeof Uint8Array<"u",e0=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&ArrayBuffer.isView&&(dt.prototype instanceof Uint8Array||dt.TYPED_ARRAY_SUPPORT);function t0(e,t){if(e instanceof dt)return e;if(typeof e=="string")return dt.from(e,t);if(e0&&ArrayBuffer.isView(e)){if(e.byteLength===0)return dt.alloc(0);var r=dt.from(e.buffer,e.byteOffset,e.byteLength);if(r.byteLength===e.byteLength)return r}if(Zh&&e instanceof Uint8Array||dt.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e))return dt.from(e);throw new TypeError('The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.')}st.prototype.update=function(e,t,r){var n=t0(e,t),i=this._update(n);return this.hashMode?this:(r&&(i=this._toString(i,r)),i)};st.prototype.setAutoPadding=function(){};st.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")};st.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")};st.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")};st.prototype._transform=function(e,t,r){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(i){n=i}finally{r(n)}};st.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(r){t=r}e(t)};st.prototype._finalOrDigest=function(e){var t=this.__final()||dt.alloc(0);return e&&(t=this._toString(t,e,!0)),t};st.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new Jh(t),this._encoding=t),this._encoding!==t)throw new Error("can’t switch encodings");var n=this._decoder.write(e);return r&&(n+=this._decoder.end()),n};var r0=st,n0=Oe,i0=Jd,s0=nh,o0=Xh,Bc=r0;function ki(e){Bc.call(this,"digest"),this._hash=e}n0(ki,Bc);ki.prototype._update=function(e){this._hash.update(e)};ki.prototype._final=function(){return this._hash.digest()};var a0=function(t){return t=t.toLowerCase(),t==="md5"?new i0:t==="rmd160"||t==="ripemd160"?new s0:new ki(o0(t))},Mn=Ve.Buffer;function c0(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var o=e.length,a=e.charAt(0),u=Math.log(o)/Math.log(256),d=Math.log(256)/Math.log(o);function h(p){if((Array.isArray(p)||p instanceof Uint8Array)&&(p=Mn.from(p)),!Mn.isBuffer(p))throw new TypeError("Expected Buffer");if(p.length===0)return"";for(var I=0,k=0,B=0,R=p.length;B!==R&&p[B]===0;)B++,I++;for(var U=(R-B)*d+1>>>0,x=new Uint8Array(U);B!==R;){for(var g=p[B],S=0,E=U-1;(g!==0||S<k)&&E!==-1;E--,S++)g+=256*x[E]>>>0,x[E]=g%o>>>0,g=g/o>>>0;if(g!==0)throw new Error("Non-zero carry");k=S,B++}for(var F=U-k;F!==U&&x[F]===0;)F++;for(var D=a.repeat(I);F<U;++F)D+=e.charAt(x[F]);return D}function y(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return Mn.alloc(0);for(var I=0,k=0,B=0;p[I]===a;)k++,I++;for(var R=(p.length-I)*u+1>>>0,U=new Uint8Array(R);I<p.length;){var x=p.charCodeAt(I);if(x>255)return;var g=t[x];if(g===255)return;for(var S=0,E=R-1;(g!==0||S<B)&&E!==-1;E--,S++)g+=o*U[E]>>>0,U[E]=g%256>>>0,g=g/256>>>0;if(g!==0)throw new Error("Non-zero carry");B=S,I++}for(var F=R-B;F!==R&&U[F]===0;)F++;var D=Mn.allocUnsafe(k+(R-F));D.fill(0,0,k);for(var O=k;F!==R;)D[O++]=U[F++];return D}function v(p){var I=y(p);if(I)return I;throw new Error("Non-base"+o+" character")}return{encode:h,decodeUnsafe:y,decode:v}}var f0=c0,u0=f0,l0="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",d0=u0(l0),os=d0,h0=Ve.Buffer,p0=function(e){function t(s){var o=e(s);return os.encode(h0.concat([s,o],s.length+4))}function r(s){var o=s.slice(0,-4),a=s.slice(-4),u=e(o);if(!(a[0]^u[0]|a[1]^u[1]|a[2]^u[2]|a[3]^u[3]))return o}function n(s){var o=os.decodeUnsafe(s);if(o)return r(o)}function i(s){var o=os.decode(s),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:i,decodeUnsafe:n}},Zo=a0,y0=p0;function m0(e){var t=Zo("sha256").update(e).digest();return Zo("sha256").update(t).digest()}var b0=y0(m0),Es=b0;function Ic(e,t){if(t!==void 0&&e[0]!==t)throw new Error("Invalid network version");if(e.length===33)return{version:e[0],privateKey:e.slice(1,33),compressed:!1};if(e.length!==34)throw new Error("Invalid WIF length");if(e[33]!==1)throw new Error("Invalid compression flag");return{version:e[0],privateKey:e.slice(1,33),compressed:!0}}function xs(e,t,r){var n=new Buffer(r?34:33);return n.writeUInt8(e,0),t.copy(n,1),r&&(n[33]=1),n}function w0(e,t){return Ic(Es.decode(e),t)}function g0(e,t,r){return typeof e=="number"?Es.encode(xs(e,t,r)):Es.encode(xs(e.version,e.privateKey,e.compressed))}var _0={decode:w0,decodeRaw:Ic,encode:g0,encodeRaw:xs},Bi={};Object.defineProperty(Bi,"__esModule",{value:!0});Bi.testEcc=void 0;const W=e=>Buffer.from(e,"hex");function v0(e){ue(e.isPoint(W("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ue(!e.isPoint(W("030000000000000000000000000000000000000000000000000000000000000005"))),ue(e.isPrivate(W("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ue(e.isPrivate(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))),ue(!e.isPrivate(W("0000000000000000000000000000000000000000000000000000000000000000"))),ue(!e.isPrivate(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"))),ue(!e.isPrivate(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364142"))),ue(Buffer.from(e.privateAdd(W("0000000000000000000000000000000000000000000000000000000000000001"),W("0000000000000000000000000000000000000000000000000000000000000000"))).equals(W("0000000000000000000000000000000000000000000000000000000000000001"))),ue(e.privateAdd(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413e"),W("0000000000000000000000000000000000000000000000000000000000000003"))===null),ue(Buffer.from(e.privateAdd(W("e211078564db65c3ce7704f08262b1f38f1ef412ad15b5ac2d76657a63b2c500"),W("b51fbb69051255d1becbd683de5848242a89c229348dd72896a87ada94ae8665"))).equals(W("9730c2ee69edbb958d42db7460bafa18fef9d955325aec99044c81c8282b0a24"))),ue(Buffer.from(e.privateNegate(W("0000000000000000000000000000000000000000000000000000000000000001"))).equals(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))),ue(Buffer.from(e.privateNegate(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413e"))).equals(W("0000000000000000000000000000000000000000000000000000000000000003"))),ue(Buffer.from(e.privateNegate(W("b1121e4088a66a28f5b6b0f5844943ecd9f610196d7bb83b25214b60452c09af"))).equals(W("4eede1bf775995d70a494f0a7bb6bc11e0b8cccd41cce8009ab1132c8b0a3792"))),ue(Buffer.from(e.pointCompress(W("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),!0)).equals(W("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ue(Buffer.from(e.pointCompress(W("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),!1)).equals(W("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"))),ue(Buffer.from(e.pointCompress(W("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),!0)).equals(W("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ue(Buffer.from(e.pointCompress(W("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),!1)).equals(W("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"))),ue(Buffer.from(e.pointFromScalar(W("b1121e4088a66a28f5b6b0f5844943ecd9f610196d7bb83b25214b60452c09af"))).equals(W("02b07ba9dca9523b7ef4bd97703d43d20399eb698e194704791a25ce77a400df99"))),ue(e.xOnlyPointAddTweak(W("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))===null);let t=e.xOnlyPointAddTweak(W("1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b"),W("a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac"));ue(Buffer.from(t.xOnlyPubkey).equals(W("e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"))&&t.parity===1),t=e.xOnlyPointAddTweak(W("2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991"),W("823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47")),ue(Buffer.from(t.xOnlyPubkey).equals(W("9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"))&&t.parity===0),ue(Buffer.from(e.sign(W("5e9f0a0d593efdcf78ac923bc3313e4e7d408d574354ee2b3288c0da9fbba6ed"),W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))).equals(W("54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5"))),ue(e.verify(W("5e9f0a0d593efdcf78ac923bc3313e4e7d408d574354ee2b3288c0da9fbba6ed"),W("0379be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),W("54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5"))),e.signSchnorr&&ue(Buffer.from(e.signSchnorr(W("7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c"),W("c90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b14e5c9"),W("c87aa53824b4d7ae2eb035a2b5bbbccc080e76cdc6d1692c4b0b62d798e6d906"))).equals(W("5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7"))),e.verifySchnorr&&ue(e.verifySchnorr(W("7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c"),W("dd308afec5777e13121fa72b9cc1b7cc0139715309b086c960e18fd969774eb8"),W("5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7")))}Bi.testEcc=v0;function ue(e){if(!e)throw new Error("ecc library invalid")}Object.defineProperty(Nr,"__esModule",{value:!0});Nr.ECPairFactory=Nr.networks=void 0;const Ss=Hr;Nr.networks=Ss;const je=Ka,E0=Gl,ea=_0,x0=Bi,as=je.typeforce.maybe(je.typeforce.compile({compressed:je.maybe(je.Boolean),network:je.maybe(je.Network)})),S0=e=>e.length===32?e:e.slice(1,33);function T0(e){(0,x0.testEcc)(e);function t(a){return e.isPoint(a)}function r(a,u){if(je.typeforce(je.Buffer256bit,a),!e.isPrivate(a))throw new TypeError("Private key not in range [1, n)");return je.typeforce(as,u),new o(a,void 0,u)}function n(a,u){return je.typeforce(e.isPoint,a),je.typeforce(as,u),new o(void 0,a,u)}function i(a,u){const d=ea.decode(a),h=d.version;if(je.Array(u)){if(u=u.filter(y=>h===y.wif).pop(),!u)throw new Error("Unknown network version")}else if(u=u||Ss.bitcoin,h!==u.wif)throw new Error("Invalid network version");return r(d.privateKey,{compressed:d.compressed,network:u})}function s(a){je.typeforce(as,a),a===void 0&&(a={});const u=a.rng||E0;let d;do d=u(32),je.typeforce(je.Buffer256bit,d);while(!e.isPrivate(d));return r(d,a)}class o{constructor(u,d,h){gr(this,"__D");gr(this,"__Q");gr(this,"compressed");gr(this,"network");gr(this,"lowR");this.__D=u,this.__Q=d,this.lowR=!1,h===void 0&&(h={}),this.compressed=h.compressed===void 0?!0:h.compressed,this.network=h.network||Ss.bitcoin,d!==void 0&&(this.__Q=Buffer.from(e.pointCompress(d,this.compressed)))}get privateKey(){return this.__D}get publicKey(){if(!this.__Q){const u=e.pointFromScalar(this.__D,this.compressed);this.__Q=Buffer.from(u)}return this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return ea.encode(this.network.wif,this.__D,this.compressed)}tweak(u){return this.privateKey?this.tweakFromPrivateKey(u):this.tweakFromPublicKey(u)}sign(u,d){if(!this.__D)throw new Error("Missing private key");if(d===void 0&&(d=this.lowR),d===!1)return Buffer.from(e.sign(u,this.__D));{let h=e.sign(u,this.__D);const y=Buffer.alloc(32,0);let v=0;for(;h[0]>127;)v++,y.writeUIntLE(v,0,6),h=e.sign(u,this.__D,y);return Buffer.from(h)}}signSchnorr(u){if(!this.privateKey)throw new Error("Missing private key");if(!e.signSchnorr)throw new Error("signSchnorr not supported by ecc library");return Buffer.from(e.signSchnorr(u,this.privateKey))}verify(u,d){return e.verify(u,this.publicKey,d)}verifySchnorr(u,d){if(!e.verifySchnorr)throw new Error("verifySchnorr not supported by ecc library");return e.verifySchnorr(u,this.publicKey.subarray(1,33),d)}tweakFromPublicKey(u){const d=S0(this.publicKey),h=e.xOnlyPointAddTweak(d,u);if(!h||h.xOnlyPubkey===null)throw new Error("Cannot tweak public key!");const y=Buffer.from([h.parity===0?2:3]);return n(Buffer.concat([y,h.xOnlyPubkey]),{network:this.network,compressed:this.compressed})}tweakFromPrivateKey(u){const h=this.publicKey[0]===3||this.publicKey[0]===4&&(this.publicKey[64]&1)===1?e.privateNegate(this.privateKey):this.privateKey,y=e.privateAdd(h,u);if(!y)throw new Error("Invalid tweaked private key!");return r(Buffer.from(y),{network:this.network,compressed:this.compressed})}}return{isPoint:t,fromPrivateKey:r,fromPublicKey:n,fromWIF:i,makeRandom:s}}Nr.ECPairFactory=T0;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.networks=e.ECPairFactory=e.default=void 0;var t=Nr;Object.defineProperty(e,"default",{enumerable:!0,get:function(){return t.ECPairFactory}}),Object.defineProperty(e,"ECPairFactory",{enumerable:!0,get:function(){return t.ECPairFactory}}),Object.defineProperty(e,"networks",{enumerable:!0,get:function(){return t.networks}})})(Wa);const A0=Of(Wa);class wn extends j.EventBroker{get isInitialized(){return!!this.digestKey}constructor(t,r){super(),this.digestKey=t,this.walletClient=r}static fromDigestKey(t){return new wn(rr(t))}static fromWalletClient(t){return new wn(void 0,t)}async initialize(){if(this.digestKey)return re("Already initialized");const t=await this.deriveDigestKeyFromWalletClient();return t.error?M(t.error):(this.emit("initialized",!0),re("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return M("No walletClient found");if(!this.walletClient.account)return M("No account found");try{const t=await this.walletClient.signTypedData({account:this.walletClient.account,types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"}],Data:[{name:"Message",type:"string"},{name:"Version",type:"string"},{name:"Nonce",type:"uint256"}]},domain:{name:"GARDEN FINANCE",version:"1"},primaryType:"Data",message:{Message:"Initialize your account",Version:"1.0.2",Nonce:1n}});return this.digestKey=rr(it.sha256(t)),this.emit("initialized",!0),re(this.digestKey)}catch(t){return M("Failed to initialize: "+t)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return M("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const t=await this.deriveDigestKeyFromWalletClient();if(t.error)return M(t.error)}return this.digestKey?re(this.digestKey):M("No private key found")}async generateSecret(t){const r=await this.signMessage(t);if(r.error)return M(r.error);const n=it.sha256(j.with0x(r.val)),i=it.sha256(n);return re({secret:n,secretHash:i})}async signMessage(t){if(!this.digestKey){const d=await this.getDigestKey();if(d.error)return M(d.error);this.digestKey=d.val}const r=A0(sr),n="Garden.fi"+t.toString(),i=Buffer.from(n,"utf8"),s=it.sha256(i),o=Buffer.from(rr(this.digestKey),"hex");if(o.length!==32)return M("Invalid private key length. Expected 32 bytes.");const u=r.fromPrivateKey(o).sign(Buffer.from(rr(s),"hex"));return re(u.toString("hex"))}}const ta=[{inputs:[{internalType:"address",name:"token_",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"initiateWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],internalType:"struct HTLC.InitWithSig[]",name:"inits",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],internalType:"struct HTLC.Redeem[]",name:"redeems",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],internalType:"struct HTLC.Refund[]",name:"refunds",type:"tuple[]"}],name:"multicall",outputs:[{internalType:"bool[]",name:"results",type:"bool[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address",name:"initiator",type:"address"},{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"contract IERC20",name:"",type:"address"}],stateMutability:"view",type:"function"}];function pt(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const Pc="2.26.3";let rn={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${Pc}`};class he extends Error{constructor(t,r={}){var a;const n=(()=>{var u;return r.cause instanceof he?r.cause.details:(u=r.cause)!=null&&u.message?r.cause.message:r.details})(),i=r.cause instanceof he&&r.cause.docsPath||r.docsPath,s=(a=rn.getDocsUrl)==null?void 0:a.call(rn,{...r,docsPath:i}),o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...rn.version?[`Version: ${rn.version}`]:[]].join(`
|
|
32
|
-
`);super(o,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=Pc}walk(t){return Oc(this,t)}}function Oc(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?Oc(e.cause,t):t?null:e}class k0 extends he{constructor({max:t,min:r,signed:n,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class B0 extends he{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}function Bn(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function Mr(e){return Bn(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function si(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let i=0;i<r.length-1&&r[t==="left"?i:r.length-i-1].toString()==="0";i++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}class I0 extends he{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}}class Rc extends he{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function $r(e,{dir:t,size:r=32}={}){return typeof e=="string"?P0(e,{dir:t,size:r}):O0(e,{dir:t,size:r})}function P0(e,{dir:t,size:r=32}={}){if(r===null)return e;const n=e.replace("0x","");if(n.length>r*2)throw new Rc({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function O0(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new Rc({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const s=t==="right";n[s?i:r-i-1]=e[s?i:e.length-i-1]}return n}const R0=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Q(e,t={}){return typeof e=="number"||typeof e=="bigint"?Cc(e,t):typeof e=="string"?L0(e,t):typeof e=="boolean"?C0(e,t):Jt(e,t)}function C0(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?(jr(r,{size:t.size}),$r(r,{size:t.size})):r}function Jt(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=R0[e[i]];const n=`0x${r}`;return typeof t.size=="number"?(jr(n,{size:t.size}),$r(n,{dir:"right",size:t.size})):n}function Cc(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const u=typeof e=="bigint"?"n":"";throw new k0({max:s?`${s}${u}`:void 0,min:`${o}${u}`,signed:r,size:n,value:`${e}${u}`})}const a=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?$r(a,{size:n}):a}const U0=new TextEncoder;function L0(e,t={}){const r=U0.encode(e);return Jt(r,t)}const N0=new TextEncoder;function Uc(e,t={}){return typeof e=="number"||typeof e=="bigint"?F0(e,t):typeof e=="boolean"?H0(e,t):Bn(e)?fr(e,t):Lc(e,t)}function H0(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?(jr(r,{size:t.size}),$r(r,{size:t.size})):r}const _t={zero:48,nine:57,A:65,F:70,a:97,f:102};function ra(e){if(e>=_t.zero&&e<=_t.nine)return e-_t.zero;if(e>=_t.A&&e<=_t.F)return e-(_t.A-10);if(e>=_t.a&&e<=_t.f)return e-(_t.a-10)}function fr(e,t={}){let r=e;t.size&&(jr(r,{size:t.size}),r=$r(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const u=ra(n.charCodeAt(a++)),d=ra(n.charCodeAt(a++));if(u===void 0||d===void 0)throw new he(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);s[o]=u*16+d}return s}function F0(e,t){const r=Cc(e,t);return fr(r)}function Lc(e,t={}){const r=N0.encode(e);return typeof t.size=="number"?(jr(r,{size:t.size}),$r(r,{dir:"right",size:t.size})):r}function jr(e,{size:t}){if(Mr(e)>t)throw new B0({givenSize:Mr(e),maxSize:t})}function kr(e,t={}){const{signed:r}=t;t.size&&jr(e,{size:t.size});const n=BigInt(e);if(!r)return n;const i=(e.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return n<=s?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function oi(e,t={}){return Number(kr(e,t))}function Ws(e,t){return({exclude:r,format:n})=>({exclude:r,format:i=>{const s=t(i);if(r)for(const o of r)delete s[o];return{...s,...n(i)}},type:e})}const Nc={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Ks(e){const t={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?oi(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?oi(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?Nc[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(t.authorizationList=D0(e.authorizationList)),t.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof t.v=="bigint"){if(t.v===0n||t.v===27n)return 0;if(t.v===1n||t.v===28n)return 1;if(t.v>=35n)return t.v%2n===0n?1:0}})(),t.type==="legacy"&&(delete t.accessList,delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas,delete t.yParity),t.type==="eip2930"&&(delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas),t.type==="eip1559"&&delete t.maxFeePerBlobGas,t}const M0=Ws("transaction",Ks);function D0(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function $0(e){const t=(e.transactions??[]).map(r=>typeof r=="string"?r:Ks(r));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:t,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const j0=Ws("block",$0);function G0(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}const V0={"0x0":"reverted","0x1":"success"};function z0(e){const t={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(r=>G0(r)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?oi(e.transactionIndex):null,status:e.status?V0[e.status]:null,type:e.type?Nc[e.type]||e.type:null};return e.blobGasPrice&&(t.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(t.blobGasUsed=BigInt(e.blobGasUsed)),t}const q0=Ws("transactionReceipt",z0),Ys=2n**256n-1n;function In(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}class na extends he{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class W0 extends he{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}}class K0 extends he{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}const Y0={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new K0({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new W0({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new na({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new na({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function Hc(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(Y0);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function ur(e,t="hex"){const r=Fc(e),n=Hc(new Uint8Array(r.length));return r.encode(n),t==="hex"?Jt(n.bytes):n.bytes}function Fc(e){return Array.isArray(e)?X0(e.map(t=>Fc(t))):J0(e)}function X0(e){const t=e.reduce((i,s)=>i+s.length,0),r=Mc(t);return{length:t<=55?1+t:1+r+t,encode(i){t<=55?i.pushByte(192+t):(i.pushByte(247+r),r===1?i.pushUint8(t):r===2?i.pushUint16(t):r===3?i.pushUint24(t):i.pushUint32(t));for(const{encode:s}of e)s(i)}}}function J0(e){const t=typeof e=="string"?fr(e):e,r=Mc(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(i){t.length===1&&t[0]<128?i.pushBytes(t):t.length<=55?(i.pushByte(128+t.length),i.pushBytes(t)):(i.pushByte(183+r),r===1?i.pushUint8(t.length):r===2?i.pushUint16(t.length):r===3?i.pushUint24(t.length):i.pushUint32(t.length),i.pushBytes(t))}}}function Mc(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new he("Length is too large.")}const Q0={ether:-9,wei:9};function Z0(e,t){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[i,s]=[r.slice(0,r.length-t),r.slice(r.length-t)];return s=s.replace(/(0+)$/,""),`${n?"-":""}${i||"0"}${s?`.${s}`:""}`}function Ts(e,t="wei"){return Z0(e,Q0[t])}function ep(e){const t=Object.entries(e).map(([n,i])=>i===void 0||i===!1?null:[n,i]).filter(Boolean),r=t.reduce((n,[i])=>Math.max(n,i.length),0);return t.map(([n,i])=>` ${`${n}:`.padEnd(r+1)} ${i}`).join(`
|
|
33
|
-
`)}class
|
|
34
|
-
`),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(qc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class Wc extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}function oa(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function hp(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Js(e,...t){if(!hp(e))throw new Error("Uint8Array expected");if(t.length>0&&!t.includes(e.length))throw new Error("Uint8Array expected of length "+t+", got length="+e.length)}function aa(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function pp(e,t){Js(e);const r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Dn=BigInt(2**32-1),ca=BigInt(32);function yp(e,t=!1){return t?{h:Number(e&Dn),l:Number(e>>ca&Dn)}:{h:Number(e>>ca&Dn)|0,l:Number(e&Dn)|0}}function mp(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=yp(e[i],t);[r[i],n[i]]=[s,o]}return[r,n]}const bp=(e,t,r)=>e<<r|t>>>32-r,wp=(e,t,r)=>t<<r|e>>>32-r,gp=(e,t,r)=>t<<r-32|e>>>64-r,_p=(e,t,r)=>e<<r-32|t>>>64-r;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function vp(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}const fa=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ep(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}function ua(e){for(let t=0;t<e.length;t++)e[t]=Ep(e[t])}function xp(e){if(typeof e!="string")throw new Error("utf8ToBytes expected string, got "+typeof e);return new Uint8Array(new TextEncoder().encode(e))}function Kc(e){return typeof e=="string"&&(e=xp(e)),Js(e),e}class Sp{clone(){return this._cloneInto()}}function Tp(e){const t=n=>e().update(Kc(n)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}const Yc=[],Xc=[],Jc=[],Ap=BigInt(0),nn=BigInt(1),kp=BigInt(2),Bp=BigInt(7),Ip=BigInt(256),Pp=BigInt(113);for(let e=0,t=nn,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Yc.push(2*(5*n+r)),Xc.push((e+1)*(e+2)/2%64);let i=Ap;for(let s=0;s<7;s++)t=(t<<nn^(t>>Bp)*Pp)%Ip,t&kp&&(i^=nn<<(nn<<BigInt(s))-nn);Jc.push(i)}const[Op,Rp]=mp(Jc,!0),la=(e,t,r)=>r>32?gp(e,t,r):bp(e,t,r),da=(e,t,r)=>r>32?_p(e,t,r):wp(e,t,r);function Cp(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let o=0;o<10;o++)r[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,u=(o+2)%10,d=r[u],h=r[u+1],y=la(d,h,1)^r[a],v=da(d,h,1)^r[a+1];for(let p=0;p<50;p+=10)e[o+p]^=y,e[o+p+1]^=v}let i=e[2],s=e[3];for(let o=0;o<24;o++){const a=Xc[o],u=la(i,s,a),d=da(i,s,a),h=Yc[o];i=e[h],s=e[h+1],e[h]=u,e[h+1]=d}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=e[o+a];for(let a=0;a<10;a++)e[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=Op[n],e[1]^=Rp[n]}r.fill(0)}class Qs extends Sp{constructor(t,r,n,i=!1,s=24){if(super(),this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,oa(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=vp(this.state)}keccak(){fa||ua(this.state32),Cp(this.state32,this.rounds),fa||ua(this.state32),this.posOut=0,this.pos=0}update(t){aa(this);const{blockLen:r,state:n}=this;t=Kc(t);const i=t.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=t[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:i}=this;t[n]^=r,r&128&&n===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){aa(this,!1),Js(t),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=t.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);t.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return oa(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(pp(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,this.state.fill(0)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return t||(t=new Qs(r,n,i,o,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=i,t.enableXOF=o,t.destroyed=this.destroyed,t}}const Up=(e,t,r)=>Tp(()=>new Qs(t,e,r)),Lp=Up(1,136,256/8);function Np(e,t){return Lp(Bn(e,{strict:!1})?Uc(e):e)}const cs=new Wc(8192);function Hp(e,t){if(cs.has(`${e}.${t}`))return cs.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=Np(Lc(r)),i=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(n[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return cs.set(`${e}.${t}`,s),s}const Fp=/^0x[a-fA-F0-9]{40}$/,fs=new Wc(8192);function dr(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(fs.has(n))return fs.get(n);const i=Fp.test(e)?e.toLowerCase()===e?!0:r?Hp(e)===e:!0:!1;return fs.set(n,i),i}function Mp(e,t,r,{strict:n}={}){return Bn(e,{strict:!1})?$p(e,t,r,{strict:n}):Dp(e,t,r,{strict:n})}function Qc(e,t,r){if(Mr(e)!==r-t)throw new I0({offset:r,position:"end",size:Mr(e)})}function Dp(e,t,r,{strict:n}={}){const i=e.slice(t,r);return n&&Qc(i,t,r),i}function $p(e,t,r,{strict:n}={}){const i=`0x${e.replace("0x","").slice(t*2,r*2)}`;return n&&Qc(i,t,r),i}function jp(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:n}=r,i=r.address;if(!dr(i))throw new lr({address:i});if(n<0)throw new Ii({chainId:n})}Zs(e)}function Gp(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new zc;for(const r of t){const n=Mr(r),i=oi(Mp(r,0,1));if(n!==32)throw new fp({hash:r,size:n});if(i!==Vc)throw new up({hash:r,version:i})}}Zs(e)}function Zs(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new Ii({chainId:t});if(i&&!dr(i))throw new lr({address:i});if(n&&n>Ys)throw new Pi({maxFeePerGas:n});if(r&&n&&r>n)throw new qc({maxFeePerGas:n,maxPriorityFeePerGas:r})}function Vp(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(t<=0)throw new Ii({chainId:t});if(s&&!dr(s))throw new lr({address:s});if(r||i)throw new he("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Ys)throw new Pi({maxFeePerGas:n})}function zp(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(s&&!dr(s))throw new lr({address:s});if(typeof t<"u"&&t<=0)throw new Ii({chainId:t});if(r||i)throw new he("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Ys)throw new Pi({maxFeePerGas:n})}function qp(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new rp({transaction:e})}function Oi(e){if(!e||e.length===0)return[];const t=[];for(let r=0;r<e.length;r++){const{address:n,storageKeys:i}=e[r];for(let s=0;s<i.length;s++)if(i[s].length-2!==64)throw new np({storageKey:i[s]});if(!dr(n,{strict:!1}))throw new lr({address:n});t.push([n,i])}return t}function Wp(e,t){const r=qp(e);return r==="eip1559"?Xp(e,t):r==="eip2930"?Jp(e,t):r==="eip4844"?Yp(e,t):r==="eip7702"?Kp(e,t):Qp(e,t)}function Kp(e,t){const{authorizationList:r,chainId:n,gas:i,nonce:s,to:o,value:a,maxFeePerGas:u,maxPriorityFeePerGas:d,accessList:h,data:y}=e;jp(e);const v=Oi(h),p=ip(r);return In(["0x04",ur([Q(n),s?Q(s):"0x",d?Q(d):"0x",u?Q(u):"0x",i?Q(i):"0x",o??"0x",a?Q(a):"0x",y??"0x",v,p,...Pn(e,t)])])}function Yp(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:o,maxFeePerBlobGas:a,maxFeePerGas:u,maxPriorityFeePerGas:d,accessList:h,data:y}=e;Gp(e);let v=e.blobVersionedHashes,p=e.sidecars;if(e.blobs&&(typeof v>"u"||typeof p>"u")){const x=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(E=>Jt(E)),g=e.kzg,S=Dc({blobs:x,kzg:g});if(typeof v>"u"&&(v=ap({commitments:S})),typeof p>"u"){const E=$c({blobs:x,commitments:S,kzg:g});p=dp({blobs:x,commitments:S,proofs:E})}}const I=Oi(h),k=[Q(r),i?Q(i):"0x",d?Q(d):"0x",u?Q(u):"0x",n?Q(n):"0x",s??"0x",o?Q(o):"0x",y??"0x",I,a?Q(a):"0x",v??[],...Pn(e,t)],B=[],R=[],U=[];if(p)for(let x=0;x<p.length;x++){const{blob:g,commitment:S,proof:E}=p[x];B.push(g),R.push(S),U.push(E)}return In(["0x03",ur(p?[k,B,R,U]:k)])}function Xp(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:o,maxFeePerGas:a,maxPriorityFeePerGas:u,accessList:d,data:h}=e;Zs(e);const y=Oi(d),v=[Q(r),i?Q(i):"0x",u?Q(u):"0x",a?Q(a):"0x",n?Q(n):"0x",s??"0x",o?Q(o):"0x",h??"0x",y,...Pn(e,t)];return In(["0x02",ur(v)])}function Jp(e,t){const{chainId:r,gas:n,data:i,nonce:s,to:o,value:a,accessList:u,gasPrice:d}=e;Vp(e);const h=Oi(u),y=[Q(r),s?Q(s):"0x",d?Q(d):"0x",n?Q(n):"0x",o??"0x",a?Q(a):"0x",i??"0x",h,...Pn(e,t)];return In(["0x01",ur(y)])}function Qp(e,t){const{chainId:r=0,gas:n,data:i,nonce:s,to:o,value:a,gasPrice:u}=e;zp(e);let d=[s?Q(s):"0x",u?Q(u):"0x",n?Q(n):"0x",o??"0x",a?Q(a):"0x",i??"0x"];if(t){const h=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);const p=27n+(t.v===27n?0n:1n);if(t.v!==p)throw new tp({v:t.v});return p})(),y=si(t.r),v=si(t.s);d=[...d,Q(h),y==="0x00"?"0x":y,v==="0x00"?"0x":v]}else r>0&&(d=[...d,Q(r),"0x","0x"]);return ur(d)}function Pn(e,t){const r=t??e,{v:n,yParity:i}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof i>"u")return[];const s=si(r.r),o=si(r.s);return[typeof i=="number"?i?Q(1):"0x":n===0n?"0x":n===1n?Q(1):n===27n?"0x":Q(1),s==="0x00"?"0x":s,o==="0x00"?"0x":o]}const Zp={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},ey={block:j0({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const i=Ks(n);return i.typeHex==="0x7e"&&(i.isSystemTx=n.isSystemTx,i.mint=n.mint?kr(n.mint):void 0,i.sourceHash=n.sourceHash,i.type="deposit"),i}),stateRoot:e.stateRoot}}}),transaction:M0({format(e){const t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?kr(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:q0({format(e){return{l1GasPrice:e.l1GasPrice?kr(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?kr(e.l1GasUsed):null,l1Fee:e.l1Fee?kr(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};function ty(e,t){return iy(e)?ny(e):Wp(e,t)}const ry={transaction:ty};function ny(e){sy(e);const{sourceHash:t,data:r,from:n,gas:i,isSystemTx:s,mint:o,to:a,value:u}=e,d=[t,n,a??"0x",o?Q(o):"0x",u?Q(u):"0x",i?Q(i):"0x",s?"0x1":"0x",r??"0x"];return In(["0x7e",ur(d)])}function iy(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function sy(e){const{from:t,to:r}=e;if(t&&!dr(t))throw new lr({address:t});if(r&&!dr(r))throw new lr({address:r})}const ai={contracts:Zp,formatters:ey,serializers:ry},oy=pt({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),ay=pt({id:421614,name:"Arbitrum Sepolia",nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),sn=1,cy=pt({...ai,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...ai.contracts,disputeGameFactory:{[sn]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[sn]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[sn]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[sn]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:sn}),on=11155111,fy=pt({...ai,id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://sepolia.basescan.org",apiUrl:"https://api-sepolia.basescan.org/api"}},contracts:{...ai.contracts,disputeGameFactory:{[on]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[on]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[on]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[on]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:on}),uy=pt({id:80094,name:"Berachain",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0xddfb18888a9466688235887dec2a10c4f5effee9",blockCreated:877008}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),ly=pt({id:80084,name:"Berachain bArtio",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:109269},ensRegistry:{address:"0xB0eef18971290b333450586D33dcA6cE122651D2",blockCreated:7736794},ensUniversalResolver:{address:"0x41692Ef1EA0C79E6b73077E4A67572D2BDbD7057",blockCreated:7736795}},ensTlds:[".bera"],rpcUrls:{default:{http:["https://bartio.rpc.berachain.com"]}},blockExplorers:{default:{name:"Berachain bArtio Beratrail",url:"https://bartio.beratrail.io"}},testnet:!0}),dy=pt({id:5115,name:"Citrea Testnet",nativeCurrency:{name:"cBTC",symbol:"cBTC",decimals:18},rpcUrls:{default:{http:["https://rpc.testnet.citrea.xyz"]}},blockExplorers:{default:{name:"Citrea Explorer",url:"https://explorer.testnet.citrea.xyz",apiUrl:"https://explorer.testnet.citrea.xyz/api"}},testnet:!0}),hy=pt({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xce01f8eee7E479C928F8919abD53E553a36CeF67",blockCreated:19258213},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),py=pt({id:10143,name:"Monad Testnet",nativeCurrency:{name:"Testnet MON Token",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://testnet-rpc.monad.xyz"]}},blockExplorers:{default:{name:"Monad Testnet explorer",url:"https://testnet.monadexplorer.com"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:251449}},testnet:!0}),yy=pt({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.drpc.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xc8Af999e38273D658BE1b921b88A9Ddf005769cC",blockCreated:5317080}},testnet:!0}),my={...yy,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},Zc={id:998,name:"Hyperliquid EVM Testnet",nativeCurrency:{name:"Hyperliquid",symbol:"HYPE",decimals:18},blockExplorers:{default:{name:"Hyperliquid Explorer",url:"https://testnet.purrsec.com/"}},rpcUrls:{default:{http:["https://rpc.hyperliquid-testnet.xyz/evm"]}}},ef={id:999,name:"HyperEVM",nativeCurrency:{name:"Hyperliquid",symbol:"HYPE",decimals:18},blockExplorers:{default:{name:"Hyperliquid Explorer",url:"https://hyperscan.gas.zip/"}},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}}},tf={ethereum:hy,arbitrum:oy,ethereum_sepolia:my,arbitrum_sepolia:ay,ethereum_localnet:le.EthereumLocalnet,arbitrum_localnet:le.ArbitrumLocalnet,base_sepolia:fy,base:cy,bera_testnet:ly,citrea_testnet:dy,bera:uy,monad_testnet:py,hyperliquid_testnet:Zc,hyperliquid:ef},rf=async(e,t)=>{var n;const r=tf[e];if(r)try{if(r.id===((n=t.chain)==null?void 0:n.id))return re({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const i=it.createWalletClient({account:t.account,chain:r,transport:it.custom(t.transport)});return re({message:"Switched chain",walletClient:i})}catch(i){if(by(i))try{await t.addChain({chain:r});const s=it.createWalletClient({account:t.account,chain:r,transport:it.custom(window.ethereum)});return re({message:"Added network",walletClient:s})}catch{return M("Failed to add network")}else return M("Failed to switch network")}else return M("Chain not supported")},by=e=>typeof e=="object"&&e!==null&&"code"in e&&e.code===4902,wy=[{inputs:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[],name:"NativeHTLC__DuplicateOrder",type:"error"},{inputs:[],name:"NativeHTLC__IncorrectFundsRecieved",type:"error"},{inputs:[],name:"NativeHTLC__IncorrectSecret",type:"error"},{inputs:[],name:"NativeHTLC__InsufficientBalance",type:"error"},{inputs:[],name:"NativeHTLC__InvalidRedeemerSignature",type:"error"},{inputs:[],name:"NativeHTLC__OrderFulfilled",type:"error"},{inputs:[],name:"NativeHTLC__OrderNotExpired",type:"error"},{inputs:[],name:"NativeHTLC__OrderNotInitiated",type:"error"},{inputs:[],name:"NativeHTLC__SameInitiatorAndRedeemer",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAddressInitiator",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAddressRedeemer",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAmount",type:"error"},{inputs:[],name:"NativeHTLC__ZeroTimelock",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address payable",name:"initiator",type:"address"},{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiateOnBehalf",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"instantRefundDigest",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address payable",name:"initiator",type:"address"},{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];class nf{constructor(t,r,n){this.url=new j.Url("/relayer",t),this.auth=n,this.wallet=r}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(t){if(!this.wallet.account)return j.Err("No account found");if(this.wallet.account.address.toLowerCase()!==t.source_swap.initiator.toLowerCase())return j.Err("Account address and order initiator mismatch");if(!le.isEVM(t.source_swap.chain))return j.Err("Source chain is not an EVM chain");const r=await rf(t.source_swap.chain,this.wallet);if(r.error)return j.Err(r.error);if(this.wallet=r.val.walletClient,!this.wallet.account)return j.Err("No account found");const{create_order:n,source_swap:i}=t;if(!i.amount||!i.redeemer||!n.timelock||!n.secret_hash)return j.Err("Invalid order");const s=j.with0x(n.secret_hash),o=BigInt(n.timelock),a=j.with0x(i.redeemer),u=BigInt(i.amount),d=await this.getTokenAddress(t.source_swap.asset);return d.error?j.Err(d.error):le.isEvmNativeToken(t.source_swap.chain,d.val)?this._initiateOnNativeHTLC(s,o,u,a,t.source_swap.asset):this._initiateOnErc20HTLC(s,o,u,a,t.source_swap.asset,d.val,n.create_id)}async getTokenAddress(t){try{const n=await it.getContract({address:j.with0x(t),abi:ta,client:this.wallet}).read.token();return j.Ok(n)}catch(r){return j.Err("Failed to get token address",String(r))}}async _initiateOnNativeHTLC(t,r,n,i,s){if(!this.wallet.account)return j.Err("No account found");try{const a=await it.getContract({address:j.with0x(s),abi:wy,client:this.wallet}).write.initiate([i,r,n,t],{account:this.wallet.account,chain:this.wallet.chain,value:n});return j.Ok(a)}catch(o){return j.Err("Failed to initiate on native HTLC",String(o))}}async _initiateOnErc20HTLC(t,r,n,i,s,o,a){if(!this.wallet.account)return j.Err("No account found");try{const u=await this.auth.getAuthHeaders();if(u.error)return j.Err(u.error);const d=it.getContract({address:j.with0x(s),abi:ta,client:this.wallet}),h=await j.checkAllowanceAndApprove(Number(n),o,s,this.wallet);if(h.error)return j.Err(h.error);const y=await d.read.eip712Domain(),v=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:y[1],version:y[2],chainId:Number(y[3]),verifyingContract:y[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:i,timelock:r,amount:n,secretHash:t}}),p={...u.val,"Content-Type":"application/json"},I=await xt.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:a,signature:v,perform_on:"Source"}),headers:p});return I.error?j.Err(I.error):I.result?j.Ok(I.result):j.Err("Init: No result found")}catch(u){return console.log("init error :",u),j.Err(String(u))}}async redeem(t,r){try{const n=await this.auth.getAuthHeaders();if(n.error)return j.Err(n.error);const i=await xt.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:rr(r),perform_on:"Destination"}),headers:{...n.val,"Content-Type":"application/json"}});return i.error?j.Err(i.error):i.result?j.Ok(i.result):j.Err("Redeem: No result found")}catch(n){return j.Err(String(n))}}async refund(){return j.Err("Refund not supported")}}const sf=[{name:"LockingContract",type:"impl",interface_name:"src::mintable_lock_interface::ILockingContract"},{name:"src::mintable_lock_interface::ILockingContract",type:"interface",items:[{name:"set_locking_contract",type:"function",inputs:[{name:"locking_contract",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"get_locking_contract",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"}]},{name:"LockAndDelegate",type:"impl",interface_name:"src::mintable_lock_interface::ILockAndDelegate"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"src::mintable_lock_interface::ILockAndDelegate",type:"interface",items:[{name:"lock_and_delegate",type:"function",inputs:[{name:"delegatee",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"lock_and_delegate_by_sig",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"delegatee",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"},{name:"nonce",type:"core::felt252"},{name:"expiry",type:"core::integer::u64"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"MintableToken",type:"impl",interface_name:"src::mintable_token_interface::IMintableToken"},{name:"src::mintable_token_interface::IMintableToken",type:"interface",items:[{name:"permissioned_mint",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"permissioned_burn",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"}]},{name:"MintableTokenCamelImpl",type:"impl",interface_name:"src::mintable_token_interface::IMintableTokenCamel"},{name:"src::mintable_token_interface::IMintableTokenCamel",type:"interface",items:[{name:"permissionedMint",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"permissionedBurn",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"}]},{name:"Replaceable",type:"impl",interface_name:"src::replaceability_interface::IReplaceable"},{name:"core::array::Span::<core::felt252>",type:"struct",members:[{name:"snapshot",type:"@core::array::Array::<core::felt252>"}]},{name:"src::replaceability_interface::EICData",type:"struct",members:[{name:"eic_hash",type:"core::starknet::class_hash::ClassHash"},{name:"eic_init_data",type:"core::array::Span::<core::felt252>"}]},{name:"core::option::Option::<src::replaceability_interface::EICData>",type:"enum",variants:[{name:"Some",type:"src::replaceability_interface::EICData"},{name:"None",type:"()"}]},{name:"core::bool",type:"enum",variants:[{name:"False",type:"()"},{name:"True",type:"()"}]},{name:"src::replaceability_interface::ImplementationData",type:"struct",members:[{name:"impl_hash",type:"core::starknet::class_hash::ClassHash"},{name:"eic_data",type:"core::option::Option::<src::replaceability_interface::EICData>"},{name:"final",type:"core::bool"}]},{name:"src::replaceability_interface::IReplaceable",type:"interface",items:[{name:"get_upgrade_delay",type:"function",inputs:[],outputs:[{type:"core::integer::u64"}],state_mutability:"view"},{name:"get_impl_activation_time",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[{type:"core::integer::u64"}],state_mutability:"view"},{name:"add_new_implementation",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"},{name:"remove_implementation",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"},{name:"replace_to",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"}]},{name:"AccessControlImplExternal",type:"impl",interface_name:"src::access_control_interface::IAccessControl"},{name:"src::access_control_interface::IAccessControl",type:"interface",items:[{name:"has_role",type:"function",inputs:[{name:"role",type:"core::felt252"},{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"get_role_admin",type:"function",inputs:[{name:"role",type:"core::felt252"}],outputs:[{type:"core::felt252"}],state_mutability:"view"}]},{name:"RolesImpl",type:"impl",interface_name:"src::roles_interface::IMinimalRoles"},{name:"src::roles_interface::IMinimalRoles",type:"interface",items:[{name:"is_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"is_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"register_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"remove_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"register_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"remove_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"renounce",type:"function",inputs:[{name:"role",type:"core::felt252"}],outputs:[],state_mutability:"external"}]},{name:"ERC20Impl",type:"impl",interface_name:"openzeppelin::token::erc20::interface::IERC20"},{name:"openzeppelin::token::erc20::interface::IERC20",type:"interface",items:[{name:"name",type:"function",inputs:[],outputs:[{type:"core::felt252"}],state_mutability:"view"},{name:"symbol",type:"function",inputs:[],outputs:[{type:"core::felt252"}],state_mutability:"view"},{name:"decimals",type:"function",inputs:[],outputs:[{type:"core::integer::u8"}],state_mutability:"view"},{name:"total_supply",type:"function",inputs:[],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"balance_of",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"allowance",type:"function",inputs:[{name:"owner",type:"core::starknet::contract_address::ContractAddress"},{name:"spender",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"transfer",type:"function",inputs:[{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"transfer_from",type:"function",inputs:[{name:"sender",type:"core::starknet::contract_address::ContractAddress"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"approve",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"}]},{name:"ERC20CamelOnlyImpl",type:"impl",interface_name:"openzeppelin::token::erc20::interface::IERC20CamelOnly"},{name:"openzeppelin::token::erc20::interface::IERC20CamelOnly",type:"interface",items:[{name:"totalSupply",type:"function",inputs:[],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"balanceOf",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"transferFrom",type:"function",inputs:[{name:"sender",type:"core::starknet::contract_address::ContractAddress"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"name",type:"core::felt252"},{name:"symbol",type:"core::felt252"},{name:"decimals",type:"core::integer::u8"},{name:"initial_supply",type:"core::integer::u256"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"permitted_minter",type:"core::starknet::contract_address::ContractAddress"},{name:"provisional_governance_admin",type:"core::starknet::contract_address::ContractAddress"},{name:"upgrade_delay",type:"core::integer::u64"}]},{name:"increase_allowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"added_value",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"decrease_allowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"subtracted_value",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"increaseAllowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"addedValue",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"decreaseAllowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"subtractedValue",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{kind:"struct",name:"src::strk::erc20_lockable::ERC20Lockable::Transfer",type:"event",members:[{kind:"data",name:"from",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"to",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"value",type:"core::integer::u256"}]},{kind:"struct",name:"src::strk::erc20_lockable::ERC20Lockable::Approval",type:"event",members:[{kind:"data",name:"owner",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"spender",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"value",type:"core::integer::u256"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationAdded",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationRemoved",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationReplaced",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationFinalized",type:"event",members:[{kind:"data",name:"impl_hash",type:"core::starknet::class_hash::ClassHash"}]},{kind:"struct",name:"src::access_control_interface::RoleGranted",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"sender",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::access_control_interface::RoleRevoked",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"sender",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::access_control_interface::RoleAdminChanged",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"previous_admin_role",type:"core::felt252"},{kind:"data",name:"new_admin_role",type:"core::felt252"}]},{kind:"struct",name:"src::roles_interface::GovernanceAdminAdded",type:"event",members:[{kind:"data",name:"added_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"added_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::GovernanceAdminRemoved",type:"event",members:[{kind:"data",name:"removed_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"removed_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::UpgradeGovernorAdded",type:"event",members:[{kind:"data",name:"added_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"added_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::UpgradeGovernorRemoved",type:"event",members:[{kind:"data",name:"removed_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"removed_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"enum",name:"src::strk::erc20_lockable::ERC20Lockable::Event",type:"event",variants:[{kind:"nested",name:"Transfer",type:"src::strk::erc20_lockable::ERC20Lockable::Transfer"},{kind:"nested",name:"Approval",type:"src::strk::erc20_lockable::ERC20Lockable::Approval"},{kind:"nested",name:"ImplementationAdded",type:"src::replaceability_interface::ImplementationAdded"},{kind:"nested",name:"ImplementationRemoved",type:"src::replaceability_interface::ImplementationRemoved"},{kind:"nested",name:"ImplementationReplaced",type:"src::replaceability_interface::ImplementationReplaced"},{kind:"nested",name:"ImplementationFinalized",type:"src::replaceability_interface::ImplementationFinalized"},{kind:"nested",name:"RoleGranted",type:"src::access_control_interface::RoleGranted"},{kind:"nested",name:"RoleRevoked",type:"src::access_control_interface::RoleRevoked"},{kind:"nested",name:"RoleAdminChanged",type:"src::access_control_interface::RoleAdminChanged"},{kind:"nested",name:"GovernanceAdminAdded",type:"src::roles_interface::GovernanceAdminAdded"},{kind:"nested",name:"GovernanceAdminRemoved",type:"src::roles_interface::GovernanceAdminRemoved"},{kind:"nested",name:"UpgradeGovernorAdded",type:"src::roles_interface::UpgradeGovernorAdded"},{kind:"nested",name:"UpgradeGovernorRemoved",type:"src::roles_interface::UpgradeGovernorRemoved"}]}],of=async(e,t,r,n,i)=>{try{const s=new Ne.RpcProvider({nodeUrl:i}),o=await ha(e.address,t,r,i);if(o.error)return M(o.error);const a=Ne.cairo.uint256(BigInt(Ne.uint256.UINT_256_MAX));if(o.val<n){const u=await e.execute([{contractAddress:$n(t),entrypoint:"approve",calldata:[r,a.low,a.high]}]);await s.waitForTransaction(u.transaction_hash,{retryInterval:3e3,successStates:[Ne.TransactionExecutionStatus.SUCCEEDED]}),await j.sleep(2e3);let d=0n;for(let h=0;h<20;h++){const y=await ha(e.address,t,r,i);if(y.error)return M(y.error);if(d=y.val,d>=n)break;await j.sleep(2e3)}return d<n?M("Allowance not approved"):re(u.transaction_hash)}return re("Allowance already approved")}catch(s){return M(`Failed to check or approve allowance: ${s instanceof Error?s.message:String(s)}`)}},ha=async(e,t,r,n)=>{try{const i=new Ne.RpcProvider({nodeUrl:n}),o=await new Ne.Contract(sf,$n(t),i).call("allowance",[$n(e),$n(r)]);return re(BigInt((o==null?void 0:o.toString())||"0"))}catch(i){return M(`Failed to check allowance: ${i instanceof Error?i.message:String(i)}`)}},af=[{name:"HTLC",type:"impl",interface_name:"starknet_htlc::interface::IHTLC"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"starknet_htlc::interface::IHTLC",type:"interface",items:[{name:"token",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"},{name:"initiate",type:"function",inputs:[{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_on_behalf",type:"function",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_with_signature",type:"function",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u32; 8]"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{name:"redeem",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"secret",type:"core::array::Array::<core::integer::u32>"}],outputs:[],state_mutability:"external"},{name:"refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[],state_mutability:"external"},{name:"instant_refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"token",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"starknet_htlc::interface::events::Initiated",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"amount",type:"core::integer::u256"}]},{kind:"struct",name:"starknet_htlc::interface::events::Redeemed",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"secret",type:"core::array::Array::<core::integer::u32>"}]},{kind:"struct",name:"starknet_htlc::interface::events::Refunded",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"}]},{kind:"enum",name:"starknet_htlc::htlc::HTLC::Event",type:"event",variants:[{kind:"nested",name:"Initiated",type:"starknet_htlc::interface::events::Initiated"},{kind:"nested",name:"Redeemed",type:"starknet_htlc::interface::events::Redeemed"},{kind:"nested",name:"Refunded",type:"starknet_htlc::interface::events::Refunded"}]}],gy={name:"HTLC",version:Ne.shortString.encodeShortString("1"),chainId:"0x534e5f5345504f4c4941",revision:Ne.TypedDataRevision.ACTIVE},_y={StarknetDomain:[{name:"name",type:"shortstring"},{name:"version",type:"shortstring"},{name:"chainId",type:"shortstring"},{name:"revision",type:"shortstring"}],Initiate:[{name:"redeemer",type:"ContractAddress"},{name:"amount",type:"u256"},{name:"timelock",type:"u128"},{name:"secretHash",type:"u128*"}]},vy={[j.Network.MAINNET]:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8",[j.Network.TESTNET]:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"};class cf{constructor(t,r,n){this.nodeUrl=vy[n],this.url=new j.Url("/",t),this.account=r}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(t){if(!this.account.address)return M("No account address");const{create_order:r,source_swap:n}=t,{redeemer:i,amount:s}=n;if(!s||!i||!r.secret_hash||!r.timelock)return M("Invalid order");try{const o=new Ne.Contract(af,t.source_swap.asset,this.account),a=await(o==null?void 0:o.token()),u=Ne.num.toHex(a),d=await of(this.account,u,n.asset,BigInt(s),this.nodeUrl);if(d.error)return M(d.error);const h={domain:gy,primaryType:"Initiate",types:_y,message:{redeemer:i,amount:Ne.cairo.uint256(s),timelock:r.timelock,secretHash:j.hexToU32Array(r.secret_hash)}},y=await this.account.signMessage(h),v=xf(y);if(v.error)return M(v.error);const p=await xt.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:r.create_id,signature:v.val,perform_on:"Source"}),headers:{"Content-Type":"application/json"},retryCount:5,retryDelay:2e3});return p.error?M(p.error):p.result?re(p.result):M("Init: No result found")}catch(o){return M(String(o))}}async redeem(t,r){try{const n=await xt.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"}});return n.error?M(n.error):n.result?re(n.result):M("Redeem: No result found")}catch(n){return M(String(n))}}async refund(){return M("Refund is taken care of by the relayer")}}class eo extends j.EventBroker{constructor(t){if(super(),this.environment=j.Environment.TESTNET,this.getOrderThreshold=20,this.refundSacpCache=new Map,this.bitcoinRedeemCache=new Fl,typeof t.digestKey=="string"){const n=j.DigestKey.from(t.digestKey);if(n.error)throw new Error(n.error);this._digestKey=n.val}else this._digestKey=t.digestKey;if(typeof t.environment=="string"){if(this.environment=t.environment,this._api=t.environment===j.Environment.MAINNET?un.mainnet:t.environment===j.Environment.TESTNET?un.testnet:void 0,!this._api)throw new Error("API not found, invalid environment "+t.environment)}else this._api=t.environment;this._quote=t.quote??new qa(this._api.quote),this._auth=t.auth??j.Siwe.fromDigestKey(new j.Url(this._api.auth),this._digestKey),this._orderbook=t.orderbook??new le.Orderbook(new j.Url(this._api.orderbook)),this._evmHTLC=t.htlc.evm,this._starknetHTLC=t.htlc.starknet,this._secretManager=t.secretManager??wn.fromDigestKey(this._digestKey.digestKey),this.orderExecutorCache=new Hl,this._blockNumberFetcher=t.blockNumberFetcher??new za(this._api.info,this.environment);const r=new Rr.BitcoinProvider(vf(this.environment));this._btcWallet=Rr.BitcoinWallet.fromPrivateKey(this._digestKey.digestKey,r)}static fromWallets(t){let r;if(typeof t.digestKey=="string"){const s=j.DigestKey.from(t.digestKey);if(s.error)throw new Error(s.error);r=s.val}else r=t.digestKey;let n;if(typeof t.environment=="string"?n=t.environment===j.Environment.MAINNET?un.mainnet:t.environment===j.Environment.TESTNET?un.testnet:void 0:n=t.environment,!n)throw new Error("API not found, invalid environment "+t.environment);const i={evm:t.wallets.evm?new nf(n.evmRelay,t.wallets.evm,j.Siwe.fromDigestKey(new j.Url(n.auth),r)):void 0,starknet:t.wallets.starknet?new cf(n.starknetRelay,t.wallets.starknet,t.environment===j.Environment.MAINNET?j.Network.MAINNET:j.Network.TESTNET):void 0};return new eo({htlc:i,...t})}get evmHTLC(){return this._evmHTLC}get starknetHTLC(){return this._starknetHTLC}get quote(){return this._quote}get btcWallet(){return this._btcWallet}get orderbook(){return this._orderbook}get blockNumberFetcher(){return this._blockNumberFetcher}get secretManager(){return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}async swap(t){const r=await this.validateAndFillParams(t);if(r.error)return M(r.error);const{sendAddress:n,receiveAddress:i,timelock:s}=r.val,o=Date.now().toString(),a=await this._secretManager.generateSecret(o);if(a.error)return M(a.error);const{strategyId:u,btcAddress:d}=t.additionalData,h={strategy_id:u,...d&&{bitcoin_optional_recipient:d}},y={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,initiator_source_address:n,initiator_destination_address:i,source_amount:t.sendAmount,destination_amount:t.receiveAmount,fee:"1",nonce:o,timelock:s,secret_hash:rr(a.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:h},v=await this._quote.getAttestedQuote(y);if(v.error)return M(v.error);const p=await this._orderbook.createOrder(v.val,this.auth);if(p.error)return M(p.error);const I=await this.pollOrder(p.val);return I.error?M(I.error):re(I.val)}async validateAndFillParams(t){if(!t.additionalData.strategyId)return M("StrategyId is required");if(!t.fromAsset||!t.toAsset)return M("Source and destination assets are required for swap");if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return M("Source and destination assets cannot be the same");if(le.isMainnet(t.fromAsset.chain)&&!le.isMainnet(t.toAsset.chain)||!le.isMainnet(t.fromAsset.chain)&&le.isMainnet(t.toAsset.chain))return M("Both assets should be on the same network (either mainnet or testnet)");const r=this.validateAmount(t.sendAmount);if(r.error)return M(r.error);const n=this.validateAmount(t.receiveAmount);if(n.error)return M(n.error);if(r<n)return M("Send amount should be greater than receive amount");const i=le.getTimeLock(t.fromAsset.chain);if(!i)return M("Unsupported chain for timelock");if((le.isBitcoin(t.fromAsset.chain)||le.isBitcoin(t.toAsset.chain))&&!t.additionalData.btcAddress)return M("btcAddress in additionalData is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const s=await this.getAddresses(t.fromAsset.chain);if(s.error)return M(s.error);const o=await this.getAddresses(t.toAsset.chain);return o.error?M(o.error):re({sendAddress:s.val,receiveAddress:o.val,timelock:t.timelock??i})}async getAddresses(t){var n;switch(le.getBlockchainType(t)){case le.BlockchainType.EVM:return this._evmHTLC?re(this._evmHTLC.htlcActorAddress):M("Please provide evmHTLC when initializing garden");case le.BlockchainType.Bitcoin:{const i=await((n=this._btcWallet)==null?void 0:n.getPublicKey());return!i||!gf(i)?M("Invalid btc public key"):re(Dt(i))}case le.BlockchainType.Starknet:return this._starknetHTLC?re(this._starknetHTLC.htlcActorAddress):M("Please provide starknetHTLC when initializing garden");default:return M("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return M("Invalid amount ",t);const r=new df(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?M("Invalid amount ",t):re(r)}async pollOrder(t){let r=await this._orderbook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await j.sleep(1e3),n++,r.error){if(!r.error.includes("result is undefined"))return M(r.error)}else if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return re(r.val);r=await this._orderbook.getOrder(t,!0)}return M(`Order not found, createOrder id: ${t}`)}async execute(t=5e3){return await this._orderbook.subscribeOrders(this._digestKey.userId,!0,t,async r=>{if(r.data.length===0)return;const n=await this.filterExpiredAndAssignStatus(r.data);if(!n.error){this.emit("onPendingOrdersChanged",n.val);for(let i=0;i<n.val.length;i++){const s=n.val[i],o=Bs(s.status);if(le.isBitcoin(s.source_swap.chain)&&s.status===de.InitiateDetected){const a=this.btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");continue}await this.postRefundSACP(s,a)}switch(o){case Te.Redeem:{const a=await this._secretManager.generateSecret(s.create_order.nonce);if(a.error){this.emit("error",s,a.error);return}switch(le.getBlockchainType(s.destination_swap.chain)){case le.BlockchainType.EVM:{await this.evmRedeem(s,a.val.secret);break}case le.BlockchainType.Bitcoin:{const u=this.btcWallet;if(!u){this.emit("error",s,"BTC wallet not found");return}await this.btcRedeem(u,s,a.val.secret);break}case le.BlockchainType.Starknet:{await this.starknetRedeem(s,a.val.secret);break}default:this.emit("error",s,"Unsupported chain: "+s.destination_swap.chain)}break}case Te.Refund:{switch(le.getBlockchainType(s.source_swap.chain)){case le.BlockchainType.EVM:{this.emit("error",s,"EVM refund is automatically done by relay service");break}case le.BlockchainType.Bitcoin:{const a=this.btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");return}await this.btcRefund(a,s);break}case le.BlockchainType.Starknet:{this.emit("error",s,"Starknet refund is automatically done by relay service");break}default:this.emit("error",s,"Unsupported chain: "+s.source_swap.chain)}break}}}}},"pending",{per_page:500})}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,Te.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._evmHTLC){this.emit("error",t,"EVMHTLC is required");return}const i=await this._evmHTLC.redeem(t,r);if(i.error){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Te.Redeem,t.destination_swap.redeem_tx_hash);return}this.orderExecutorCache.set(t,Te.Redeem,i.val),this.emit("success",t,Te.Redeem,i.val)}async starknetRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing starknet redeem"),this.orderExecutorCache.get(t,Te.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._starknetHTLC){this.emit("error",t,"StarknetHTLC is required");return}const i=await this._starknetHTLC.redeem(t,r);if(i.error){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Te.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,Te.Redeem,i.val),this.emit("success",t,Te.Redeem,i.val))}async btcRedeem(t,r,n){var a,u;const i=this.bitcoinRedeemCache.get(r.create_order.create_id),s=(a=r.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:a.split(":").at(0);if(!s){this.emit("error",r,"Failed to get initiate_tx_hash");return}let o=!1;if(i)if(i.redeemedFromUTXO&&i.redeemedFromUTXO!==s)o=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else if(i.redeemedAt&&Date.now()-i.redeemedAt>1e3*60*15)this.emit("log",r.create_order.create_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const d=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let h=!1;for(const y of d.vin)if(y.txid===s){h=!0;break}if(h){this.emit("log",r.create_order.create_id,"already a valid redeem");let y=0;try{const[v]=await(await t.getProvider()).getTransactionTimes([r.destination_swap.redeem_tx_hash]);v!==0&&(y=v)}catch{y=Date.now()}this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:y,redeemTxHash:r.destination_swap.redeem_tx_hash});return}o=!0}catch(d){if(d.message.includes("Transaction not found"))o=!0;else{this.emit("error",r,"Failed to get redeem tx: "+d);return}}this.emit("log",r.create_order.create_id,"executing btc redeem");try{const h=await(await hn.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,Dt(r.destination_swap.initiator),Dt(r.destination_swap.redeemer),r.destination_swap.timelock,o?[s]:[])).getRedeemHex(rr(n),(u=r.create_order.additional_data)==null?void 0:u.bitcoin_optional_recipient),y=await this.broadcastRedeemTx(h,r.create_order.create_id);if(y.error||!y.val){this.emit("error",r,y.error||"Failed to broadcast redeem tx");return}o?(this.emit("log",r.create_order.create_id,"rbf: btc redeem success"),this.emit("rbf",r,y.val)):this.emit("success",r,Te.Redeem,y.val),this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:Date.now(),redeemTxHash:y.val})}catch(d){console.log("error",d),this.emit("error",r,"Failed btc redeem: "+d)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,Te.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const s=await(await hn.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,Dt(r.source_swap.initiator),Dt(r.source_swap.redeemer),r.source_swap.timelock)).refund((n=r.create_order.additional_data)==null?void 0:n.bitcoin_optional_recipient);this.orderExecutorCache.set(r,Te.Refund,s),this.emit("success",r,Te.Refund,s)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}async postRefundSACP(t,r){const n=this.refundSacpCache.get(t.create_order.create_id);if((n==null?void 0:n.initTxHash)===t.source_swap.initiate_tx_hash)return;const i=await hn.from(r,Number(t.source_swap.amount),t.create_order.secret_hash,Dt(t.source_swap.initiator),Dt(t.source_swap.redeemer),t.source_swap.timelock),s=t.create_order.additional_data.bitcoin_optional_recipient;if(s)try{const o=await i.generateInstantRefundSACP(s);if(!this._api)return;const a=new j.Url(this._api.orderbook).endpoint("orders/bitcoin/"+t.create_order.create_id+"/instant-refund");(await xt.post(a,{headers:{"Content-Type":"application/json"},body:JSON.stringify({instant_refund_tx_bytes:o})})).status==="Ok"&&this.refundSacpCache.set(t.create_order.create_id,{initTxHash:t.source_swap.initiate_tx_hash})}catch(o){this.emit("error",t,"Failed to generate and post SACP: "+o);return}}async filterExpiredAndAssignStatus(t){var i;if(t.length===0)return re([]);const r=await((i=this._blockNumberFetcher)==null?void 0:i.fetchBlockNumbers());if(r.error)return M(r.error);const n=[];for(let s=0;s<t.length;s++){const o=t[s];if(wa(o))continue;const a=o.source_swap.chain,u=o.destination_swap.chain,d=r==null?void 0:r.val[a],h=r==null?void 0:r.val[u];if(!d||!h){this.emit("error",o,"Error while fetching CurrentBlockNumbers");continue}const y=ks(o,d,h);n.push({...o,status:y})}return re(n)}async broadcastRedeemTx(t,r){try{if(!this._api)return M("API not found");const n=new j.Url(this._api.evmRelay).endpoint("/bitcoin/redeem "),i=await this._auth.getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...i.val},body:JSON.stringify({redeem_tx_bytes:t,order_id:r})})).json();return o.status==="Ok"&&o.result?re(o.result):M(o.error)}catch(n){return M("Failed to broadcast redeem tx: "+n)}}}const Ey="https://starknet-sepolia.public.blastapi.io/rpc/v0_7";class xy{constructor(t,r){this.callData=new Ne.CallData(sf),this.nodeUrl=r||Ey,this.account=t}get htlcActorAddress(){return this.account.address}async getHTLCContract(t,r=!1){const n=r?t.destination_swap.asset:t.source_swap.asset;return new Ne.Contract(af,n,this.account)}async initiate(t){try{const n=await(await this.getHTLCContract(t)).token();if(!n)throw new Error("Token address retrieval failed");const i=Ne.num.toHex(n),s=Ne.cairo.uint256(BigInt(t.source_swap.amount));try{const a=await of(this.account,i,t.source_swap.asset,BigInt(t.source_swap.amount),this.nodeUrl);if(a.error)return M(a.error)}catch(a){return M(`Allowance check failed: ${a}`)}const o=await this.account.execute({contractAddress:t.source_swap.asset,entrypoint:"initiate",calldata:[t.source_swap.redeemer,BigInt(t.source_swap.timelock),s.low,s.high,...j.hexToU32Array(t.create_order.secret_hash)]});if(!o.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return re(o.transaction_hash)}catch(r){return M(`HTLC Initiation Error: ${r}`)}}async redeem(t,r){try{const n=await this.getHTLCContract(t,!0),i=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,s=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:Ne.CallData.compile({swap_id:i,secret:j.hexToU32Array(r)})});return s.transaction_hash?re(s.transaction_hash):M("Failed to redeem HTLC transaction")}catch{return M("HTLC Redeem Error")}}async refund(t){try{const r=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,n=await this.getHTLCContract(t),i=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return i.transaction_hash?re(i.transaction_hash):M("Failed to refund HTLC transaction")}catch{return M("HTLC Refund Error")}}}exports.API=un;exports.BlockNumberFetcher=za;exports.EvmRelay=nf;exports.Garden=eo;exports.OrderActions=Te;exports.OrderStatus=de;exports.ParseOrderStatus=ks;exports.ParseSwapStatus=ds;exports.Quote=qa;exports.SecretManager=wn;exports.StarknetHTLC=xy;exports.StarknetRelay=cf;exports.SwapStatus=be;exports.constructOrderPair=ba;exports.evmToViemChainMap=tf;exports.filterDeadlineExpiredOrders=Tf;exports.hyperliquid=ef;exports.hyperliquidTestnet=Zc;exports.isExpired=pn;exports.parseAction=Sf;exports.parseActionFromStatus=Bs;exports.switchOrAddNetwork=rf;exports.toXOnly=Dt;exports.validateBTCAddress=_f;
|
|
28
|
+
`.trim().replace(/\s+/g," "))}leaves(){return[{version:Nn,output:this.redeemLeaf()},[{version:Nn,output:this.refundLeaf()},{version:Nn,output:this.instantRefundLeaf()}]]}generateMerkleProofFor(t){const r=this.leafHash(1),n=this.leafHash(2),i=this.leafHash(0);switch(t){case 1:{const s=Ef(i,n);return[ie.crypto.taggedHash("TapBranch",Buffer.concat(s))]}case 0:return[n,r];case 2:return[i,r];default:throw new Error(Be.invalidLeaf)}}}function vr(e,t){const r=[];for(let n=0;n<t;n++)r.push(e);return r}class Xl{constructor(){this.cache={}}set(t,r,n,i){const s={txHash:n,timeStamp:Date.now(),btcRedeemUTXO:i};this.cache[`${r}_${t.create_order.create_id}`]=s}get(t,r){return this.cache[`${r}_${t.create_order.create_id}`]||null}remove(t,r){delete this.cache[`${r}_${t.create_order.create_id}`]}}class Jl{constructor(){this.cache={}}set(t,r){this.cache[t]=r}get(t){return this.cache[t]||null}}class Xa{constructor(t,r){this.url=new j.Url(t).endpoint("blocknumbers").endpoint(r)}async fetchBlockNumbers(){try{const t=await xt.get(this.url);return re(t)}catch(t){return M("Failed to fetch block numbers",t)}}}const fn={mainnet:{orderbook:"https://api.garden.finance",auth:"https://api.garden.finance/auth",quote:"https://api.garden.finance/quote",info:"https://api.garden.finance/info",evmRelay:"https://api.garden.finance/relayer",starknetRelay:""},testnet:{orderbook:"https://testnet.api.garden.finance",auth:"https://testnet.api.garden.finance/auth",quote:"https://testnet.api.garden.finance/quote",info:"https://testnet.api.garden.finance/info",evmRelay:"https://testnet.api.garden.finance/relayer",starknetRelay:""},localnet:{orderbook:"",auth:"",quote:"",info:"",evmRelay:"",starknetRelay:""}};class Ja{constructor(t){this.quoteUrl=new j.Url(t)}async getQuote(t,r,n=!1,i){try{const s=this.quoteUrl.endpoint("/").addSearchParams({order_pair:t,amount:r.toString(),exact_out:n.toString()}),o=await xt.get(s,{retryCount:0,...i});return o.error?M(o.error):o.result?re(o.result):M("GetQuote: Unexpected error, result is undefined")}catch(s){return M("GetQuote:",String(s))}}async getAttestedQuote(t){try{const r=await xt.post(this.quoteUrl.endpoint("/attested").toString(),{body:JSON.stringify(t),headers:{"Content-Type":"application/json"}});return r.error?M(r.error):r.result?re(r.result):M("GetAttestedQuote: Unexpected error, result is undefined")}catch(r){return console.log("error :",r),M("GetAttestedQuote:",String(r))}}async getStrategies(){try{const t=await xt.get(this.quoteUrl.endpoint("/strategies"));if(t.error)return M(t.error);if(!t.result)return M("GetStrategies: Unexpected error, result is undefined");const r={};for(const n of Object.values(t.result)){const i=wa(n.source_chain,n.source_asset.asset,n.dest_chain,n.dest_asset.asset);r[i]={id:n.id,minAmount:n.min_amount,maxAmount:n.max_amount,fee:n.fee}}return re(r)}catch(t){return M("GetStrategies:",String(t))}}}var Qa={},Lr={},Nr={};Object.defineProperty(Nr,"__esModule",{value:!0});Nr.testnet=Nr.bitcoin=void 0;Nr.bitcoin={messagePrefix:`Bitcoin Signed Message:
|
|
29
|
+
`,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128};Nr.testnet={messagePrefix:`Bitcoin Signed Message:
|
|
30
|
+
`,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};var Za={};(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.maybe=e.Boolean=e.Array=e.Buffer256bit=e.Network=e.typeforce=void 0,e.typeforce=ka,e.Network=e.typeforce.compile({messagePrefix:e.typeforce.oneOf(e.typeforce.Buffer,e.typeforce.String),bip32:{public:e.typeforce.UInt32,private:e.typeforce.UInt32},pubKeyHash:e.typeforce.UInt8,scriptHash:e.typeforce.UInt8,wif:e.typeforce.UInt8}),e.Buffer256bit=e.typeforce.BufferN(32),e.Array=e.typeforce.Array,e.Boolean=e.typeforce.Boolean,e.maybe=e.typeforce.maybe})(Za);var bs={exports:{}},ws={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */(function(e,t){var r=Bt,n=r.Buffer;function i(o,a){for(var u in o)a[u]=o[u]}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=s);function s(o,a,u){return n(o,a,u)}s.prototype=Object.create(n.prototype),i(n,s),s.from=function(o,a,u){if(typeof o=="number")throw new TypeError("Argument must not be a number");return n(o,a,u)},s.alloc=function(o,a,u){if(typeof o!="number")throw new TypeError("Argument must be a number");var h=n(o);return a!==void 0?typeof u=="string"?h.fill(a,u):h.fill(a):h.fill(0),h},s.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n(o)},s.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r.SlowBuffer(o)}})(ws,ws.exports);var Ve=ws.exports,Yi=65536,Ql=4294967295;function Zl(){throw new Error(`Secure random number generation is not supported by this browser.
|
|
31
|
+
Use Chrome, Firefox or Internet Explorer 11`)}var eh=Ve.Buffer,ei=Gt.crypto||Gt.msCrypto;ei&&ei.getRandomValues?bs.exports=th:bs.exports=Zl;function th(e,t){if(e>Ql)throw new RangeError("requested too many random bytes");var r=eh.allocUnsafe(e);if(e>0)if(e>Yi)for(var n=0;n<e;n+=Yi)ei.getRandomValues(r.slice(n,n+Yi));else ei.getRandomValues(r);return typeof t=="function"?process.nextTick(function(){t(null,r)}):r}var rh=bs.exports,gs={exports:{}};typeof Object.create=="function"?gs.exports=function(t,r){r&&(t.super_=r,t.prototype=Object.create(r.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:gs.exports=function(t,r){if(r){t.super_=r;var n=function(){};n.prototype=r.prototype,t.prototype=new n,t.prototype.constructor=t}};var Oe=gs.exports,_s={exports:{}},qs={exports:{}},Pr=typeof Reflect=="object"?Reflect:null,Co=Pr&&typeof Pr.apply=="function"?Pr.apply:function(t,r,n){return Function.prototype.apply.call(t,r,n)},Yn;Pr&&typeof Pr.ownKeys=="function"?Yn=Pr.ownKeys:Object.getOwnPropertySymbols?Yn=function(t){return Object.getOwnPropertyNames(t).concat(Object.getOwnPropertySymbols(t))}:Yn=function(t){return Object.getOwnPropertyNames(t)};function nh(e){console&&console.warn&&console.warn(e)}var ec=Number.isNaN||function(t){return t!==t};function se(){se.init.call(this)}qs.exports=se;qs.exports.once=ah;se.EventEmitter=se;se.prototype._events=void 0;se.prototype._eventsCount=0;se.prototype._maxListeners=void 0;var Uo=10;function wi(e){if(typeof e!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}Object.defineProperty(se,"defaultMaxListeners",{enumerable:!0,get:function(){return Uo},set:function(e){if(typeof e!="number"||e<0||ec(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");Uo=e}});se.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};se.prototype.setMaxListeners=function(t){if(typeof t!="number"||t<0||ec(t))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+t+".");return this._maxListeners=t,this};function tc(e){return e._maxListeners===void 0?se.defaultMaxListeners:e._maxListeners}se.prototype.getMaxListeners=function(){return tc(this)};se.prototype.emit=function(t){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=t==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var u=s[t];if(u===void 0)return!1;if(typeof u=="function")Co(u,this,r);else for(var h=u.length,d=oc(u,h),n=0;n<h;++n)Co(d[n],this,r);return!0};function rc(e,t,r,n){var i,s,o;if(wi(r),s=e._events,s===void 0?(s=e._events=Object.create(null),e._eventsCount=0):(s.newListener!==void 0&&(e.emit("newListener",t,r.listener?r.listener:r),s=e._events),o=s[t]),o===void 0)o=s[t]=r,++e._eventsCount;else if(typeof o=="function"?o=s[t]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=tc(e),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,nh(a)}return e}se.prototype.addListener=function(t,r){return rc(this,t,r,!1)};se.prototype.on=se.prototype.addListener;se.prototype.prependListener=function(t,r){return rc(this,t,r,!0)};function ih(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function nc(e,t,r){var n={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},i=ih.bind(n);return i.listener=r,n.wrapFn=i,i}se.prototype.once=function(t,r){return wi(r),this.on(t,nc(this,t,r)),this};se.prototype.prependOnceListener=function(t,r){return wi(r),this.prependListener(t,nc(this,t,r)),this};se.prototype.removeListener=function(t,r){var n,i,s,o,a;if(wi(r),i=this._events,i===void 0)return this;if(n=i[t],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[t],i.removeListener&&this.emit("removeListener",t,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():sh(n,s),n.length===1&&(i[t]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",t,a||r)}return this};se.prototype.off=se.prototype.removeListener;se.prototype.removeAllListeners=function(t){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[t]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[t]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[t],typeof r=="function")this.removeListener(t,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(t,r[i]);return this};function ic(e,t,r){var n=e._events;if(n===void 0)return[];var i=n[t];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?oh(i):oc(i,i.length)}se.prototype.listeners=function(t){return ic(this,t,!0)};se.prototype.rawListeners=function(t){return ic(this,t,!1)};se.listenerCount=function(e,t){return typeof e.listenerCount=="function"?e.listenerCount(t):sc.call(e,t)};se.prototype.listenerCount=sc;function sc(e){var t=this._events;if(t!==void 0){var r=t[e];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}se.prototype.eventNames=function(){return this._eventsCount>0?Yn(this._events):[]};function oc(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}function sh(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function oh(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}function ah(e,t){return new Promise(function(r,n){function i(o){e.removeListener(t,s),n(o)}function s(){typeof e.removeListener=="function"&&e.removeListener("error",i),r([].slice.call(arguments))}ac(e,t,s,{once:!0}),t!=="error"&&ch(e,i,{once:!0})})}function ch(e,t,r){typeof e.on=="function"&&ac(e,"error",t,r)}function ac(e,t,r,n){if(typeof e.on=="function")n.once?e.once(t,r):e.on(t,r);else if(typeof e.addEventListener=="function")e.addEventListener(t,function i(s){n.once&&e.removeEventListener(t,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}var cc=qs.exports,fc=cc.EventEmitter;const fh={},uh=Object.freeze(Object.defineProperty({__proto__:null,default:fh},Symbol.toStringTag,{value:"Module"})),Ws=_a(uh);var Xi,Lo;function lh(){if(Lo)return Xi;Lo=1;function e(I,k){var B=Object.keys(I);if(Object.getOwnPropertySymbols){var R=Object.getOwnPropertySymbols(I);k&&(R=R.filter(function(U){return Object.getOwnPropertyDescriptor(I,U).enumerable})),B.push.apply(B,R)}return B}function t(I){for(var k=1;k<arguments.length;k++){var B=arguments[k]!=null?arguments[k]:{};k%2?e(Object(B),!0).forEach(function(R){r(I,R,B[R])}):Object.getOwnPropertyDescriptors?Object.defineProperties(I,Object.getOwnPropertyDescriptors(B)):e(Object(B)).forEach(function(R){Object.defineProperty(I,R,Object.getOwnPropertyDescriptor(B,R))})}return I}function r(I,k,B){return k=o(k),k in I?Object.defineProperty(I,k,{value:B,enumerable:!0,configurable:!0,writable:!0}):I[k]=B,I}function n(I,k){if(!(I instanceof k))throw new TypeError("Cannot call a class as a function")}function i(I,k){for(var B=0;B<k.length;B++){var R=k[B];R.enumerable=R.enumerable||!1,R.configurable=!0,"value"in R&&(R.writable=!0),Object.defineProperty(I,o(R.key),R)}}function s(I,k,B){return k&&i(I.prototype,k),Object.defineProperty(I,"prototype",{writable:!1}),I}function o(I){var k=a(I,"string");return typeof k=="symbol"?k:String(k)}function a(I,k){if(typeof I!="object"||I===null)return I;var B=I[Symbol.toPrimitive];if(B!==void 0){var R=B.call(I,k);if(typeof R!="object")return R;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(I)}var u=Bt,h=u.Buffer,d=Ws,p=d.inspect,v=p&&p.custom||"inspect";function y(I,k,B){h.prototype.copy.call(I,k,B)}return Xi=function(){function I(){n(this,I),this.head=null,this.tail=null,this.length=0}return s(I,[{key:"push",value:function(B){var R={data:B,next:null};this.length>0?this.tail.next=R:this.head=R,this.tail=R,++this.length}},{key:"unshift",value:function(B){var R={data:B,next:this.head};this.length===0&&(this.tail=R),this.head=R,++this.length}},{key:"shift",value:function(){if(this.length!==0){var B=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,B}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(B){if(this.length===0)return"";for(var R=this.head,U=""+R.data;R=R.next;)U+=B+R.data;return U}},{key:"concat",value:function(B){if(this.length===0)return h.alloc(0);for(var R=h.allocUnsafe(B>>>0),U=this.head,x=0;U;)y(U.data,R,x),x+=U.data.length,U=U.next;return R}},{key:"consume",value:function(B,R){var U;return B<this.head.data.length?(U=this.head.data.slice(0,B),this.head.data=this.head.data.slice(B)):B===this.head.data.length?U=this.shift():U=R?this._getString(B):this._getBuffer(B),U}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(B){var R=this.head,U=1,x=R.data;for(B-=x.length;R=R.next;){var g=R.data,S=B>g.length?g.length:B;if(S===g.length?x+=g:x+=g.slice(0,B),B-=S,B===0){S===g.length?(++U,R.next?this.head=R.next:this.head=this.tail=null):(this.head=R,R.data=g.slice(S));break}++U}return this.length-=U,x}},{key:"_getBuffer",value:function(B){var R=h.allocUnsafe(B),U=this.head,x=1;for(U.data.copy(R),B-=U.data.length;U=U.next;){var g=U.data,S=B>g.length?g.length:B;if(g.copy(R,R.length-B,0,S),B-=S,B===0){S===g.length?(++x,U.next?this.head=U.next:this.head=this.tail=null):(this.head=U,U.data=g.slice(S));break}++x}return this.length-=x,R}},{key:v,value:function(B,R){return p(this,t(t({},R),{},{depth:0,customInspect:!1}))}}]),I}(),Xi}function hh(e,t){var r=this,n=this._readableState&&this._readableState.destroyed,i=this._writableState&&this._writableState.destroyed;return n||i?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(vs,this,e)):process.nextTick(vs,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(s){!t&&s?r._writableState?r._writableState.errorEmitted?process.nextTick(Xn,r):(r._writableState.errorEmitted=!0,process.nextTick(No,r,s)):process.nextTick(No,r,s):t?(process.nextTick(Xn,r),t(s)):process.nextTick(Xn,r)}),this)}function No(e,t){vs(e,t),Xn(e)}function Xn(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function dh(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function vs(e,t){e.emit("error",t)}function ph(e,t){var r=e._readableState,n=e._writableState;r&&r.autoDestroy||n&&n.autoDestroy?e.destroy(t):e.emit("error",t)}var uc={destroy:hh,undestroy:dh,errorOrDestroy:ph},pr={};function yh(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}var lc={};function et(e,t,r){r||(r=Error);function n(s,o,a){return typeof t=="string"?t:t(s,o,a)}var i=function(s){yh(o,s);function o(a,u,h){return s.call(this,n(a,u,h))||this}return o}(r);i.prototype.name=r.name,i.prototype.code=e,lc[e]=i}function Ho(e,t){if(Array.isArray(e)){var r=e.length;return e=e.map(function(n){return String(n)}),r>2?"one of ".concat(t," ").concat(e.slice(0,r-1).join(", "),", or ")+e[r-1]:r===2?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}else return"of ".concat(t," ").concat(String(e))}function mh(e,t,r){return e.substr(0,t.length)===t}function bh(e,t,r){return(r===void 0||r>e.length)&&(r=e.length),e.substring(r-t.length,r)===t}function wh(e,t,r){return typeof r!="number"&&(r=0),r+t.length>e.length?!1:e.indexOf(t,r)!==-1}et("ERR_INVALID_OPT_VALUE",function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'},TypeError);et("ERR_INVALID_ARG_TYPE",function(e,t,r){var n;typeof t=="string"&&mh(t,"not ")?(n="must not be",t=t.replace(/^not /,"")):n="must be";var i;if(bh(e," argument"))i="The ".concat(e," ").concat(n," ").concat(Ho(t,"type"));else{var s=wh(e,".")?"property":"argument";i='The "'.concat(e,'" ').concat(s," ").concat(n," ").concat(Ho(t,"type"))}return i+=". Received type ".concat(typeof r),i},TypeError);et("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF");et("ERR_METHOD_NOT_IMPLEMENTED",function(e){return"The "+e+" method is not implemented"});et("ERR_STREAM_PREMATURE_CLOSE","Premature close");et("ERR_STREAM_DESTROYED",function(e){return"Cannot call "+e+" after a stream was destroyed"});et("ERR_MULTIPLE_CALLBACK","Callback called multiple times");et("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable");et("ERR_STREAM_WRITE_AFTER_END","write after end");et("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError);et("ERR_UNKNOWN_ENCODING",function(e){return"Unknown encoding: "+e},TypeError);et("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event");pr.codes=lc;var gh=pr.codes.ERR_INVALID_OPT_VALUE;function _h(e,t,r){return e.highWaterMark!=null?e.highWaterMark:t?e[r]:null}function vh(e,t,r,n){var i=_h(t,n,r);if(i!=null){if(!(isFinite(i)&&Math.floor(i)===i)||i<0){var s=n?r:"highWaterMark";throw new gh(s,i)}return Math.floor(i)}return e.objectMode?16:16*1024}var hc={getHighWaterMark:vh},Eh=xh;function xh(e,t){if(Ji("noDeprecation"))return e;var r=!1;function n(){if(!r){if(Ji("throwDeprecation"))throw new Error(t);Ji("traceDeprecation")?console.trace(t):console.warn(t),r=!0}return e.apply(this,arguments)}return n}function Ji(e){try{if(!Gt.localStorage)return!1}catch{return!1}var t=Gt.localStorage[e];return t==null?!1:String(t).toLowerCase()==="true"}var Qi,Fo;function dc(){if(Fo)return Qi;Fo=1,Qi=D;function e(A){var T=this;this.next=null,this.entry=null,this.finish=function(){yt(T,A)}}var t;D.WritableState=E;var r={deprecate:Eh},n=fc,i=Bt.Buffer,s=(typeof Gt<"u"?Gt:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function o(A){return i.from(A)}function a(A){return i.isBuffer(A)||A instanceof s}var u=uc,h=hc,d=h.getHighWaterMark,p=pr.codes,v=p.ERR_INVALID_ARG_TYPE,y=p.ERR_METHOD_NOT_IMPLEMENTED,I=p.ERR_MULTIPLE_CALLBACK,k=p.ERR_STREAM_CANNOT_PIPE,B=p.ERR_STREAM_DESTROYED,R=p.ERR_STREAM_NULL_VALUES,U=p.ERR_STREAM_WRITE_AFTER_END,x=p.ERR_UNKNOWN_ENCODING,g=u.errorOrDestroy;Oe(D,n);function S(){}function E(A,T,H){t=t||Hr(),A=A||{},typeof H!="boolean"&&(H=T instanceof t),this.objectMode=!!A.objectMode,H&&(this.objectMode=this.objectMode||!!A.writableObjectMode),this.highWaterMark=d(this,A,"writableHighWaterMark",H),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var q=A.decodeStrings===!1;this.decodeStrings=!q,this.defaultEncoding=A.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(Y){ve(T,Y)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=A.emitClose!==!1,this.autoDestroy=!!A.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new e(this)}E.prototype.getBuffer=function(){for(var T=this.bufferedRequest,H=[];T;)H.push(T),T=T.next;return H},function(){try{Object.defineProperty(E.prototype,"buffer",{get:r.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}}();var F;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(F=Function.prototype[Symbol.hasInstance],Object.defineProperty(D,Symbol.hasInstance,{value:function(T){return F.call(this,T)?!0:this!==D?!1:T&&T._writableState instanceof E}})):F=function(T){return T instanceof this};function D(A){t=t||Hr();var T=this instanceof t;if(!T&&!F.call(D,this))return new D(A);this._writableState=new E(A,this,T),this.writable=!0,A&&(typeof A.write=="function"&&(this._write=A.write),typeof A.writev=="function"&&(this._writev=A.writev),typeof A.destroy=="function"&&(this._destroy=A.destroy),typeof A.final=="function"&&(this._final=A.final)),n.call(this)}D.prototype.pipe=function(){g(this,new k)};function O(A,T){var H=new U;g(A,H),process.nextTick(T,H)}function K(A,T,H,q){var Y;return H===null?Y=new R:typeof H!="string"&&!T.objectMode&&(Y=new v("chunk",["string","Buffer"],H)),Y?(g(A,Y),process.nextTick(q,Y),!1):!0}D.prototype.write=function(A,T,H){var q=this._writableState,Y=!1,b=!q.objectMode&&a(A);return b&&!i.isBuffer(A)&&(A=o(A)),typeof T=="function"&&(H=T,T=null),b?T="buffer":T||(T=q.defaultEncoding),typeof H!="function"&&(H=S),q.ending?O(this,H):(b||K(this,q,A,H))&&(q.pendingcb++,Y=G(this,q,b,A,T,H)),Y},D.prototype.cork=function(){this._writableState.corked++},D.prototype.uncork=function(){var A=this._writableState;A.corked&&(A.corked--,!A.writing&&!A.corked&&!A.bufferProcessing&&A.bufferedRequest&&qe(this,A))},D.prototype.setDefaultEncoding=function(T){if(typeof T=="string"&&(T=T.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((T+"").toLowerCase())>-1))throw new x(T);return this._writableState.defaultEncoding=T,this},Object.defineProperty(D.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function C(A,T,H){return!A.objectMode&&A.decodeStrings!==!1&&typeof T=="string"&&(T=i.from(T,H)),T}Object.defineProperty(D.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function G(A,T,H,q,Y,b){if(!H){var w=C(T,q,Y);q!==w&&(H=!0,Y="buffer",q=w)}var N=T.objectMode?1:q.length;T.length+=N;var $=T.length<T.highWaterMark;if($||(T.needDrain=!0),T.writing||T.corked){var ye=T.lastBufferedRequest;T.lastBufferedRequest={chunk:q,encoding:Y,isBuf:H,callback:b,next:null},ye?ye.next=T.lastBufferedRequest:T.bufferedRequest=T.lastBufferedRequest,T.bufferedRequestCount+=1}else V(A,T,!1,N,q,Y,b);return $}function V(A,T,H,q,Y,b,w){T.writelen=q,T.writecb=w,T.writing=!0,T.sync=!0,T.destroyed?T.onwrite(new B("write")):H?A._writev(Y,T.onwrite):A._write(Y,b,T.onwrite),T.sync=!1}function z(A,T,H,q,Y){--T.pendingcb,H?(process.nextTick(Y,q),process.nextTick(We,A,T),A._writableState.errorEmitted=!0,g(A,q)):(Y(q),A._writableState.errorEmitted=!0,g(A,q),We(A,T))}function ee(A){A.writing=!1,A.writecb=null,A.length-=A.writelen,A.writelen=0}function ve(A,T){var H=A._writableState,q=H.sync,Y=H.writecb;if(typeof Y!="function")throw new I;if(ee(H),T)z(A,H,q,T,Y);else{var b=It(H)||A.destroyed;!b&&!H.corked&&!H.bufferProcessing&&H.bufferedRequest&&qe(A,H),q?process.nextTick(ze,A,H,b,Y):ze(A,H,b,Y)}}function ze(A,T,H,q){H||tt(A,T),T.pendingcb--,q(),We(A,T)}function tt(A,T){T.length===0&&T.needDrain&&(T.needDrain=!1,A.emit("drain"))}function qe(A,T){T.bufferProcessing=!0;var H=T.bufferedRequest;if(A._writev&&H&&H.next){var q=T.bufferedRequestCount,Y=new Array(q),b=T.corkedRequestsFree;b.entry=H;for(var w=0,N=!0;H;)Y[w]=H,H.isBuf||(N=!1),H=H.next,w+=1;Y.allBuffers=N,V(A,T,!0,T.length,Y,"",b.finish),T.pendingcb++,T.lastBufferedRequest=null,b.next?(T.corkedRequestsFree=b.next,b.next=null):T.corkedRequestsFree=new e(T),T.bufferedRequestCount=0}else{for(;H;){var $=H.chunk,ye=H.encoding,X=H.callback,ne=T.objectMode?1:$.length;if(V(A,T,!1,ne,$,ye,X),H=H.next,T.bufferedRequestCount--,T.writing)break}H===null&&(T.lastBufferedRequest=null)}T.bufferedRequest=H,T.bufferProcessing=!1}D.prototype._write=function(A,T,H){H(new y("_write()"))},D.prototype._writev=null,D.prototype.end=function(A,T,H){var q=this._writableState;return typeof A=="function"?(H=A,A=null,T=null):typeof T=="function"&&(H=T,T=null),A!=null&&this.write(A,T),q.corked&&(q.corked=1,this.uncork()),q.ending||Pt(this,q,H),this},Object.defineProperty(D.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function It(A){return A.ending&&A.length===0&&A.bufferedRequest===null&&!A.finished&&!A.writing}function pe(A,T){A._final(function(H){T.pendingcb--,H&&g(A,H),T.prefinished=!0,A.emit("prefinish"),We(A,T)})}function Ee(A,T){!T.prefinished&&!T.finalCalled&&(typeof A._final=="function"&&!T.destroyed?(T.pendingcb++,T.finalCalled=!0,process.nextTick(pe,A,T)):(T.prefinished=!0,A.emit("prefinish")))}function We(A,T){var H=It(T);if(H&&(Ee(A,T),T.pendingcb===0&&(T.finished=!0,A.emit("finish"),T.autoDestroy))){var q=A._readableState;(!q||q.autoDestroy&&q.endEmitted)&&A.destroy()}return H}function Pt(A,T,H){T.ending=!0,We(A,T),H&&(T.finished?process.nextTick(H):A.once("finish",H)),T.ended=!0,A.writable=!1}function yt(A,T,H){var q=A.entry;for(A.entry=null;q;){var Y=q.callback;T.pendingcb--,Y(H),q=q.next}T.corkedRequestsFree.next=A}return Object.defineProperty(D.prototype,"destroyed",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(T){this._writableState&&(this._writableState.destroyed=T)}}),D.prototype.destroy=u.destroy,D.prototype._undestroy=u.undestroy,D.prototype._destroy=function(A,T){T(A)},Qi}var Zi,Mo;function Hr(){if(Mo)return Zi;Mo=1;var e=Object.keys||function(h){var d=[];for(var p in h)d.push(p);return d};Zi=o;var t=yc(),r=dc();Oe(o,t);for(var n=e(r.prototype),i=0;i<n.length;i++){var s=n[i];o.prototype[s]||(o.prototype[s]=r.prototype[s])}function o(h){if(!(this instanceof o))return new o(h);t.call(this,h),r.call(this,h),this.allowHalfOpen=!0,h&&(h.readable===!1&&(this.readable=!1),h.writable===!1&&(this.writable=!1),h.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once("end",a)))}Object.defineProperty(o.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(o.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(o.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}});function a(){this._writableState.ended||process.nextTick(u,this)}function u(h){h.end()}return Object.defineProperty(o.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(d){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=d,this._writableState.destroyed=d)}}),Zi}var ti={},Ks=Ve.Buffer,Do=Ks.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function Sh(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function Th(e){var t=Sh(e);if(typeof t!="string"&&(Ks.isEncoding===Do||!Do(e)))throw new Error("Unknown encoding: "+e);return t||e}ti.StringDecoder=vn;function vn(e){this.encoding=Th(e);var t;switch(this.encoding){case"utf16le":this.text=Oh,this.end=Rh,t=4;break;case"utf8":this.fillLast=Bh,t=4;break;case"base64":this.text=Ch,this.end=Uh,t=3;break;default:this.write=Lh,this.end=Nh;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Ks.allocUnsafe(t)}vn.prototype.write=function(e){if(e.length===0)return"";var t,r;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";r=this.lastNeed,this.lastNeed=0}else r=0;return r<e.length?t?t+this.text(e,r):this.text(e,r):t||""};vn.prototype.end=Ph;vn.prototype.text=Ih;vn.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function es(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function Ah(e,t,r){var n=t.length-1;if(n<r)return 0;var i=es(t[n]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--n<r||i===-2?0:(i=es(t[n]),i>=0?(i>0&&(e.lastNeed=i-2),i):--n<r||i===-2?0:(i=es(t[n]),i>=0?(i>0&&(i===2?i=0:e.lastNeed=i-3),i):0))}function kh(e,t,r){if((t[0]&192)!==128)return e.lastNeed=0,"�";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"�";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"�"}}function Bh(e){var t=this.lastTotal-this.lastNeed,r=kh(this,e);if(r!==void 0)return r;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function Ih(e,t){var r=Ah(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=r;var n=e.length-(r-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function Ph(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"�":t}function Oh(e,t){if((e.length-t)%2===0){var r=e.toString("utf16le",t);if(r){var n=r.charCodeAt(r.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function Rh(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,r)}return t}function Ch(e,t){var r=(e.length-t)%3;return r===0?e.toString("base64",t):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-r))}function Uh(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function Lh(e){return e.toString(this.encoding)}function Nh(e){return e&&e.length?this.write(e):""}var $o=pr.codes.ERR_STREAM_PREMATURE_CLOSE;function Hh(e){var t=!1;return function(){if(!t){t=!0;for(var r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];e.apply(this,n)}}}function Fh(){}function Mh(e){return e.setHeader&&typeof e.abort=="function"}function pc(e,t,r){if(typeof t=="function")return pc(e,null,t);t||(t={}),r=Hh(r||Fh);var n=t.readable||t.readable!==!1&&e.readable,i=t.writable||t.writable!==!1&&e.writable,s=function(){e.writable||a()},o=e._writableState&&e._writableState.finished,a=function(){i=!1,o=!0,n||r.call(e)},u=e._readableState&&e._readableState.endEmitted,h=function(){n=!1,u=!0,i||r.call(e)},d=function(I){r.call(e,I)},p=function(){var I;if(n&&!u)return(!e._readableState||!e._readableState.ended)&&(I=new $o),r.call(e,I);if(i&&!o)return(!e._writableState||!e._writableState.ended)&&(I=new $o),r.call(e,I)},v=function(){e.req.on("finish",a)};return Mh(e)?(e.on("complete",a),e.on("abort",p),e.req?v():e.on("request",v)):i&&!e._writableState&&(e.on("end",s),e.on("close",s)),e.on("end",h),e.on("finish",a),t.error!==!1&&e.on("error",d),e.on("close",p),function(){e.removeListener("complete",a),e.removeListener("abort",p),e.removeListener("request",v),e.req&&e.req.removeListener("finish",a),e.removeListener("end",s),e.removeListener("close",s),e.removeListener("finish",a),e.removeListener("end",h),e.removeListener("error",d),e.removeListener("close",p)}}var Ys=pc,ts,jo;function Dh(){if(jo)return ts;jo=1;var e;function t(x,g,S){return g=r(g),g in x?Object.defineProperty(x,g,{value:S,enumerable:!0,configurable:!0,writable:!0}):x[g]=S,x}function r(x){var g=n(x,"string");return typeof g=="symbol"?g:String(g)}function n(x,g){if(typeof x!="object"||x===null)return x;var S=x[Symbol.toPrimitive];if(S!==void 0){var E=S.call(x,g);if(typeof E!="object")return E;throw new TypeError("@@toPrimitive must return a primitive value.")}return(g==="string"?String:Number)(x)}var i=Ys,s=Symbol("lastResolve"),o=Symbol("lastReject"),a=Symbol("error"),u=Symbol("ended"),h=Symbol("lastPromise"),d=Symbol("handlePromise"),p=Symbol("stream");function v(x,g){return{value:x,done:g}}function y(x){var g=x[s];if(g!==null){var S=x[p].read();S!==null&&(x[h]=null,x[s]=null,x[o]=null,g(v(S,!1)))}}function I(x){process.nextTick(y,x)}function k(x,g){return function(S,E){x.then(function(){if(g[u]){S(v(void 0,!0));return}g[d](S,E)},E)}}var B=Object.getPrototypeOf(function(){}),R=Object.setPrototypeOf((e={get stream(){return this[p]},next:function(){var g=this,S=this[a];if(S!==null)return Promise.reject(S);if(this[u])return Promise.resolve(v(void 0,!0));if(this[p].destroyed)return new Promise(function(O,K){process.nextTick(function(){g[a]?K(g[a]):O(v(void 0,!0))})});var E=this[h],F;if(E)F=new Promise(k(E,this));else{var D=this[p].read();if(D!==null)return Promise.resolve(v(D,!1));F=new Promise(this[d])}return this[h]=F,F}},t(e,Symbol.asyncIterator,function(){return this}),t(e,"return",function(){var g=this;return new Promise(function(S,E){g[p].destroy(null,function(F){if(F){E(F);return}S(v(void 0,!0))})})}),e),B),U=function(g){var S,E=Object.create(R,(S={},t(S,p,{value:g,writable:!0}),t(S,s,{value:null,writable:!0}),t(S,o,{value:null,writable:!0}),t(S,a,{value:null,writable:!0}),t(S,u,{value:g._readableState.endEmitted,writable:!0}),t(S,d,{value:function(D,O){var K=E[p].read();K?(E[h]=null,E[s]=null,E[o]=null,D(v(K,!1))):(E[s]=D,E[o]=O)},writable:!0}),S));return E[h]=null,i(g,function(F){if(F&&F.code!=="ERR_STREAM_PREMATURE_CLOSE"){var D=E[o];D!==null&&(E[h]=null,E[s]=null,E[o]=null,D(F)),E[a]=F;return}var O=E[s];O!==null&&(E[h]=null,E[s]=null,E[o]=null,O(v(void 0,!0))),E[u]=!0}),g.on("readable",I.bind(null,E)),E};return ts=U,ts}var rs,Go;function $h(){return Go||(Go=1,rs=function(){throw new Error("Readable.from is not available in the browser")}),rs}var ns,Vo;function yc(){if(Vo)return ns;Vo=1,ns=O;var e;O.ReadableState=D,cc.EventEmitter;var t=function(w,N){return w.listeners(N).length},r=fc,n=Bt.Buffer,i=(typeof Gt<"u"?Gt:typeof window<"u"?window:typeof self<"u"?self:{}).Uint8Array||function(){};function s(b){return n.from(b)}function o(b){return n.isBuffer(b)||b instanceof i}var a=Ws,u;a&&a.debuglog?u=a.debuglog("stream"):u=function(){};var h=lh(),d=uc,p=hc,v=p.getHighWaterMark,y=pr.codes,I=y.ERR_INVALID_ARG_TYPE,k=y.ERR_STREAM_PUSH_AFTER_EOF,B=y.ERR_METHOD_NOT_IMPLEMENTED,R=y.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,U,x,g;Oe(O,r);var S=d.errorOrDestroy,E=["error","close","destroy","pause","resume"];function F(b,w,N){if(typeof b.prependListener=="function")return b.prependListener(w,N);!b._events||!b._events[w]?b.on(w,N):Array.isArray(b._events[w])?b._events[w].unshift(N):b._events[w]=[N,b._events[w]]}function D(b,w,N){e=e||Hr(),b=b||{},typeof N!="boolean"&&(N=w instanceof e),this.objectMode=!!b.objectMode,N&&(this.objectMode=this.objectMode||!!b.readableObjectMode),this.highWaterMark=v(this,b,"readableHighWaterMark",N),this.buffer=new h,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=b.emitClose!==!1,this.autoDestroy=!!b.autoDestroy,this.destroyed=!1,this.defaultEncoding=b.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,b.encoding&&(U||(U=ti.StringDecoder),this.decoder=new U(b.encoding),this.encoding=b.encoding)}function O(b){if(e=e||Hr(),!(this instanceof O))return new O(b);var w=this instanceof e;this._readableState=new D(b,this,w),this.readable=!0,b&&(typeof b.read=="function"&&(this._read=b.read),typeof b.destroy=="function"&&(this._destroy=b.destroy)),r.call(this)}Object.defineProperty(O.prototype,"destroyed",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(w){this._readableState&&(this._readableState.destroyed=w)}}),O.prototype.destroy=d.destroy,O.prototype._undestroy=d.undestroy,O.prototype._destroy=function(b,w){w(b)},O.prototype.push=function(b,w){var N=this._readableState,$;return N.objectMode?$=!0:typeof b=="string"&&(w=w||N.defaultEncoding,w!==N.encoding&&(b=n.from(b,w),w=""),$=!0),K(this,b,w,!1,$)},O.prototype.unshift=function(b){return K(this,b,null,!0,!1)};function K(b,w,N,$,ye){u("readableAddChunk",w);var X=b._readableState;if(w===null)X.reading=!1,ve(b,X);else{var ne;if(ye||(ne=G(X,w)),ne)S(b,ne);else if(X.objectMode||w&&w.length>0)if(typeof w!="string"&&!X.objectMode&&Object.getPrototypeOf(w)!==n.prototype&&(w=s(w)),$)X.endEmitted?S(b,new R):C(b,X,w,!0);else if(X.ended)S(b,new k);else{if(X.destroyed)return!1;X.reading=!1,X.decoder&&!N?(w=X.decoder.write(w),X.objectMode||w.length!==0?C(b,X,w,!1):qe(b,X)):C(b,X,w,!1)}else $||(X.reading=!1,qe(b,X))}return!X.ended&&(X.length<X.highWaterMark||X.length===0)}function C(b,w,N,$){w.flowing&&w.length===0&&!w.sync?(w.awaitDrain=0,b.emit("data",N)):(w.length+=w.objectMode?1:N.length,$?w.buffer.unshift(N):w.buffer.push(N),w.needReadable&&ze(b)),qe(b,w)}function G(b,w){var N;return!o(w)&&typeof w!="string"&&w!==void 0&&!b.objectMode&&(N=new I("chunk",["string","Buffer","Uint8Array"],w)),N}O.prototype.isPaused=function(){return this._readableState.flowing===!1},O.prototype.setEncoding=function(b){U||(U=ti.StringDecoder);var w=new U(b);this._readableState.decoder=w,this._readableState.encoding=this._readableState.decoder.encoding;for(var N=this._readableState.buffer.head,$="";N!==null;)$+=w.write(N.data),N=N.next;return this._readableState.buffer.clear(),$!==""&&this._readableState.buffer.push($),this._readableState.length=$.length,this};var V=1073741824;function z(b){return b>=V?b=V:(b--,b|=b>>>1,b|=b>>>2,b|=b>>>4,b|=b>>>8,b|=b>>>16,b++),b}function ee(b,w){return b<=0||w.length===0&&w.ended?0:w.objectMode?1:b!==b?w.flowing&&w.length?w.buffer.head.data.length:w.length:(b>w.highWaterMark&&(w.highWaterMark=z(b)),b<=w.length?b:w.ended?w.length:(w.needReadable=!0,0))}O.prototype.read=function(b){u("read",b),b=parseInt(b,10);var w=this._readableState,N=b;if(b!==0&&(w.emittedReadable=!1),b===0&&w.needReadable&&((w.highWaterMark!==0?w.length>=w.highWaterMark:w.length>0)||w.ended))return u("read: emitReadable",w.length,w.ended),w.length===0&&w.ended?H(this):ze(this),null;if(b=ee(b,w),b===0&&w.ended)return w.length===0&&H(this),null;var $=w.needReadable;u("need readable",$),(w.length===0||w.length-b<w.highWaterMark)&&($=!0,u("length less than watermark",$)),w.ended||w.reading?($=!1,u("reading or ended",$)):$&&(u("do read"),w.reading=!0,w.sync=!0,w.length===0&&(w.needReadable=!0),this._read(w.highWaterMark),w.sync=!1,w.reading||(b=ee(N,w)));var ye;return b>0?ye=T(b,w):ye=null,ye===null?(w.needReadable=w.length<=w.highWaterMark,b=0):(w.length-=b,w.awaitDrain=0),w.length===0&&(w.ended||(w.needReadable=!0),N!==b&&w.ended&&H(this)),ye!==null&&this.emit("data",ye),ye};function ve(b,w){if(u("onEofChunk"),!w.ended){if(w.decoder){var N=w.decoder.end();N&&N.length&&(w.buffer.push(N),w.length+=w.objectMode?1:N.length)}w.ended=!0,w.sync?ze(b):(w.needReadable=!1,w.emittedReadable||(w.emittedReadable=!0,tt(b)))}}function ze(b){var w=b._readableState;u("emitReadable",w.needReadable,w.emittedReadable),w.needReadable=!1,w.emittedReadable||(u("emitReadable",w.flowing),w.emittedReadable=!0,process.nextTick(tt,b))}function tt(b){var w=b._readableState;u("emitReadable_",w.destroyed,w.length,w.ended),!w.destroyed&&(w.length||w.ended)&&(b.emit("readable"),w.emittedReadable=!1),w.needReadable=!w.flowing&&!w.ended&&w.length<=w.highWaterMark,A(b)}function qe(b,w){w.readingMore||(w.readingMore=!0,process.nextTick(It,b,w))}function It(b,w){for(;!w.reading&&!w.ended&&(w.length<w.highWaterMark||w.flowing&&w.length===0);){var N=w.length;if(u("maybeReadMore read 0"),b.read(0),N===w.length)break}w.readingMore=!1}O.prototype._read=function(b){S(this,new B("_read()"))},O.prototype.pipe=function(b,w){var N=this,$=this._readableState;switch($.pipesCount){case 0:$.pipes=b;break;case 1:$.pipes=[$.pipes,b];break;default:$.pipes.push(b);break}$.pipesCount+=1,u("pipe count=%d opts=%j",$.pipesCount,w);var ye=(!w||w.end!==!1)&&b!==process.stdout&&b!==process.stderr,X=ye?Ot:Qt;$.endEmitted?process.nextTick(X):N.once("end",X),b.on("unpipe",ne);function ne(l,c){u("onunpipe"),l===N&&c&&c.hasUnpiped===!1&&(c.hasUnpiped=!0,br())}function Ot(){u("onend"),b.end()}var mr=pe(N);b.on("drain",mr);var jr=!1;function br(){u("cleanup"),b.removeListener("close",Gr),b.removeListener("finish",Je),b.removeListener("drain",mr),b.removeListener("error",Jt),b.removeListener("unpipe",ne),N.removeListener("end",Ot),N.removeListener("end",Qt),N.removeListener("data",Ke),jr=!0,$.awaitDrain&&(!b._writableState||b._writableState.needDrain)&&mr()}N.on("data",Ke);function Ke(l){u("ondata");var c=b.write(l);u("dest.write",c),c===!1&&(($.pipesCount===1&&$.pipes===b||$.pipesCount>1&&Y($.pipes,b)!==-1)&&!jr&&(u("false write response, pause",$.awaitDrain),$.awaitDrain++),N.pause())}function Jt(l){u("onerror",l),Qt(),b.removeListener("error",Jt),t(b,"error")===0&&S(b,l)}F(b,"error",Jt);function Gr(){b.removeListener("finish",Je),Qt()}b.once("close",Gr);function Je(){u("onfinish"),b.removeListener("close",Gr),Qt()}b.once("finish",Je);function Qt(){u("unpipe"),N.unpipe(b)}return b.emit("pipe",N),$.flowing||(u("pipe resume"),N.resume()),b};function pe(b){return function(){var N=b._readableState;u("pipeOnDrain",N.awaitDrain),N.awaitDrain&&N.awaitDrain--,N.awaitDrain===0&&t(b,"data")&&(N.flowing=!0,A(b))}}O.prototype.unpipe=function(b){var w=this._readableState,N={hasUnpiped:!1};if(w.pipesCount===0)return this;if(w.pipesCount===1)return b&&b!==w.pipes?this:(b||(b=w.pipes),w.pipes=null,w.pipesCount=0,w.flowing=!1,b&&b.emit("unpipe",this,N),this);if(!b){var $=w.pipes,ye=w.pipesCount;w.pipes=null,w.pipesCount=0,w.flowing=!1;for(var X=0;X<ye;X++)$[X].emit("unpipe",this,{hasUnpiped:!1});return this}var ne=Y(w.pipes,b);return ne===-1?this:(w.pipes.splice(ne,1),w.pipesCount-=1,w.pipesCount===1&&(w.pipes=w.pipes[0]),b.emit("unpipe",this,N),this)},O.prototype.on=function(b,w){var N=r.prototype.on.call(this,b,w),$=this._readableState;return b==="data"?($.readableListening=this.listenerCount("readable")>0,$.flowing!==!1&&this.resume()):b==="readable"&&!$.endEmitted&&!$.readableListening&&($.readableListening=$.needReadable=!0,$.flowing=!1,$.emittedReadable=!1,u("on readable",$.length,$.reading),$.length?ze(this):$.reading||process.nextTick(We,this)),N},O.prototype.addListener=O.prototype.on,O.prototype.removeListener=function(b,w){var N=r.prototype.removeListener.call(this,b,w);return b==="readable"&&process.nextTick(Ee,this),N},O.prototype.removeAllListeners=function(b){var w=r.prototype.removeAllListeners.apply(this,arguments);return(b==="readable"||b===void 0)&&process.nextTick(Ee,this),w};function Ee(b){var w=b._readableState;w.readableListening=b.listenerCount("readable")>0,w.resumeScheduled&&!w.paused?w.flowing=!0:b.listenerCount("data")>0&&b.resume()}function We(b){u("readable nexttick read 0"),b.read(0)}O.prototype.resume=function(){var b=this._readableState;return b.flowing||(u("resume"),b.flowing=!b.readableListening,Pt(this,b)),b.paused=!1,this};function Pt(b,w){w.resumeScheduled||(w.resumeScheduled=!0,process.nextTick(yt,b,w))}function yt(b,w){u("resume",w.reading),w.reading||b.read(0),w.resumeScheduled=!1,b.emit("resume"),A(b),w.flowing&&!w.reading&&b.read(0)}O.prototype.pause=function(){return u("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&(u("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this};function A(b){var w=b._readableState;for(u("flow",w.flowing);w.flowing&&b.read()!==null;);}O.prototype.wrap=function(b){var w=this,N=this._readableState,$=!1;b.on("end",function(){if(u("wrapped end"),N.decoder&&!N.ended){var ne=N.decoder.end();ne&&ne.length&&w.push(ne)}w.push(null)}),b.on("data",function(ne){if(u("wrapped data"),N.decoder&&(ne=N.decoder.write(ne)),!(N.objectMode&&ne==null)&&!(!N.objectMode&&(!ne||!ne.length))){var Ot=w.push(ne);Ot||($=!0,b.pause())}});for(var ye in b)this[ye]===void 0&&typeof b[ye]=="function"&&(this[ye]=function(Ot){return function(){return b[Ot].apply(b,arguments)}}(ye));for(var X=0;X<E.length;X++)b.on(E[X],this.emit.bind(this,E[X]));return this._read=function(ne){u("wrapped _read",ne),$&&($=!1,b.resume())},this},typeof Symbol=="function"&&(O.prototype[Symbol.asyncIterator]=function(){return x===void 0&&(x=Dh()),x(this)}),Object.defineProperty(O.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(O.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(O.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(w){this._readableState&&(this._readableState.flowing=w)}}),O._fromList=T,Object.defineProperty(O.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}});function T(b,w){if(w.length===0)return null;var N;return w.objectMode?N=w.buffer.shift():!b||b>=w.length?(w.decoder?N=w.buffer.join(""):w.buffer.length===1?N=w.buffer.first():N=w.buffer.concat(w.length),w.buffer.clear()):N=w.buffer.consume(b,w.decoder),N}function H(b){var w=b._readableState;u("endReadable",w.endEmitted),w.endEmitted||(w.ended=!0,process.nextTick(q,w,b))}function q(b,w){if(u("endReadableNT",b.endEmitted,b.length),!b.endEmitted&&b.length===0&&(b.endEmitted=!0,w.readable=!1,w.emit("end"),b.autoDestroy)){var N=w._writableState;(!N||N.autoDestroy&&N.finished)&&w.destroy()}}typeof Symbol=="function"&&(O.from=function(b,w){return g===void 0&&(g=$h()),g(O,b,w)});function Y(b,w){for(var N=0,$=b.length;N<$;N++)if(b[N]===w)return N;return-1}return ns}var mc=kt,gi=pr.codes,jh=gi.ERR_METHOD_NOT_IMPLEMENTED,Gh=gi.ERR_MULTIPLE_CALLBACK,Vh=gi.ERR_TRANSFORM_ALREADY_TRANSFORMING,zh=gi.ERR_TRANSFORM_WITH_LENGTH_0,_i=Hr();Oe(kt,_i);function qh(e,t){var r=this._transformState;r.transforming=!1;var n=r.writecb;if(n===null)return this.emit("error",new Gh);r.writechunk=null,r.writecb=null,t!=null&&this.push(t),n(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function kt(e){if(!(this instanceof kt))return new kt(e);_i.call(this,e),this._transformState={afterTransform:qh.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",Wh)}function Wh(){var e=this;typeof this._flush=="function"&&!this._readableState.destroyed?this._flush(function(t,r){zo(e,t,r)}):zo(this,null,null)}kt.prototype.push=function(e,t){return this._transformState.needTransform=!1,_i.prototype.push.call(this,e,t)};kt.prototype._transform=function(e,t,r){r(new jh("_transform()"))};kt.prototype._write=function(e,t,r){var n=this._transformState;if(n.writecb=r,n.writechunk=e,n.writeencoding=t,!n.transforming){var i=this._readableState;(n.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}};kt.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};kt.prototype._destroy=function(e,t){_i.prototype._destroy.call(this,e,function(r){t(r)})};function zo(e,t,r){if(t)return e.emit("error",t);if(r!=null&&e.push(r),e._writableState.length)throw new zh;if(e._transformState.transforming)throw new Vh;return e.push(null)}var Kh=mn,bc=mc;Oe(mn,bc);function mn(e){if(!(this instanceof mn))return new mn(e);bc.call(this,e)}mn.prototype._transform=function(e,t,r){r(null,e)};var is;function Yh(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}var wc=pr.codes,Xh=wc.ERR_MISSING_ARGS,Jh=wc.ERR_STREAM_DESTROYED;function qo(e){if(e)throw e}function Qh(e){return e.setHeader&&typeof e.abort=="function"}function Zh(e,t,r,n){n=Yh(n);var i=!1;e.on("close",function(){i=!0}),is===void 0&&(is=Ys),is(e,{readable:t,writable:r},function(o){if(o)return n(o);i=!0,n()});var s=!1;return function(o){if(!i&&!s){if(s=!0,Qh(e))return e.abort();if(typeof e.destroy=="function")return e.destroy();n(o||new Jh("pipe"))}}}function Wo(e){e()}function ed(e,t){return e.pipe(t)}function td(e){return!e.length||typeof e[e.length-1]!="function"?qo:e.pop()}function rd(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=td(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new Xh("streams");var i,s=t.map(function(o,a){var u=a<t.length-1,h=a>0;return Zh(o,u,h,function(d){i||(i=d),d&&s.forEach(Wo),!u&&(s.forEach(Wo),n(i))})});return t.reduce(ed)}var nd=rd;(function(e,t){t=e.exports=yc(),t.Stream=t,t.Readable=t,t.Writable=dc(),t.Duplex=Hr(),t.Transform=mc,t.PassThrough=Kh,t.finished=Ys,t.pipeline=nd})(_s,_s.exports);var gc=_s.exports,ri=Ve.Buffer,_c=gc.Transform,id=Oe;function sd(e,t){if(!ri.isBuffer(e)&&typeof e!="string")throw new TypeError(t+" must be a string or a buffer")}function Kt(e){_c.call(this),this._block=ri.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}id(Kt,_c);Kt.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(i){n=i}r(n)};Kt.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(r){t=r}e(t)};Kt.prototype.update=function(e,t){if(sd(e,"Data"),this._finalized)throw new Error("Digest already called");ri.isBuffer(e)||(e=ri.from(e,t));for(var r=this._block,n=0;this._blockOffset+e.length-n>=this._blockSize;){for(var i=this._blockOffset;i<this._blockSize;)r[i++]=e[n++];this._update(),this._blockOffset=0}for(;n<e.length;)r[this._blockOffset++]=e[n++];for(var s=0,o=e.length*8;o>0;++s)this._length[s]+=o,o=this._length[s]/4294967296|0,o>0&&(this._length[s]-=4294967296*o);return this};Kt.prototype._update=function(){throw new Error("_update is not implemented")};Kt.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();e!==void 0&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t};Kt.prototype._digest=function(){throw new Error("_digest is not implemented")};var od=Kt,ad=Oe,vc=od,cd=Ve.Buffer,fd=new Array(16);function vi(){vc.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878}ad(vi,vc);vi.prototype._update=function(){for(var e=fd,t=0;t<16;++t)e[t]=this._block.readInt32LE(t*4);var r=this._a,n=this._b,i=this._c,s=this._d;r=Re(r,n,i,s,e[0],3614090360,7),s=Re(s,r,n,i,e[1],3905402710,12),i=Re(i,s,r,n,e[2],606105819,17),n=Re(n,i,s,r,e[3],3250441966,22),r=Re(r,n,i,s,e[4],4118548399,7),s=Re(s,r,n,i,e[5],1200080426,12),i=Re(i,s,r,n,e[6],2821735955,17),n=Re(n,i,s,r,e[7],4249261313,22),r=Re(r,n,i,s,e[8],1770035416,7),s=Re(s,r,n,i,e[9],2336552879,12),i=Re(i,s,r,n,e[10],4294925233,17),n=Re(n,i,s,r,e[11],2304563134,22),r=Re(r,n,i,s,e[12],1804603682,7),s=Re(s,r,n,i,e[13],4254626195,12),i=Re(i,s,r,n,e[14],2792965006,17),n=Re(n,i,s,r,e[15],1236535329,22),r=Ce(r,n,i,s,e[1],4129170786,5),s=Ce(s,r,n,i,e[6],3225465664,9),i=Ce(i,s,r,n,e[11],643717713,14),n=Ce(n,i,s,r,e[0],3921069994,20),r=Ce(r,n,i,s,e[5],3593408605,5),s=Ce(s,r,n,i,e[10],38016083,9),i=Ce(i,s,r,n,e[15],3634488961,14),n=Ce(n,i,s,r,e[4],3889429448,20),r=Ce(r,n,i,s,e[9],568446438,5),s=Ce(s,r,n,i,e[14],3275163606,9),i=Ce(i,s,r,n,e[3],4107603335,14),n=Ce(n,i,s,r,e[8],1163531501,20),r=Ce(r,n,i,s,e[13],2850285829,5),s=Ce(s,r,n,i,e[2],4243563512,9),i=Ce(i,s,r,n,e[7],1735328473,14),n=Ce(n,i,s,r,e[12],2368359562,20),r=Ue(r,n,i,s,e[5],4294588738,4),s=Ue(s,r,n,i,e[8],2272392833,11),i=Ue(i,s,r,n,e[11],1839030562,16),n=Ue(n,i,s,r,e[14],4259657740,23),r=Ue(r,n,i,s,e[1],2763975236,4),s=Ue(s,r,n,i,e[4],1272893353,11),i=Ue(i,s,r,n,e[7],4139469664,16),n=Ue(n,i,s,r,e[10],3200236656,23),r=Ue(r,n,i,s,e[13],681279174,4),s=Ue(s,r,n,i,e[0],3936430074,11),i=Ue(i,s,r,n,e[3],3572445317,16),n=Ue(n,i,s,r,e[6],76029189,23),r=Ue(r,n,i,s,e[9],3654602809,4),s=Ue(s,r,n,i,e[12],3873151461,11),i=Ue(i,s,r,n,e[15],530742520,16),n=Ue(n,i,s,r,e[2],3299628645,23),r=Le(r,n,i,s,e[0],4096336452,6),s=Le(s,r,n,i,e[7],1126891415,10),i=Le(i,s,r,n,e[14],2878612391,15),n=Le(n,i,s,r,e[5],4237533241,21),r=Le(r,n,i,s,e[12],1700485571,6),s=Le(s,r,n,i,e[3],2399980690,10),i=Le(i,s,r,n,e[10],4293915773,15),n=Le(n,i,s,r,e[1],2240044497,21),r=Le(r,n,i,s,e[8],1873313359,6),s=Le(s,r,n,i,e[15],4264355552,10),i=Le(i,s,r,n,e[6],2734768916,15),n=Le(n,i,s,r,e[13],1309151649,21),r=Le(r,n,i,s,e[4],4149444226,6),s=Le(s,r,n,i,e[11],3174756917,10),i=Le(i,s,r,n,e[2],718787259,15),n=Le(n,i,s,r,e[9],3951481745,21),this._a=this._a+r|0,this._b=this._b+n|0,this._c=this._c+i|0,this._d=this._d+s|0};vi.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=cd.allocUnsafe(16);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e};function Ei(e,t){return e<<t|e>>>32-t}function Re(e,t,r,n,i,s,o){return Ei(e+(t&r|~t&n)+i+s|0,o)+t|0}function Ce(e,t,r,n,i,s,o){return Ei(e+(t&n|r&~n)+i+s|0,o)+t|0}function Ue(e,t,r,n,i,s,o){return Ei(e+(t^r^n)+i+s|0,o)+t|0}function Le(e,t,r,n,i,s,o){return Ei(e+(r^(t|~n))+i+s|0,o)+t|0}var ud=vi,ni=Ve.Buffer,Ec=gc.Transform,ld=Oe;function hd(e,t){if(!ni.isBuffer(e)&&typeof e!="string")throw new TypeError(t+" must be a string or a buffer")}function Yt(e){Ec.call(this),this._block=ni.allocUnsafe(e),this._blockSize=e,this._blockOffset=0,this._length=[0,0,0,0],this._finalized=!1}ld(Yt,Ec);Yt.prototype._transform=function(e,t,r){var n=null;try{this.update(e,t)}catch(i){n=i}r(n)};Yt.prototype._flush=function(e){var t=null;try{this.push(this.digest())}catch(r){t=r}e(t)};Yt.prototype.update=function(e,t){if(hd(e,"Data"),this._finalized)throw new Error("Digest already called");ni.isBuffer(e)||(e=ni.from(e,t));for(var r=this._block,n=0;this._blockOffset+e.length-n>=this._blockSize;){for(var i=this._blockOffset;i<this._blockSize;)r[i++]=e[n++];this._update(),this._blockOffset=0}for(;n<e.length;)r[this._blockOffset++]=e[n++];for(var s=0,o=e.length*8;o>0;++s)this._length[s]+=o,o=this._length[s]/4294967296|0,o>0&&(this._length[s]-=4294967296*o);return this};Yt.prototype._update=function(){throw new Error("_update is not implemented")};Yt.prototype.digest=function(e){if(this._finalized)throw new Error("Digest already called");this._finalized=!0;var t=this._digest();e!==void 0&&(t=t.toString(e)),this._block.fill(0),this._blockOffset=0;for(var r=0;r<4;++r)this._length[r]=0;return t};Yt.prototype._digest=function(){throw new Error("_digest is not implemented")};var dd=Yt,ss=Bt.Buffer,pd=Oe,xc=dd,yd=new Array(16),Yr=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13],Xr=[5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11],Jr=[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6],Qr=[8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11],Zr=[0,1518500249,1859775393,2400959708,2840853838],en=[1352829926,1548603684,1836072691,2053994217,0];function xi(){xc.call(this,64),this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520}pd(xi,xc);xi.prototype._update=function(){for(var e=yd,t=0;t<16;++t)e[t]=this._block.readInt32LE(t*4);for(var r=this._a|0,n=this._b|0,i=this._c|0,s=this._d|0,o=this._e|0,a=this._a|0,u=this._b|0,h=this._c|0,d=this._d|0,p=this._e|0,v=0;v<80;v+=1){var y,I;v<16?(y=Ko(r,n,i,s,o,e[Yr[v]],Zr[0],Jr[v]),I=Qo(a,u,h,d,p,e[Xr[v]],en[0],Qr[v])):v<32?(y=Yo(r,n,i,s,o,e[Yr[v]],Zr[1],Jr[v]),I=Jo(a,u,h,d,p,e[Xr[v]],en[1],Qr[v])):v<48?(y=Xo(r,n,i,s,o,e[Yr[v]],Zr[2],Jr[v]),I=Xo(a,u,h,d,p,e[Xr[v]],en[2],Qr[v])):v<64?(y=Jo(r,n,i,s,o,e[Yr[v]],Zr[3],Jr[v]),I=Yo(a,u,h,d,p,e[Xr[v]],en[3],Qr[v])):(y=Qo(r,n,i,s,o,e[Yr[v]],Zr[4],Jr[v]),I=Ko(a,u,h,d,p,e[Xr[v]],en[4],Qr[v])),r=o,o=s,s=ar(i,10),i=n,n=y,a=p,p=d,d=ar(h,10),h=u,u=I}var k=this._b+i+d|0;this._b=this._c+s+p|0,this._c=this._d+o+a|0,this._d=this._e+r+u|0,this._e=this._a+n+h|0,this._a=k};xi.prototype._digest=function(){this._block[this._blockOffset++]=128,this._blockOffset>56&&(this._block.fill(0,this._blockOffset,64),this._update(),this._blockOffset=0),this._block.fill(0,this._blockOffset,56),this._block.writeUInt32LE(this._length[0],56),this._block.writeUInt32LE(this._length[1],60),this._update();var e=ss.alloc?ss.alloc(20):new ss(20);return e.writeInt32LE(this._a,0),e.writeInt32LE(this._b,4),e.writeInt32LE(this._c,8),e.writeInt32LE(this._d,12),e.writeInt32LE(this._e,16),e};function ar(e,t){return e<<t|e>>>32-t}function Ko(e,t,r,n,i,s,o,a){return ar(e+(t^r^n)+s+o|0,a)+i|0}function Yo(e,t,r,n,i,s,o,a){return ar(e+(t&r|~t&n)+s+o|0,a)+i|0}function Xo(e,t,r,n,i,s,o,a){return ar(e+((t|~r)^n)+s+o|0,a)+i|0}function Jo(e,t,r,n,i,s,o,a){return ar(e+(t&n|r&~n)+s+o|0,a)+i|0}function Qo(e,t,r,n,i,s,o,a){return ar(e+(t^(r|~n))+s+o|0,a)+i|0}var md=xi,Sc={exports:{}},Tc=Ve.Buffer;function Si(e,t){this._block=Tc.alloc(e),this._finalSize=t,this._blockSize=e,this._len=0}Si.prototype.update=function(e,t){typeof e=="string"&&(t=t||"utf8",e=Tc.from(e,t));for(var r=this._block,n=this._blockSize,i=e.length,s=this._len,o=0;o<i;){for(var a=s%n,u=Math.min(i-o,n-a),h=0;h<u;h++)r[a+h]=e[o+h];s+=u,o+=u,s%n===0&&this._update(r)}return this._len+=i,this};Si.prototype.digest=function(e){var t=this._len%this._blockSize;this._block[t]=128,this._block.fill(0,t+1),t>=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=this._len*8;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(r&4294967295)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var s=this._hash();return e?s.toString(e):s};Si.prototype._update=function(){throw new Error("_update must be implemented by subclass")};var Mr=Si,bd=Oe,Ac=Mr,wd=Ve.Buffer,gd=[1518500249,1859775393,-1894007588,-899497514],_d=new Array(80);function En(){this.init(),this._w=_d,Ac.call(this,64,56)}bd(En,Ac);En.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function vd(e){return e<<5|e>>>27}function Ed(e){return e<<30|e>>>2}function xd(e,t,r,n){return e===0?t&r|~t&n:e===2?t&r|t&n|r&n:t^r^n}En.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,s=this._d|0,o=this._e|0,a=0;a<16;++a)t[a]=e.readInt32BE(a*4);for(;a<80;++a)t[a]=t[a-3]^t[a-8]^t[a-14]^t[a-16];for(var u=0;u<80;++u){var h=~~(u/20),d=vd(r)+xd(h,n,i,s)+o+t[u]+gd[h]|0;o=s,s=i,i=Ed(n),n=r,r=d}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=o+this._e|0};En.prototype._hash=function(){var e=wd.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};var Sd=En,Td=Oe,kc=Mr,Ad=Ve.Buffer,kd=[1518500249,1859775393,-1894007588,-899497514],Bd=new Array(80);function xn(){this.init(),this._w=Bd,kc.call(this,64,56)}Td(xn,kc);xn.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function Id(e){return e<<1|e>>>31}function Pd(e){return e<<5|e>>>27}function Od(e){return e<<30|e>>>2}function Rd(e,t,r,n){return e===0?t&r|~t&n:e===2?t&r|t&n|r&n:t^r^n}xn.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,s=this._d|0,o=this._e|0,a=0;a<16;++a)t[a]=e.readInt32BE(a*4);for(;a<80;++a)t[a]=Id(t[a-3]^t[a-8]^t[a-14]^t[a-16]);for(var u=0;u<80;++u){var h=~~(u/20),d=Pd(r)+Rd(h,n,i,s)+o+t[u]+kd[h]|0;o=s,s=i,i=Od(n),n=r,r=d}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=o+this._e|0};xn.prototype._hash=function(){var e=Ad.allocUnsafe(20);return e.writeInt32BE(this._a|0,0),e.writeInt32BE(this._b|0,4),e.writeInt32BE(this._c|0,8),e.writeInt32BE(this._d|0,12),e.writeInt32BE(this._e|0,16),e};var Cd=xn,Ud=Oe,Bc=Mr,Ld=Ve.Buffer,Nd=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],Hd=new Array(64);function Sn(){this.init(),this._w=Hd,Bc.call(this,64,56)}Ud(Sn,Bc);Sn.prototype.init=function(){return this._a=1779033703,this._b=3144134277,this._c=1013904242,this._d=2773480762,this._e=1359893119,this._f=2600822924,this._g=528734635,this._h=1541459225,this};function Fd(e,t,r){return r^e&(t^r)}function Md(e,t,r){return e&t|r&(e|t)}function Dd(e){return(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10)}function $d(e){return(e>>>6|e<<26)^(e>>>11|e<<21)^(e>>>25|e<<7)}function jd(e){return(e>>>7|e<<25)^(e>>>18|e<<14)^e>>>3}function Gd(e){return(e>>>17|e<<15)^(e>>>19|e<<13)^e>>>10}Sn.prototype._update=function(e){for(var t=this._w,r=this._a|0,n=this._b|0,i=this._c|0,s=this._d|0,o=this._e|0,a=this._f|0,u=this._g|0,h=this._h|0,d=0;d<16;++d)t[d]=e.readInt32BE(d*4);for(;d<64;++d)t[d]=Gd(t[d-2])+t[d-7]+jd(t[d-15])+t[d-16]|0;for(var p=0;p<64;++p){var v=h+$d(o)+Fd(o,a,u)+Nd[p]+t[p]|0,y=Dd(r)+Md(r,n,i)|0;h=u,u=a,a=o,o=s+v|0,s=i,i=n,n=r,r=v+y|0}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=o+this._e|0,this._f=a+this._f|0,this._g=u+this._g|0,this._h=h+this._h|0};Sn.prototype._hash=function(){var e=Ld.allocUnsafe(32);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e.writeInt32BE(this._h,28),e};var Ic=Sn,Vd=Oe,zd=Ic,qd=Mr,Wd=Ve.Buffer,Kd=new Array(64);function Ti(){this.init(),this._w=Kd,qd.call(this,64,56)}Vd(Ti,zd);Ti.prototype.init=function(){return this._a=3238371032,this._b=914150663,this._c=812702999,this._d=4144912697,this._e=4290775857,this._f=1750603025,this._g=1694076839,this._h=3204075428,this};Ti.prototype._hash=function(){var e=Wd.allocUnsafe(28);return e.writeInt32BE(this._a,0),e.writeInt32BE(this._b,4),e.writeInt32BE(this._c,8),e.writeInt32BE(this._d,12),e.writeInt32BE(this._e,16),e.writeInt32BE(this._f,20),e.writeInt32BE(this._g,24),e};var Yd=Ti,Xd=Oe,Pc=Mr,Jd=Ve.Buffer,Zo=[1116352408,3609767458,1899447441,602891725,3049323471,3964484399,3921009573,2173295548,961987163,4081628472,1508970993,3053834265,2453635748,2937671579,2870763221,3664609560,3624381080,2734883394,310598401,1164996542,607225278,1323610764,1426881987,3590304994,1925078388,4068182383,2162078206,991336113,2614888103,633803317,3248222580,3479774868,3835390401,2666613458,4022224774,944711139,264347078,2341262773,604807628,2007800933,770255983,1495990901,1249150122,1856431235,1555081692,3175218132,1996064986,2198950837,2554220882,3999719339,2821834349,766784016,2952996808,2566594879,3210313671,3203337956,3336571891,1034457026,3584528711,2466948901,113926993,3758326383,338241895,168717936,666307205,1188179964,773529912,1546045734,1294757372,1522805485,1396182291,2643833823,1695183700,2343527390,1986661051,1014477480,2177026350,1206759142,2456956037,344077627,2730485921,1290863460,2820302411,3158454273,3259730800,3505952657,3345764771,106217008,3516065817,3606008344,3600352804,1432725776,4094571909,1467031594,275423344,851169720,430227734,3100823752,506948616,1363258195,659060556,3750685593,883997877,3785050280,958139571,3318307427,1322822218,3812723403,1537002063,2003034995,1747873779,3602036899,1955562222,1575990012,2024104815,1125592928,2227730452,2716904306,2361852424,442776044,2428436474,593698344,2756734187,3733110249,3204031479,2999351573,3329325298,3815920427,3391569614,3928383900,3515267271,566280711,3940187606,3454069534,4118630271,4000239992,116418474,1914138554,174292421,2731055270,289380356,3203993006,460393269,320620315,685471733,587496836,852142971,1086792851,1017036298,365543100,1126000580,2618297676,1288033470,3409855158,1501505948,4234509866,1607167915,987167468,1816402316,1246189591],Qd=new Array(160);function Tn(){this.init(),this._w=Qd,Pc.call(this,128,112)}Xd(Tn,Pc);Tn.prototype.init=function(){return this._ah=1779033703,this._bh=3144134277,this._ch=1013904242,this._dh=2773480762,this._eh=1359893119,this._fh=2600822924,this._gh=528734635,this._hh=1541459225,this._al=4089235720,this._bl=2227873595,this._cl=4271175723,this._dl=1595750129,this._el=2917565137,this._fl=725511199,this._gl=4215389547,this._hl=327033209,this};function ea(e,t,r){return r^e&(t^r)}function ta(e,t,r){return e&t|r&(e|t)}function ra(e,t){return(e>>>28|t<<4)^(t>>>2|e<<30)^(t>>>7|e<<25)}function na(e,t){return(e>>>14|t<<18)^(e>>>18|t<<14)^(t>>>9|e<<23)}function Zd(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^e>>>7}function e0(e,t){return(e>>>1|t<<31)^(e>>>8|t<<24)^(e>>>7|t<<25)}function t0(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^e>>>6}function r0(e,t){return(e>>>19|t<<13)^(t>>>29|e<<3)^(e>>>6|t<<26)}function ke(e,t){return e>>>0<t>>>0?1:0}Tn.prototype._update=function(e){for(var t=this._w,r=this._ah|0,n=this._bh|0,i=this._ch|0,s=this._dh|0,o=this._eh|0,a=this._fh|0,u=this._gh|0,h=this._hh|0,d=this._al|0,p=this._bl|0,v=this._cl|0,y=this._dl|0,I=this._el|0,k=this._fl|0,B=this._gl|0,R=this._hl|0,U=0;U<32;U+=2)t[U]=e.readInt32BE(U*4),t[U+1]=e.readInt32BE(U*4+4);for(;U<160;U+=2){var x=t[U-30],g=t[U-15*2+1],S=Zd(x,g),E=e0(g,x);x=t[U-2*2],g=t[U-2*2+1];var F=t0(x,g),D=r0(g,x),O=t[U-7*2],K=t[U-7*2+1],C=t[U-16*2],G=t[U-16*2+1],V=E+K|0,z=S+O+ke(V,E)|0;V=V+D|0,z=z+F+ke(V,D)|0,V=V+G|0,z=z+C+ke(V,G)|0,t[U]=z,t[U+1]=V}for(var ee=0;ee<160;ee+=2){z=t[ee],V=t[ee+1];var ve=ta(r,n,i),ze=ta(d,p,v),tt=ra(r,d),qe=ra(d,r),It=na(o,I),pe=na(I,o),Ee=Zo[ee],We=Zo[ee+1],Pt=ea(o,a,u),yt=ea(I,k,B),A=R+pe|0,T=h+It+ke(A,R)|0;A=A+yt|0,T=T+Pt+ke(A,yt)|0,A=A+We|0,T=T+Ee+ke(A,We)|0,A=A+V|0,T=T+z+ke(A,V)|0;var H=qe+ze|0,q=tt+ve+ke(H,qe)|0;h=u,R=B,u=a,B=k,a=o,k=I,I=y+A|0,o=s+T+ke(I,y)|0,s=i,y=v,i=n,v=p,n=r,p=d,d=A+H|0,r=T+q+ke(d,A)|0}this._al=this._al+d|0,this._bl=this._bl+p|0,this._cl=this._cl+v|0,this._dl=this._dl+y|0,this._el=this._el+I|0,this._fl=this._fl+k|0,this._gl=this._gl+B|0,this._hl=this._hl+R|0,this._ah=this._ah+r+ke(this._al,d)|0,this._bh=this._bh+n+ke(this._bl,p)|0,this._ch=this._ch+i+ke(this._cl,v)|0,this._dh=this._dh+s+ke(this._dl,y)|0,this._eh=this._eh+o+ke(this._el,I)|0,this._fh=this._fh+a+ke(this._fl,k)|0,this._gh=this._gh+u+ke(this._gl,B)|0,this._hh=this._hh+h+ke(this._hl,R)|0};Tn.prototype._hash=function(){var e=Jd.allocUnsafe(64);function t(r,n,i){e.writeInt32BE(r,i),e.writeInt32BE(n,i+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),t(this._gh,this._gl,48),t(this._hh,this._hl,56),e};var Oc=Tn,n0=Oe,i0=Oc,s0=Mr,o0=Ve.Buffer,a0=new Array(160);function Ai(){this.init(),this._w=a0,s0.call(this,128,112)}n0(Ai,i0);Ai.prototype.init=function(){return this._ah=3418070365,this._bh=1654270250,this._ch=2438529370,this._dh=355462360,this._eh=1731405415,this._fh=2394180231,this._gh=3675008525,this._hh=1203062813,this._al=3238371032,this._bl=914150663,this._cl=812702999,this._dl=4144912697,this._el=4290775857,this._fl=1750603025,this._gl=1694076839,this._hl=3204075428,this};Ai.prototype._hash=function(){var e=o0.allocUnsafe(48);function t(r,n,i){e.writeInt32BE(r,i),e.writeInt32BE(n,i+4)}return t(this._ah,this._al,0),t(this._bh,this._bl,8),t(this._ch,this._cl,16),t(this._dh,this._dl,24),t(this._eh,this._el,32),t(this._fh,this._fl,40),e};var c0=Ai,yr=Sc.exports=function(t){t=t.toLowerCase();var r=yr[t];if(!r)throw new Error(t+" is not supported (we accept pull requests)");return new r};yr.sha=Sd;yr.sha1=Cd;yr.sha224=Yd;yr.sha256=Ic;yr.sha384=c0;yr.sha512=Oc;var f0=Sc.exports,ht=Ve.Buffer,Rc=Ws.Transform,u0=ti.StringDecoder,l0=Oe;function it(e){Rc.call(this),this.hashMode=typeof e=="string",this.hashMode?this[e]=this._finalOrDigest:this.final=this._finalOrDigest,this._final&&(this.__final=this._final,this._final=null),this._decoder=null,this._encoding=null}l0(it,Rc);var h0=typeof Uint8Array<"u",d0=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u"&&ArrayBuffer.isView&&(ht.prototype instanceof Uint8Array||ht.TYPED_ARRAY_SUPPORT);function p0(e,t){if(e instanceof ht)return e;if(typeof e=="string")return ht.from(e,t);if(d0&&ArrayBuffer.isView(e)){if(e.byteLength===0)return ht.alloc(0);var r=ht.from(e.buffer,e.byteOffset,e.byteLength);if(r.byteLength===e.byteLength)return r}if(h0&&e instanceof Uint8Array||ht.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e))return ht.from(e);throw new TypeError('The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView.')}it.prototype.update=function(e,t,r){var n=p0(e,t),i=this._update(n);return this.hashMode?this:(r&&(i=this._toString(i,r)),i)};it.prototype.setAutoPadding=function(){};it.prototype.getAuthTag=function(){throw new Error("trying to get auth tag in unsupported state")};it.prototype.setAuthTag=function(){throw new Error("trying to set auth tag in unsupported state")};it.prototype.setAAD=function(){throw new Error("trying to set aad in unsupported state")};it.prototype._transform=function(e,t,r){var n;try{this.hashMode?this._update(e):this.push(this._update(e))}catch(i){n=i}finally{r(n)}};it.prototype._flush=function(e){var t;try{this.push(this.__final())}catch(r){t=r}e(t)};it.prototype._finalOrDigest=function(e){var t=this.__final()||ht.alloc(0);return e&&(t=this._toString(t,e,!0)),t};it.prototype._toString=function(e,t,r){if(this._decoder||(this._decoder=new u0(t),this._encoding=t),this._encoding!==t)throw new Error("can’t switch encodings");var n=this._decoder.write(e);return r&&(n+=this._decoder.end()),n};var y0=it,m0=Oe,b0=ud,w0=md,g0=f0,Cc=y0;function ki(e){Cc.call(this,"digest"),this._hash=e}m0(ki,Cc);ki.prototype._update=function(e){this._hash.update(e)};ki.prototype._final=function(){return this._hash.digest()};var _0=function(t){return t=t.toLowerCase(),t==="md5"?new b0:t==="rmd160"||t==="ripemd160"?new w0:new ki(g0(t))},Hn=Ve.Buffer;function v0(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var n=0;n<e.length;n++){var i=e.charAt(n),s=i.charCodeAt(0);if(t[s]!==255)throw new TypeError(i+" is ambiguous");t[s]=n}var o=e.length,a=e.charAt(0),u=Math.log(o)/Math.log(256),h=Math.log(256)/Math.log(o);function d(y){if((Array.isArray(y)||y instanceof Uint8Array)&&(y=Hn.from(y)),!Hn.isBuffer(y))throw new TypeError("Expected Buffer");if(y.length===0)return"";for(var I=0,k=0,B=0,R=y.length;B!==R&&y[B]===0;)B++,I++;for(var U=(R-B)*h+1>>>0,x=new Uint8Array(U);B!==R;){for(var g=y[B],S=0,E=U-1;(g!==0||S<k)&&E!==-1;E--,S++)g+=256*x[E]>>>0,x[E]=g%o>>>0,g=g/o>>>0;if(g!==0)throw new Error("Non-zero carry");k=S,B++}for(var F=U-k;F!==U&&x[F]===0;)F++;for(var D=a.repeat(I);F<U;++F)D+=e.charAt(x[F]);return D}function p(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return Hn.alloc(0);for(var I=0,k=0,B=0;y[I]===a;)k++,I++;for(var R=(y.length-I)*u+1>>>0,U=new Uint8Array(R);I<y.length;){var x=y.charCodeAt(I);if(x>255)return;var g=t[x];if(g===255)return;for(var S=0,E=R-1;(g!==0||S<B)&&E!==-1;E--,S++)g+=o*U[E]>>>0,U[E]=g%256>>>0,g=g/256>>>0;if(g!==0)throw new Error("Non-zero carry");B=S,I++}for(var F=R-B;F!==R&&U[F]===0;)F++;var D=Hn.allocUnsafe(k+(R-F));D.fill(0,0,k);for(var O=k;F!==R;)D[O++]=U[F++];return D}function v(y){var I=p(y);if(I)return I;throw new Error("Non-base"+o+" character")}return{encode:d,decodeUnsafe:p,decode:v}}var E0=v0,x0=E0,S0="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",T0=x0(S0),os=T0,A0=Ve.Buffer,k0=function(e){function t(s){var o=e(s);return os.encode(A0.concat([s,o],s.length+4))}function r(s){var o=s.slice(0,-4),a=s.slice(-4),u=e(o);if(!(a[0]^u[0]|a[1]^u[1]|a[2]^u[2]|a[3]^u[3]))return o}function n(s){var o=os.decodeUnsafe(s);if(o)return r(o)}function i(s){var o=os.decode(s),a=r(o);if(!a)throw new Error("Invalid checksum");return a}return{encode:t,decode:i,decodeUnsafe:n}},ia=_0,B0=k0;function I0(e){var t=ia("sha256").update(e).digest();return ia("sha256").update(t).digest()}var P0=B0(I0),Es=P0;function Uc(e,t){if(t!==void 0&&e[0]!==t)throw new Error("Invalid network version");if(e.length===33)return{version:e[0],privateKey:e.slice(1,33),compressed:!1};if(e.length!==34)throw new Error("Invalid WIF length");if(e[33]!==1)throw new Error("Invalid compression flag");return{version:e[0],privateKey:e.slice(1,33),compressed:!0}}function xs(e,t,r){var n=new Buffer(r?34:33);return n.writeUInt8(e,0),t.copy(n,1),r&&(n[33]=1),n}function O0(e,t){return Uc(Es.decode(e),t)}function R0(e,t,r){return typeof e=="number"?Es.encode(xs(e,t,r)):Es.encode(xs(e.version,e.privateKey,e.compressed))}var C0={decode:O0,decodeRaw:Uc,encode:R0,encodeRaw:xs},Bi={};Object.defineProperty(Bi,"__esModule",{value:!0});Bi.testEcc=void 0;const W=e=>Buffer.from(e,"hex");function U0(e){ue(e.isPoint(W("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ue(!e.isPoint(W("030000000000000000000000000000000000000000000000000000000000000005"))),ue(e.isPrivate(W("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ue(e.isPrivate(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))),ue(!e.isPrivate(W("0000000000000000000000000000000000000000000000000000000000000000"))),ue(!e.isPrivate(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"))),ue(!e.isPrivate(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364142"))),ue(Buffer.from(e.privateAdd(W("0000000000000000000000000000000000000000000000000000000000000001"),W("0000000000000000000000000000000000000000000000000000000000000000"))).equals(W("0000000000000000000000000000000000000000000000000000000000000001"))),ue(e.privateAdd(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413e"),W("0000000000000000000000000000000000000000000000000000000000000003"))===null),ue(Buffer.from(e.privateAdd(W("e211078564db65c3ce7704f08262b1f38f1ef412ad15b5ac2d76657a63b2c500"),W("b51fbb69051255d1becbd683de5848242a89c229348dd72896a87ada94ae8665"))).equals(W("9730c2ee69edbb958d42db7460bafa18fef9d955325aec99044c81c8282b0a24"))),ue(Buffer.from(e.privateNegate(W("0000000000000000000000000000000000000000000000000000000000000001"))).equals(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))),ue(Buffer.from(e.privateNegate(W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd036413e"))).equals(W("0000000000000000000000000000000000000000000000000000000000000003"))),ue(Buffer.from(e.privateNegate(W("b1121e4088a66a28f5b6b0f5844943ecd9f610196d7bb83b25214b60452c09af"))).equals(W("4eede1bf775995d70a494f0a7bb6bc11e0b8cccd41cce8009ab1132c8b0a3792"))),ue(Buffer.from(e.pointCompress(W("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),!0)).equals(W("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ue(Buffer.from(e.pointCompress(W("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"),!1)).equals(W("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"))),ue(Buffer.from(e.pointCompress(W("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),!0)).equals(W("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),ue(Buffer.from(e.pointCompress(W("0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),!1)).equals(W("0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"))),ue(Buffer.from(e.pointFromScalar(W("b1121e4088a66a28f5b6b0f5844943ecd9f610196d7bb83b25214b60452c09af"))).equals(W("02b07ba9dca9523b7ef4bd97703d43d20399eb698e194704791a25ce77a400df99"))),ue(e.xOnlyPointAddTweak(W("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))===null);let t=e.xOnlyPointAddTweak(W("1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b"),W("a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac"));ue(Buffer.from(t.xOnlyPubkey).equals(W("e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"))&&t.parity===1),t=e.xOnlyPointAddTweak(W("2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991"),W("823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47")),ue(Buffer.from(t.xOnlyPubkey).equals(W("9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"))&&t.parity===0),ue(Buffer.from(e.sign(W("5e9f0a0d593efdcf78ac923bc3313e4e7d408d574354ee2b3288c0da9fbba6ed"),W("fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140"))).equals(W("54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5"))),ue(e.verify(W("5e9f0a0d593efdcf78ac923bc3313e4e7d408d574354ee2b3288c0da9fbba6ed"),W("0379be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),W("54c4a33c6423d689378f160a7ff8b61330444abb58fb470f96ea16d99d4a2fed07082304410efa6b2943111b6a4e0aaa7b7db55a07e9861d1fb3cb1f421044a5"))),e.signSchnorr&&ue(Buffer.from(e.signSchnorr(W("7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c"),W("c90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b14e5c9"),W("c87aa53824b4d7ae2eb035a2b5bbbccc080e76cdc6d1692c4b0b62d798e6d906"))).equals(W("5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7"))),e.verifySchnorr&&ue(e.verifySchnorr(W("7e2d58d8b3bcdf1abadec7829054f90dda9805aab56c77333024b9d0a508b75c"),W("dd308afec5777e13121fa72b9cc1b7cc0139715309b086c960e18fd969774eb8"),W("5831aaeed7b44bb74e5eab94ba9d4294c49bcf2a60728d8b4c200f50dd313c1bab745879a5ad954a72c45a91c3a51d3c7adea98d82f8481e0e1e03674a6f3fb7")))}Bi.testEcc=U0;function ue(e){if(!e)throw new Error("ecc library invalid")}Object.defineProperty(Lr,"__esModule",{value:!0});Lr.ECPairFactory=Lr.networks=void 0;const Ss=Nr;Lr.networks=Ss;const je=Za,L0=rh,sa=C0,N0=Bi,as=je.typeforce.maybe(je.typeforce.compile({compressed:je.maybe(je.Boolean),network:je.maybe(je.Network)})),H0=e=>e.length===32?e:e.slice(1,33);function F0(e){(0,N0.testEcc)(e);function t(a){return e.isPoint(a)}function r(a,u){if(je.typeforce(je.Buffer256bit,a),!e.isPrivate(a))throw new TypeError("Private key not in range [1, n)");return je.typeforce(as,u),new o(a,void 0,u)}function n(a,u){return je.typeforce(e.isPoint,a),je.typeforce(as,u),new o(void 0,a,u)}function i(a,u){const h=sa.decode(a),d=h.version;if(je.Array(u)){if(u=u.filter(p=>d===p.wif).pop(),!u)throw new Error("Unknown network version")}else if(u=u||Ss.bitcoin,d!==u.wif)throw new Error("Invalid network version");return r(h.privateKey,{compressed:h.compressed,network:u})}function s(a){je.typeforce(as,a),a===void 0&&(a={});const u=a.rng||L0;let h;do h=u(32),je.typeforce(je.Buffer256bit,h);while(!e.isPrivate(h));return r(h,a)}class o{constructor(u,h,d){wr(this,"__D");wr(this,"__Q");wr(this,"compressed");wr(this,"network");wr(this,"lowR");this.__D=u,this.__Q=h,this.lowR=!1,d===void 0&&(d={}),this.compressed=d.compressed===void 0?!0:d.compressed,this.network=d.network||Ss.bitcoin,h!==void 0&&(this.__Q=Buffer.from(e.pointCompress(h,this.compressed)))}get privateKey(){return this.__D}get publicKey(){if(!this.__Q){const u=e.pointFromScalar(this.__D,this.compressed);this.__Q=Buffer.from(u)}return this.__Q}toWIF(){if(!this.__D)throw new Error("Missing private key");return sa.encode(this.network.wif,this.__D,this.compressed)}tweak(u){return this.privateKey?this.tweakFromPrivateKey(u):this.tweakFromPublicKey(u)}sign(u,h){if(!this.__D)throw new Error("Missing private key");if(h===void 0&&(h=this.lowR),h===!1)return Buffer.from(e.sign(u,this.__D));{let d=e.sign(u,this.__D);const p=Buffer.alloc(32,0);let v=0;for(;d[0]>127;)v++,p.writeUIntLE(v,0,6),d=e.sign(u,this.__D,p);return Buffer.from(d)}}signSchnorr(u){if(!this.privateKey)throw new Error("Missing private key");if(!e.signSchnorr)throw new Error("signSchnorr not supported by ecc library");return Buffer.from(e.signSchnorr(u,this.privateKey))}verify(u,h){return e.verify(u,this.publicKey,h)}verifySchnorr(u,h){if(!e.verifySchnorr)throw new Error("verifySchnorr not supported by ecc library");return e.verifySchnorr(u,this.publicKey.subarray(1,33),h)}tweakFromPublicKey(u){const h=H0(this.publicKey),d=e.xOnlyPointAddTweak(h,u);if(!d||d.xOnlyPubkey===null)throw new Error("Cannot tweak public key!");const p=Buffer.from([d.parity===0?2:3]);return n(Buffer.concat([p,d.xOnlyPubkey]),{network:this.network,compressed:this.compressed})}tweakFromPrivateKey(u){const d=this.publicKey[0]===3||this.publicKey[0]===4&&(this.publicKey[64]&1)===1?e.privateNegate(this.privateKey):this.privateKey,p=e.privateAdd(d,u);if(!p)throw new Error("Invalid tweaked private key!");return r(Buffer.from(p),{network:this.network,compressed:this.compressed})}}return{isPoint:t,fromPrivateKey:r,fromPublicKey:n,fromWIF:i,makeRandom:s}}Lr.ECPairFactory=F0;(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.networks=e.ECPairFactory=e.default=void 0;var t=Lr;Object.defineProperty(e,"default",{enumerable:!0,get:function(){return t.ECPairFactory}}),Object.defineProperty(e,"ECPairFactory",{enumerable:!0,get:function(){return t.ECPairFactory}}),Object.defineProperty(e,"networks",{enumerable:!0,get:function(){return t.networks}})})(Qa);const M0=Lf(Qa);class bn extends j.EventBroker{get isInitialized(){return!!this.digestKey}constructor(t,r){super(),this.digestKey=t,this.walletClient=r}static fromDigestKey(t){return new bn(tr(t))}static fromWalletClient(t){return new bn(void 0,t)}async initialize(){if(this.digestKey)return re("Already initialized");const t=await this.deriveDigestKeyFromWalletClient();return t.error?M(t.error):(this.emit("initialized",!0),re("Initialized"))}async deriveDigestKeyFromWalletClient(){if(!this.walletClient)return M("No walletClient found");if(!this.walletClient.account)return M("No account found");try{const t=await this.walletClient.signTypedData({account:this.walletClient.account,types:{EIP712Domain:[{name:"name",type:"string"},{name:"version",type:"string"}],Data:[{name:"Message",type:"string"},{name:"Version",type:"string"},{name:"Nonce",type:"uint256"}]},domain:{name:"GARDEN FINANCE",version:"1"},primaryType:"Data",message:{Message:"Initialize your account",Version:"1.0.2",Nonce:1n}});return this.digestKey=tr(nt.sha256(t)),this.emit("initialized",!0),re(this.digestKey)}catch(t){return M("Failed to initialize: "+t)}}async getDigestKey(){if(!this.digestKey&&!this.walletClient)return M("No private key or wallet client found");if(!this.digestKey&&this.walletClient){const t=await this.deriveDigestKeyFromWalletClient();if(t.error)return M(t.error)}return this.digestKey?re(this.digestKey):M("No private key found")}async generateSecret(t){const r=await this.signMessage(t);if(r.error)return M(r.error);const n=nt.sha256(j.with0x(r.val)),i=nt.sha256(n);return re({secret:n,secretHash:i})}async signMessage(t){if(!this.digestKey){const h=await this.getDigestKey();if(h.error)return M(h.error);this.digestKey=h.val}const r=M0(ir),n="Garden.fi"+t.toString(),i=Buffer.from(n,"utf8"),s=nt.sha256(i),o=Buffer.from(tr(this.digestKey),"hex");if(o.length!==32)return M("Invalid private key length. Expected 32 bytes.");const u=r.fromPrivateKey(o).sign(Buffer.from(tr(s),"hex"));return re(u.toString("hex"))}}const oa=[{inputs:[{internalType:"address",name:"token_",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"initiateWithSignature",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{components:[{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"expiry",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],internalType:"struct HTLC.InitWithSig[]",name:"inits",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],internalType:"struct HTLC.Redeem[]",name:"redeems",type:"tuple[]"},{components:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],internalType:"struct HTLC.Refund[]",name:"refunds",type:"tuple[]"}],name:"multicall",outputs:[{internalType:"bool[]",name:"results",type:"bool[]"}],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address",name:"initiator",type:"address"},{internalType:"address",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"contract IERC20",name:"",type:"address"}],stateMutability:"view",type:"function"}];function pt(e){return{formatters:void 0,fees:void 0,serializers:void 0,...e}}const Lc="2.26.3";let tn={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${Lc}`};class de extends Error{constructor(t,r={}){var a;const n=(()=>{var u;return r.cause instanceof de?r.cause.details:(u=r.cause)!=null&&u.message?r.cause.message:r.details})(),i=r.cause instanceof de&&r.cause.docsPath||r.docsPath,s=(a=tn.getDocsUrl)==null?void 0:a.call(tn,{...r,docsPath:i}),o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...tn.version?[`Version: ${tn.version}`]:[]].join(`
|
|
32
|
+
`);super(o,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=Lc}walk(t){return Nc(this,t)}}function Nc(e,t){return t!=null&&t(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?Nc(e.cause,t):t?null:e}class D0 extends de{constructor({max:t,min:r,signed:n,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${t?`(${r} to ${t})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class $0 extends de{constructor({givenSize:t,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${t} bytes.`,{name:"SizeOverflowError"})}}function An(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}function Fr(e){return An(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}function ii(e,{dir:t="left"}={}){let r=typeof e=="string"?e.replace("0x",""):e,n=0;for(let i=0;i<r.length-1&&r[t==="left"?i:r.length-i-1].toString()==="0";i++)n++;return r=t==="left"?r.slice(n):r.slice(0,r.length-n),typeof e=="string"?(r.length===1&&t==="right"&&(r=`${r}0`),`0x${r.length%2===1?`0${r}`:r}`):r}class j0 extends de{constructor({offset:t,position:r,size:n}){super(`Slice ${r==="start"?"starting":"ending"} at offset "${t}" is out-of-bounds (size: ${n}).`,{name:"SliceOffsetOutOfBoundsError"})}}class Hc extends de{constructor({size:t,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${t}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function Dr(e,{dir:t,size:r=32}={}){return typeof e=="string"?G0(e,{dir:t,size:r}):V0(e,{dir:t,size:r})}function G0(e,{dir:t,size:r=32}={}){if(r===null)return e;const n=e.replace("0x","");if(n.length>r*2)throw new Hc({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[t==="right"?"padEnd":"padStart"](r*2,"0")}`}function V0(e,{dir:t,size:r=32}={}){if(r===null)return e;if(e.length>r)throw new Hc({size:e.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const s=t==="right";n[s?i:r-i-1]=e[s?i:e.length-i-1]}return n}const z0=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Q(e,t={}){return typeof e=="number"||typeof e=="bigint"?Fc(e,t):typeof e=="string"?K0(e,t):typeof e=="boolean"?q0(e,t):Xt(e,t)}function q0(e,t={}){const r=`0x${Number(e)}`;return typeof t.size=="number"?($r(r,{size:t.size}),Dr(r,{size:t.size})):r}function Xt(e,t={}){let r="";for(let i=0;i<e.length;i++)r+=z0[e[i]];const n=`0x${r}`;return typeof t.size=="number"?($r(n,{size:t.size}),Dr(n,{dir:"right",size:t.size})):n}function Fc(e,t={}){const{signed:r,size:n}=t,i=BigInt(e);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof e=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const u=typeof e=="bigint"?"n":"";throw new D0({max:s?`${s}${u}`:void 0,min:`${o}${u}`,signed:r,size:n,value:`${e}${u}`})}const a=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?Dr(a,{size:n}):a}const W0=new TextEncoder;function K0(e,t={}){const r=W0.encode(e);return Xt(r,t)}const Y0=new TextEncoder;function Mc(e,t={}){return typeof e=="number"||typeof e=="bigint"?J0(e,t):typeof e=="boolean"?X0(e,t):An(e)?cr(e,t):Dc(e,t)}function X0(e,t={}){const r=new Uint8Array(1);return r[0]=Number(e),typeof t.size=="number"?($r(r,{size:t.size}),Dr(r,{size:t.size})):r}const _t={zero:48,nine:57,A:65,F:70,a:97,f:102};function aa(e){if(e>=_t.zero&&e<=_t.nine)return e-_t.zero;if(e>=_t.A&&e<=_t.F)return e-(_t.A-10);if(e>=_t.a&&e<=_t.f)return e-(_t.a-10)}function cr(e,t={}){let r=e;t.size&&($r(r,{size:t.size}),r=Dr(r,{dir:"right",size:t.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const u=aa(n.charCodeAt(a++)),h=aa(n.charCodeAt(a++));if(u===void 0||h===void 0)throw new de(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);s[o]=u*16+h}return s}function J0(e,t){const r=Fc(e,t);return cr(r)}function Dc(e,t={}){const r=Y0.encode(e);return typeof t.size=="number"?($r(r,{size:t.size}),Dr(r,{dir:"right",size:t.size})):r}function $r(e,{size:t}){if(Fr(e)>t)throw new $0({givenSize:Fr(e),maxSize:t})}function Ar(e,t={}){const{signed:r}=t;t.size&&$r(e,{size:t.size});const n=BigInt(e);if(!r)return n;const i=(e.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return n<=s?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function si(e,t={}){return Number(Ar(e,t))}function Xs(e,t){return({exclude:r,format:n})=>({exclude:r,format:i=>{const s=t(i);if(r)for(const o of r)delete s[o];return{...s,...n(i)}},type:e})}const $c={"0x0":"legacy","0x1":"eip2930","0x2":"eip1559","0x3":"eip4844","0x4":"eip7702"};function Js(e){const t={...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,chainId:e.chainId?si(e.chainId):void 0,gas:e.gas?BigInt(e.gas):void 0,gasPrice:e.gasPrice?BigInt(e.gasPrice):void 0,maxFeePerBlobGas:e.maxFeePerBlobGas?BigInt(e.maxFeePerBlobGas):void 0,maxFeePerGas:e.maxFeePerGas?BigInt(e.maxFeePerGas):void 0,maxPriorityFeePerGas:e.maxPriorityFeePerGas?BigInt(e.maxPriorityFeePerGas):void 0,nonce:e.nonce?si(e.nonce):void 0,to:e.to?e.to:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,type:e.type?$c[e.type]:void 0,typeHex:e.type?e.type:void 0,value:e.value?BigInt(e.value):void 0,v:e.v?BigInt(e.v):void 0};return e.authorizationList&&(t.authorizationList=Z0(e.authorizationList)),t.yParity=(()=>{if(e.yParity)return Number(e.yParity);if(typeof t.v=="bigint"){if(t.v===0n||t.v===27n)return 0;if(t.v===1n||t.v===28n)return 1;if(t.v>=35n)return t.v%2n===0n?1:0}})(),t.type==="legacy"&&(delete t.accessList,delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas,delete t.yParity),t.type==="eip2930"&&(delete t.maxFeePerBlobGas,delete t.maxFeePerGas,delete t.maxPriorityFeePerGas),t.type==="eip1559"&&delete t.maxFeePerBlobGas,t}const Q0=Xs("transaction",Js);function Z0(e){return e.map(t=>({address:t.address,chainId:Number(t.chainId),nonce:Number(t.nonce),r:t.r,s:t.s,yParity:Number(t.yParity)}))}function ep(e){const t=(e.transactions??[]).map(r=>typeof r=="string"?r:Js(r));return{...e,baseFeePerGas:e.baseFeePerGas?BigInt(e.baseFeePerGas):null,blobGasUsed:e.blobGasUsed?BigInt(e.blobGasUsed):void 0,difficulty:e.difficulty?BigInt(e.difficulty):void 0,excessBlobGas:e.excessBlobGas?BigInt(e.excessBlobGas):void 0,gasLimit:e.gasLimit?BigInt(e.gasLimit):void 0,gasUsed:e.gasUsed?BigInt(e.gasUsed):void 0,hash:e.hash?e.hash:null,logsBloom:e.logsBloom?e.logsBloom:null,nonce:e.nonce?e.nonce:null,number:e.number?BigInt(e.number):null,size:e.size?BigInt(e.size):void 0,timestamp:e.timestamp?BigInt(e.timestamp):void 0,transactions:t,totalDifficulty:e.totalDifficulty?BigInt(e.totalDifficulty):null}}const tp=Xs("block",ep);function rp(e,{args:t,eventName:r}={}){return{...e,blockHash:e.blockHash?e.blockHash:null,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,logIndex:e.logIndex?Number(e.logIndex):null,transactionHash:e.transactionHash?e.transactionHash:null,transactionIndex:e.transactionIndex?Number(e.transactionIndex):null,...r?{args:t,eventName:r}:{}}}const np={"0x0":"reverted","0x1":"success"};function ip(e){const t={...e,blockNumber:e.blockNumber?BigInt(e.blockNumber):null,contractAddress:e.contractAddress?e.contractAddress:null,cumulativeGasUsed:e.cumulativeGasUsed?BigInt(e.cumulativeGasUsed):null,effectiveGasPrice:e.effectiveGasPrice?BigInt(e.effectiveGasPrice):null,gasUsed:e.gasUsed?BigInt(e.gasUsed):null,logs:e.logs?e.logs.map(r=>rp(r)):null,to:e.to?e.to:null,transactionIndex:e.transactionIndex?si(e.transactionIndex):null,status:e.status?np[e.status]:null,type:e.type?$c[e.type]||e.type:null};return e.blobGasPrice&&(t.blobGasPrice=BigInt(e.blobGasPrice)),e.blobGasUsed&&(t.blobGasUsed=BigInt(e.blobGasUsed)),t}const sp=Xs("transactionReceipt",ip),Qs=2n**256n-1n;function kn(e){return`0x${e.reduce((t,r)=>t+r.replace("0x",""),"")}`}class ca extends de{constructor({offset:t}){super(`Offset \`${t}\` cannot be negative.`,{name:"NegativeOffsetError"})}}class op extends de{constructor({length:t,position:r}){super(`Position \`${r}\` is out of bounds (\`0 < position < ${t}\`).`,{name:"PositionOutOfBoundsError"})}}class ap extends de{constructor({count:t,limit:r}){super(`Recursive read limit of \`${r}\` exceeded (recursive read count: \`${t}\`).`,{name:"RecursiveReadLimitExceededError"})}}const cp={bytes:new Uint8Array,dataView:new DataView(new ArrayBuffer(0)),position:0,positionReadCount:new Map,recursiveReadCount:0,recursiveReadLimit:Number.POSITIVE_INFINITY,assertReadLimit(){if(this.recursiveReadCount>=this.recursiveReadLimit)throw new ap({count:this.recursiveReadCount+1,limit:this.recursiveReadLimit})},assertPosition(e){if(e<0||e>this.bytes.length-1)throw new op({length:this.bytes.length,position:e})},decrementPosition(e){if(e<0)throw new ca({offset:e});const t=this.position-e;this.assertPosition(t),this.position=t},getReadCount(e){return this.positionReadCount.get(e||this.position)||0},incrementPosition(e){if(e<0)throw new ca({offset:e});const t=this.position+e;this.assertPosition(t),this.position=t},inspectByte(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectBytes(e,t){const r=t??this.position;return this.assertPosition(r+e-1),this.bytes.subarray(r,r+e)},inspectUint8(e){const t=e??this.position;return this.assertPosition(t),this.bytes[t]},inspectUint16(e){const t=e??this.position;return this.assertPosition(t+1),this.dataView.getUint16(t)},inspectUint24(e){const t=e??this.position;return this.assertPosition(t+2),(this.dataView.getUint16(t)<<8)+this.dataView.getUint8(t+2)},inspectUint32(e){const t=e??this.position;return this.assertPosition(t+3),this.dataView.getUint32(t)},pushByte(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushBytes(e){this.assertPosition(this.position+e.length-1),this.bytes.set(e,this.position),this.position+=e.length},pushUint8(e){this.assertPosition(this.position),this.bytes[this.position]=e,this.position++},pushUint16(e){this.assertPosition(this.position+1),this.dataView.setUint16(this.position,e),this.position+=2},pushUint24(e){this.assertPosition(this.position+2),this.dataView.setUint16(this.position,e>>8),this.dataView.setUint8(this.position+2,e&255),this.position+=3},pushUint32(e){this.assertPosition(this.position+3),this.dataView.setUint32(this.position,e),this.position+=4},readByte(){this.assertReadLimit(),this._touch();const e=this.inspectByte();return this.position++,e},readBytes(e,t){this.assertReadLimit(),this._touch();const r=this.inspectBytes(e);return this.position+=t??e,r},readUint8(){this.assertReadLimit(),this._touch();const e=this.inspectUint8();return this.position+=1,e},readUint16(){this.assertReadLimit(),this._touch();const e=this.inspectUint16();return this.position+=2,e},readUint24(){this.assertReadLimit(),this._touch();const e=this.inspectUint24();return this.position+=3,e},readUint32(){this.assertReadLimit(),this._touch();const e=this.inspectUint32();return this.position+=4,e},get remaining(){return this.bytes.length-this.position},setPosition(e){const t=this.position;return this.assertPosition(e),this.position=e,()=>this.position=t},_touch(){if(this.recursiveReadLimit===Number.POSITIVE_INFINITY)return;const e=this.getReadCount();this.positionReadCount.set(this.position,e+1),e>0&&this.recursiveReadCount++}};function jc(e,{recursiveReadLimit:t=8192}={}){const r=Object.create(cp);return r.bytes=e,r.dataView=new DataView(e.buffer,e.byteOffset,e.byteLength),r.positionReadCount=new Map,r.recursiveReadLimit=t,r}function fr(e,t="hex"){const r=Gc(e),n=jc(new Uint8Array(r.length));return r.encode(n),t==="hex"?Xt(n.bytes):n.bytes}function Gc(e){return Array.isArray(e)?fp(e.map(t=>Gc(t))):up(e)}function fp(e){const t=e.reduce((i,s)=>i+s.length,0),r=Vc(t);return{length:t<=55?1+t:1+r+t,encode(i){t<=55?i.pushByte(192+t):(i.pushByte(247+r),r===1?i.pushUint8(t):r===2?i.pushUint16(t):r===3?i.pushUint24(t):i.pushUint32(t));for(const{encode:s}of e)s(i)}}}function up(e){const t=typeof e=="string"?cr(e):e,r=Vc(t.length);return{length:t.length===1&&t[0]<128?1:t.length<=55?1+t.length:1+r+t.length,encode(i){t.length===1&&t[0]<128?i.pushBytes(t):t.length<=55?(i.pushByte(128+t.length),i.pushBytes(t)):(i.pushByte(183+r),r===1?i.pushUint8(t.length):r===2?i.pushUint16(t.length):r===3?i.pushUint24(t.length):i.pushUint32(t.length),i.pushBytes(t))}}}function Vc(e){if(e<2**8)return 1;if(e<2**16)return 2;if(e<2**24)return 3;if(e<2**32)return 4;throw new de("Length is too large.")}const lp={ether:-9,wei:9};function hp(e,t){let r=e.toString();const n=r.startsWith("-");n&&(r=r.slice(1)),r=r.padStart(t,"0");let[i,s]=[r.slice(0,r.length-t),r.slice(r.length-t)];return s=s.replace(/(0+)$/,""),`${n?"-":""}${i||"0"}${s?`.${s}`:""}`}function Ts(e,t="wei"){return hp(e,lp[t])}function dp(e){const t=Object.entries(e).map(([n,i])=>i===void 0||i===!1?null:[n,i]).filter(Boolean),r=t.reduce((n,[i])=>Math.max(n,i.length),0);return t.map(([n,i])=>` ${`${n}:`.padEnd(r+1)} ${i}`).join(`
|
|
33
|
+
`)}class pp extends de{constructor({v:t}){super(`Invalid \`v\` value "${t}". Expected 27 or 28.`,{name:"InvalidLegacyVError"})}}class yp extends de{constructor({transaction:t}){super("Cannot infer a transaction type from provided transaction.",{metaMessages:["Provided Transaction:","{",dp(t),"}","","To infer the type, either provide:","- a `type` to the Transaction, or","- an EIP-1559 Transaction with `maxFeePerGas`, or","- an EIP-2930 Transaction with `gasPrice` & `accessList`, or","- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or","- an EIP-7702 Transaction with `authorizationList`, or","- a Legacy Transaction with `gasPrice`"],name:"InvalidSerializableTransactionError"})}}class mp extends de{constructor({storageKey:t}){super(`Size for storage key "${t}" is invalid. Expected 32 bytes. Got ${Math.floor((t.length-2)/2)} bytes.`,{name:"InvalidStorageKeySizeError"})}}function bp(e){if(!e||e.length===0)return[];const t=[];for(const r of e){const{chainId:n,nonce:i,...s}=r,o=r.address;t.push([n?Q(n):"0x",o,i?Q(i):"0x",...Bn({},s)])}return t}function zc(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(s=>cr(s)):e.blobs,i=[];for(const s of n)i.push(Uint8Array.from(t.blobToKzgCommitment(s)));return r==="bytes"?i:i.map(s=>Xt(s))}function qc(e){const{kzg:t}=e,r=e.to??(typeof e.blobs[0]=="string"?"hex":"bytes"),n=typeof e.blobs[0]=="string"?e.blobs.map(o=>cr(o)):e.blobs,i=typeof e.commitments[0]=="string"?e.commitments.map(o=>cr(o)):e.commitments,s=[];for(let o=0;o<n.length;o++){const a=n[o],u=i[o];s.push(Uint8Array.from(t.computeBlobKzgProof(a,u)))}return r==="bytes"?s:s.map(o=>Xt(o))}function wp(e,t){return Da(An(e,{strict:!1})?Mc(e):e)}function gp(e){const{commitment:t,version:r=1}=e,n=e.to??(typeof t=="string"?"hex":"bytes"),i=wp(t);return i.set([r],0),n==="bytes"?i:Xt(i)}function _p(e){const{commitments:t,version:r}=e,n=e.to??(typeof t[0]=="string"?"hex":"bytes"),i=[];for(const s of t)i.push(gp({commitment:s,to:n,version:r}));return i}const fa=6,Wc=32,Zs=4096,Kc=Wc*Zs,ua=Kc*fa-1-1*Zs*fa,Yc=1;class vp extends de{constructor({maxSize:t,size:r}){super("Blob size is too large.",{metaMessages:[`Max: ${t} bytes`,`Given: ${r} bytes`],name:"BlobSizeTooLargeError"})}}class Xc extends de{constructor(){super("Blob data must not be empty.",{name:"EmptyBlobError"})}}class Ep extends de{constructor({hash:t,size:r}){super(`Versioned hash "${t}" size is invalid.`,{metaMessages:["Expected: 32",`Received: ${r}`],name:"InvalidVersionedHashSizeError"})}}class xp extends de{constructor({hash:t,version:r}){super(`Versioned hash "${t}" version is invalid.`,{metaMessages:[`Expected: ${Yc}`,`Received: ${r}`],name:"InvalidVersionedHashVersionError"})}}function Sp(e){const t=e.to??(typeof e.data=="string"?"hex":"bytes"),r=typeof e.data=="string"?cr(e.data):e.data,n=Fr(r);if(!n)throw new Xc;if(n>ua)throw new vp({maxSize:ua,size:n});const i=[];let s=!0,o=0;for(;s;){const a=jc(new Uint8Array(Kc));let u=0;for(;u<Zs;){const h=r.slice(o,o+(Wc-1));if(a.pushByte(0),a.pushBytes(h),h.length<31){a.pushByte(128),s=!1;break}u++,o+=31}i.push(a)}return t==="bytes"?i.map(a=>a.bytes):i.map(a=>Xt(a.bytes))}function Tp(e){const{data:t,kzg:r,to:n}=e,i=e.blobs??Sp({data:t,to:n}),s=e.commitments??zc({blobs:i,kzg:r,to:n}),o=e.proofs??qc({blobs:i,commitments:s,kzg:r,to:n}),a=[];for(let u=0;u<i.length;u++)a.push({blob:i[u],commitment:s[u],proof:o[u]});return a}class ur extends de{constructor({address:t}){super(`Address "${t}" is invalid.`,{metaMessages:["- Address must be a hex value of 20 bytes (40 hex characters).","- Address must match its checksum counterpart."],name:"InvalidAddressError"})}}class Ii extends de{constructor({chainId:t}){super(typeof t=="number"?`Chain ID "${t}" is invalid.`:"Chain ID is invalid.",{name:"InvalidChainIdError"})}}class Pi extends de{constructor({cause:t,maxFeePerGas:r}={}){super(`The fee cap (\`maxFeePerGas\`${r?` = ${Ts(r)} gwei`:""}) cannot be higher than the maximum allowed value (2^256-1).`,{cause:t,name:"FeeCapTooHighError"})}}Object.defineProperty(Pi,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max fee per gas higher than 2\^256-1|fee cap higher than 2\^256-1/});class Jc extends de{constructor({cause:t,maxPriorityFeePerGas:r,maxFeePerGas:n}={}){super([`The provided tip (\`maxPriorityFeePerGas\`${r?` = ${Ts(r)} gwei`:""}) cannot be higher than the fee cap (\`maxFeePerGas\`${n?` = ${Ts(n)} gwei`:""}).`].join(`
|
|
34
|
+
`),{cause:t,name:"TipAboveFeeCapError"})}}Object.defineProperty(Jc,"nodeMessage",{enumerable:!0,configurable:!0,writable:!0,value:/max priority fee per gas higher than max fee per gas|tip higher than fee cap/});class Qc extends Map{constructor(t){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=t}get(t){const r=super.get(t);return super.has(t)&&r!==void 0&&(this.delete(t),super.set(t,r)),r}set(t,r){if(super.set(t,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const Fn=BigInt(2**32-1),la=BigInt(32);function Ap(e,t=!1){return t?{h:Number(e&Fn),l:Number(e>>la&Fn)}:{h:Number(e>>la&Fn)|0,l:Number(e&Fn)|0}}function kp(e,t=!1){let r=new Uint32Array(e.length),n=new Uint32Array(e.length);for(let i=0;i<e.length;i++){const{h:s,l:o}=Ap(e[i],t);[r[i],n[i]]=[s,o]}return[r,n]}const Bp=(e,t,r)=>e<<r|t>>>32-r,Ip=(e,t,r)=>t<<r|e>>>32-r,Pp=(e,t,r)=>t<<r-32|e>>>64-r,Op=(e,t,r)=>e<<r-32|t>>>64-r,Zc=[],ef=[],tf=[],Rp=BigInt(0),rn=BigInt(1),Cp=BigInt(2),Up=BigInt(7),Lp=BigInt(256),Np=BigInt(113);for(let e=0,t=rn,r=1,n=0;e<24;e++){[r,n]=[n,(2*r+3*n)%5],Zc.push(2*(5*n+r)),ef.push((e+1)*(e+2)/2%64);let i=Rp;for(let s=0;s<7;s++)t=(t<<rn^(t>>Up)*Np)%Lp,t&Cp&&(i^=rn<<(rn<<BigInt(s))-rn);tf.push(i)}const[Hp,Fp]=kp(tf,!0),ha=(e,t,r)=>r>32?Pp(e,t,r):Bp(e,t,r),da=(e,t,r)=>r>32?Op(e,t,r):Ip(e,t,r);function Mp(e,t=24){const r=new Uint32Array(10);for(let n=24-t;n<24;n++){for(let o=0;o<10;o++)r[o]=e[o]^e[o+10]^e[o+20]^e[o+30]^e[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,u=(o+2)%10,h=r[u],d=r[u+1],p=ha(h,d,1)^r[a],v=da(h,d,1)^r[a+1];for(let y=0;y<50;y+=10)e[o+y]^=p,e[o+y+1]^=v}let i=e[2],s=e[3];for(let o=0;o<24;o++){const a=ef[o],u=ha(i,s,a),h=da(i,s,a),d=Zc[o];i=e[d],s=e[d+1],e[d]=u,e[d+1]=h}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=e[o+a];for(let a=0;a<10;a++)e[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}e[0]^=Hp[n],e[1]^=Fp[n]}r.fill(0)}class eo extends Ma{constructor(t,r,n,i=!1,s=24){if(super(),this.blockLen=t,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,uo(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=pu(this.state)}keccak(){lo||ho(this.state32),Mp(this.state32,this.rounds),lo||ho(this.state32),this.posOut=0,this.pos=0}update(t){Qn(this);const{blockLen:r,state:n}=this;t=Hs(t);const i=t.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=t[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:t,suffix:r,pos:n,blockLen:i}=this;t[n]^=r,r&128&&n===i-1&&this.keccak(),t[i-1]^=128,this.keccak()}writeInto(t){Qn(this,!1),Ns(t),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=t.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);t.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return uo(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(Fa(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,this.state.fill(0)}_cloneInto(t){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return t||(t=new eo(r,n,i,o,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=n,t.outputLen=i,t.enableXOF=o,t.destroyed=this.destroyed,t}}const Dp=(e,t,r)=>Fs(()=>new eo(t,e,r)),$p=Dp(1,136,256/8);function jp(e,t){return $p(An(e,{strict:!1})?Mc(e):e)}const cs=new Qc(8192);function Gp(e,t){if(cs.has(`${e}.${t}`))return cs.get(`${e}.${t}`);const r=e.substring(2).toLowerCase(),n=jp(Dc(r)),i=r.split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(n[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return cs.set(`${e}.${t}`,s),s}const Vp=/^0x[a-fA-F0-9]{40}$/,fs=new Qc(8192);function lr(e,t){const{strict:r=!0}=t??{},n=`${e}.${r}`;if(fs.has(n))return fs.get(n);const i=Vp.test(e)?e.toLowerCase()===e?!0:r?Gp(e)===e:!0:!1;return fs.set(n,i),i}function zp(e,t,r,{strict:n}={}){return An(e,{strict:!1})?Wp(e,t,r,{strict:n}):qp(e,t,r,{strict:n})}function rf(e,t,r){if(Fr(e)!==r-t)throw new j0({offset:r,position:"end",size:Fr(e)})}function qp(e,t,r,{strict:n}={}){const i=e.slice(t,r);return n&&rf(i,t,r),i}function Wp(e,t,r,{strict:n}={}){const i=`0x${e.replace("0x","").slice(t*2,r*2)}`;return n&&rf(i,t,r),i}function Kp(e){const{authorizationList:t}=e;if(t)for(const r of t){const{chainId:n}=r,i=r.address;if(!lr(i))throw new ur({address:i});if(n<0)throw new Ii({chainId:n})}to(e)}function Yp(e){const{blobVersionedHashes:t}=e;if(t){if(t.length===0)throw new Xc;for(const r of t){const n=Fr(r),i=si(zp(r,0,1));if(n!==32)throw new Ep({hash:r,size:n});if(i!==Yc)throw new xp({hash:r,version:i})}}to(e)}function to(e){const{chainId:t,maxPriorityFeePerGas:r,maxFeePerGas:n,to:i}=e;if(t<=0)throw new Ii({chainId:t});if(i&&!lr(i))throw new ur({address:i});if(n&&n>Qs)throw new Pi({maxFeePerGas:n});if(r&&n&&r>n)throw new Jc({maxFeePerGas:n,maxPriorityFeePerGas:r})}function Xp(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(t<=0)throw new Ii({chainId:t});if(s&&!lr(s))throw new ur({address:s});if(r||i)throw new de("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid EIP-2930 Transaction attribute.");if(n&&n>Qs)throw new Pi({maxFeePerGas:n})}function Jp(e){const{chainId:t,maxPriorityFeePerGas:r,gasPrice:n,maxFeePerGas:i,to:s}=e;if(s&&!lr(s))throw new ur({address:s});if(typeof t<"u"&&t<=0)throw new Ii({chainId:t});if(r||i)throw new de("`maxFeePerGas`/`maxPriorityFeePerGas` is not a valid Legacy Transaction attribute.");if(n&&n>Qs)throw new Pi({maxFeePerGas:n})}function Qp(e){if(e.type)return e.type;if(typeof e.authorizationList<"u")return"eip7702";if(typeof e.blobs<"u"||typeof e.blobVersionedHashes<"u"||typeof e.maxFeePerBlobGas<"u"||typeof e.sidecars<"u")return"eip4844";if(typeof e.maxFeePerGas<"u"||typeof e.maxPriorityFeePerGas<"u")return"eip1559";if(typeof e.gasPrice<"u")return typeof e.accessList<"u"?"eip2930":"legacy";throw new yp({transaction:e})}function Oi(e){if(!e||e.length===0)return[];const t=[];for(let r=0;r<e.length;r++){const{address:n,storageKeys:i}=e[r];for(let s=0;s<i.length;s++)if(i[s].length-2!==64)throw new mp({storageKey:i[s]});if(!lr(n,{strict:!1}))throw new ur({address:n});t.push([n,i])}return t}function Zp(e,t){const r=Qp(e);return r==="eip1559"?ry(e,t):r==="eip2930"?ny(e,t):r==="eip4844"?ty(e,t):r==="eip7702"?ey(e,t):iy(e,t)}function ey(e,t){const{authorizationList:r,chainId:n,gas:i,nonce:s,to:o,value:a,maxFeePerGas:u,maxPriorityFeePerGas:h,accessList:d,data:p}=e;Kp(e);const v=Oi(d),y=bp(r);return kn(["0x04",fr([Q(n),s?Q(s):"0x",h?Q(h):"0x",u?Q(u):"0x",i?Q(i):"0x",o??"0x",a?Q(a):"0x",p??"0x",v,y,...Bn(e,t)])])}function ty(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:o,maxFeePerBlobGas:a,maxFeePerGas:u,maxPriorityFeePerGas:h,accessList:d,data:p}=e;Yp(e);let v=e.blobVersionedHashes,y=e.sidecars;if(e.blobs&&(typeof v>"u"||typeof y>"u")){const x=typeof e.blobs[0]=="string"?e.blobs:e.blobs.map(E=>Xt(E)),g=e.kzg,S=zc({blobs:x,kzg:g});if(typeof v>"u"&&(v=_p({commitments:S})),typeof y>"u"){const E=qc({blobs:x,commitments:S,kzg:g});y=Tp({blobs:x,commitments:S,proofs:E})}}const I=Oi(d),k=[Q(r),i?Q(i):"0x",h?Q(h):"0x",u?Q(u):"0x",n?Q(n):"0x",s??"0x",o?Q(o):"0x",p??"0x",I,a?Q(a):"0x",v??[],...Bn(e,t)],B=[],R=[],U=[];if(y)for(let x=0;x<y.length;x++){const{blob:g,commitment:S,proof:E}=y[x];B.push(g),R.push(S),U.push(E)}return kn(["0x03",fr(y?[k,B,R,U]:k)])}function ry(e,t){const{chainId:r,gas:n,nonce:i,to:s,value:o,maxFeePerGas:a,maxPriorityFeePerGas:u,accessList:h,data:d}=e;to(e);const p=Oi(h),v=[Q(r),i?Q(i):"0x",u?Q(u):"0x",a?Q(a):"0x",n?Q(n):"0x",s??"0x",o?Q(o):"0x",d??"0x",p,...Bn(e,t)];return kn(["0x02",fr(v)])}function ny(e,t){const{chainId:r,gas:n,data:i,nonce:s,to:o,value:a,accessList:u,gasPrice:h}=e;Xp(e);const d=Oi(u),p=[Q(r),s?Q(s):"0x",h?Q(h):"0x",n?Q(n):"0x",o??"0x",a?Q(a):"0x",i??"0x",d,...Bn(e,t)];return kn(["0x01",fr(p)])}function iy(e,t){const{chainId:r=0,gas:n,data:i,nonce:s,to:o,value:a,gasPrice:u}=e;Jp(e);let h=[s?Q(s):"0x",u?Q(u):"0x",n?Q(n):"0x",o??"0x",a?Q(a):"0x",i??"0x"];if(t){const d=(()=>{if(t.v>=35n)return(t.v-35n)/2n>0?t.v:27n+(t.v===35n?0n:1n);if(r>0)return BigInt(r*2)+BigInt(35n+t.v-27n);const y=27n+(t.v===27n?0n:1n);if(t.v!==y)throw new pp({v:t.v});return y})(),p=ii(t.r),v=ii(t.s);h=[...h,Q(d),p==="0x00"?"0x":p,v==="0x00"?"0x":v]}else r>0&&(h=[...h,Q(r),"0x","0x"]);return fr(h)}function Bn(e,t){const r=t??e,{v:n,yParity:i}=r;if(typeof r.r>"u")return[];if(typeof r.s>"u")return[];if(typeof n>"u"&&typeof i>"u")return[];const s=ii(r.r),o=ii(r.s);return[typeof i=="number"?i?Q(1):"0x":n===0n?"0x":n===1n?Q(1):n===27n?"0x":Q(1),s==="0x00"?"0x":s,o==="0x00"?"0x":o]}const sy={gasPriceOracle:{address:"0x420000000000000000000000000000000000000F"},l1Block:{address:"0x4200000000000000000000000000000000000015"},l2CrossDomainMessenger:{address:"0x4200000000000000000000000000000000000007"},l2Erc721Bridge:{address:"0x4200000000000000000000000000000000000014"},l2StandardBridge:{address:"0x4200000000000000000000000000000000000010"},l2ToL1MessagePasser:{address:"0x4200000000000000000000000000000000000016"}},oy={block:tp({format(e){var r;return{transactions:(r=e.transactions)==null?void 0:r.map(n=>{if(typeof n=="string")return n;const i=Js(n);return i.typeHex==="0x7e"&&(i.isSystemTx=n.isSystemTx,i.mint=n.mint?Ar(n.mint):void 0,i.sourceHash=n.sourceHash,i.type="deposit"),i}),stateRoot:e.stateRoot}}}),transaction:Q0({format(e){const t={};return e.type==="0x7e"&&(t.isSystemTx=e.isSystemTx,t.mint=e.mint?Ar(e.mint):void 0,t.sourceHash=e.sourceHash,t.type="deposit"),t}}),transactionReceipt:sp({format(e){return{l1GasPrice:e.l1GasPrice?Ar(e.l1GasPrice):null,l1GasUsed:e.l1GasUsed?Ar(e.l1GasUsed):null,l1Fee:e.l1Fee?Ar(e.l1Fee):null,l1FeeScalar:e.l1FeeScalar?Number(e.l1FeeScalar):null}}})};function ay(e,t){return uy(e)?fy(e):Zp(e,t)}const cy={transaction:ay};function fy(e){ly(e);const{sourceHash:t,data:r,from:n,gas:i,isSystemTx:s,mint:o,to:a,value:u}=e,h=[t,n,a??"0x",o?Q(o):"0x",u?Q(u):"0x",i?Q(i):"0x",s?"0x1":"0x",r??"0x"];return kn(["0x7e",fr(h)])}function uy(e){return e.type==="deposit"||typeof e.sourceHash<"u"}function ly(e){const{from:t,to:r}=e;if(t&&!lr(t))throw new ur({address:t});if(r&&!lr(r))throw new ur({address:r})}const oi={contracts:sy,formatters:oy,serializers:cy},hy=pt({id:42161,name:"Arbitrum One",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://arb1.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://arbiscan.io",apiUrl:"https://api.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:7654707}}}),dy=pt({id:421614,name:"Arbitrum Sepolia",nativeCurrency:{name:"Arbitrum Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia-rollup.arbitrum.io/rpc"]}},blockExplorers:{default:{name:"Arbiscan",url:"https://sepolia.arbiscan.io",apiUrl:"https://api-sepolia.arbiscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:81930}},testnet:!0}),nn=1,py=pt({...oi,id:8453,name:"Base",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://mainnet.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://basescan.org",apiUrl:"https://api.basescan.org/api"}},contracts:{...oi.contracts,disputeGameFactory:{[nn]:{address:"0x43edB88C4B80fDD2AdFF2412A7BebF9dF42cB40e"}},l2OutputOracle:{[nn]:{address:"0x56315b90c40730925ec5485cf004d835058518A0"}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:5022},portal:{[nn]:{address:"0x49048044D57e1C92A77f79988d21Fa8fAF74E97e",blockCreated:17482143}},l1StandardBridge:{[nn]:{address:"0x3154Cf16ccdb4C6d922629664174b904d80F2C35",blockCreated:17482143}}},sourceId:nn}),sn=11155111,yy=pt({...oi,id:84532,network:"base-sepolia",name:"Base Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.base.org"]}},blockExplorers:{default:{name:"Basescan",url:"https://sepolia.basescan.org",apiUrl:"https://api-sepolia.basescan.org/api"}},contracts:{...oi.contracts,disputeGameFactory:{[sn]:{address:"0xd6E6dBf4F7EA0ac412fD8b65ED297e64BB7a06E1"}},l2OutputOracle:{[sn]:{address:"0x84457ca9D0163FbC4bbfe4Dfbb20ba46e48DF254"}},portal:{[sn]:{address:"0x49f53e41452c74589e85ca1677426ba426459e85",blockCreated:4446677}},l1StandardBridge:{[sn]:{address:"0xfd0Bf71F60660E2f608ed56e1659C450eB113120",blockCreated:4446677}},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:1059647}},testnet:!0,sourceId:sn}),my=pt({id:80094,name:"Berachain",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:0},ensRegistry:{address:"0x5b22280886a2f5e09a49bea7e320eab0e5320e28",blockCreated:877007},ensUniversalResolver:{address:"0xddfb18888a9466688235887dec2a10c4f5effee9",blockCreated:877008}},rpcUrls:{default:{http:["https://rpc.berachain.com"]}},blockExplorers:{default:{name:"Berascan",url:"https://berascan.com"}},ensTlds:[".bera"],testnet:!1}),by=pt({id:80084,name:"Berachain bArtio",nativeCurrency:{decimals:18,name:"BERA Token",symbol:"BERA"},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:109269},ensRegistry:{address:"0xB0eef18971290b333450586D33dcA6cE122651D2",blockCreated:7736794},ensUniversalResolver:{address:"0x41692Ef1EA0C79E6b73077E4A67572D2BDbD7057",blockCreated:7736795}},ensTlds:[".bera"],rpcUrls:{default:{http:["https://bartio.rpc.berachain.com"]}},blockExplorers:{default:{name:"Berachain bArtio Beratrail",url:"https://bartio.beratrail.io"}},testnet:!0}),wy=pt({id:5115,name:"Citrea Testnet",nativeCurrency:{name:"cBTC",symbol:"cBTC",decimals:18},rpcUrls:{default:{http:["https://rpc.testnet.citrea.xyz"]}},blockExplorers:{default:{name:"Citrea Explorer",url:"https://explorer.testnet.citrea.xyz",apiUrl:"https://explorer.testnet.citrea.xyz/api"}},testnet:!0}),gy=pt({id:1,name:"Ethereum",nativeCurrency:{name:"Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://eth.merkle.io"]}},blockExplorers:{default:{name:"Etherscan",url:"https://etherscan.io",apiUrl:"https://api.etherscan.io/api"}},contracts:{ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xce01f8eee7E479C928F8919abD53E553a36CeF67",blockCreated:19258213},multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:14353601}}}),_y=pt({id:10143,name:"Monad Testnet",nativeCurrency:{name:"Testnet MON Token",symbol:"MON",decimals:18},rpcUrls:{default:{http:["https://testnet-rpc.monad.xyz"]}},blockExplorers:{default:{name:"Monad Testnet explorer",url:"https://testnet.monadexplorer.com"}},contracts:{multicall3:{address:"0xcA11bde05977b3631167028862bE2a173976CA11",blockCreated:251449}},testnet:!0}),vy=pt({id:11155111,name:"Sepolia",nativeCurrency:{name:"Sepolia Ether",symbol:"ETH",decimals:18},rpcUrls:{default:{http:["https://sepolia.drpc.org"]}},blockExplorers:{default:{name:"Etherscan",url:"https://sepolia.etherscan.io",apiUrl:"https://api-sepolia.etherscan.io/api"}},contracts:{multicall3:{address:"0xca11bde05977b3631167028862be2a173976ca11",blockCreated:751532},ensRegistry:{address:"0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e"},ensUniversalResolver:{address:"0xc8Af999e38273D658BE1b921b88A9Ddf005769cC",blockCreated:5317080}},testnet:!0}),Ey={...vy,rpcUrls:{default:{http:["https://ethereum-sepolia-rpc.publicnode.com"]}}},nf={id:998,name:"Hyperliquid EVM Testnet",nativeCurrency:{name:"Hyperliquid",symbol:"HYPE",decimals:18},blockExplorers:{default:{name:"Hyperliquid Explorer",url:"https://testnet.purrsec.com/"}},rpcUrls:{default:{http:["https://rpc.hyperliquid-testnet.xyz/evm"]}}},sf={id:999,name:"HyperEVM",nativeCurrency:{name:"Hyperliquid",symbol:"HYPE",decimals:18},blockExplorers:{default:{name:"Hyperliquid Explorer",url:"https://hyperscan.gas.zip/"}},rpcUrls:{default:{http:["https://rpc.hyperliquid.xyz/evm"]}}},of={ethereum:gy,arbitrum:hy,ethereum_sepolia:Ey,arbitrum_sepolia:dy,ethereum_localnet:le.EthereumLocalnet,arbitrum_localnet:le.ArbitrumLocalnet,base_sepolia:yy,base:py,bera_testnet:by,citrea_testnet:wy,bera:my,monad_testnet:_y,hyperliquid_testnet:nf,hyperliquid:sf},af=async(e,t)=>{var n;const r=of[e];if(r)try{if(r.id===((n=t.chain)==null?void 0:n.id))return re({message:"Already on the network",walletClient:t});await t.switchChain({id:r.id});const i=nt.createWalletClient({account:t.account,chain:r,transport:nt.custom(t.transport)});return re({message:"Switched chain",walletClient:i})}catch(i){if(xy(i))try{await t.addChain({chain:r});const s=nt.createWalletClient({account:t.account,chain:r,transport:nt.custom(window.ethereum)});return re({message:"Added network",walletClient:s})}catch{return M("Failed to add network")}else return M("Failed to switch network")}else return M("Chain not supported")},xy=e=>typeof e=="object"&&e!==null&&"code"in e&&e.code===4902,Sy=[{inputs:[{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"InvalidShortString",type:"error"},{inputs:[],name:"NativeHTLC__DuplicateOrder",type:"error"},{inputs:[],name:"NativeHTLC__IncorrectFundsRecieved",type:"error"},{inputs:[],name:"NativeHTLC__IncorrectSecret",type:"error"},{inputs:[],name:"NativeHTLC__InsufficientBalance",type:"error"},{inputs:[],name:"NativeHTLC__InvalidRedeemerSignature",type:"error"},{inputs:[],name:"NativeHTLC__OrderFulfilled",type:"error"},{inputs:[],name:"NativeHTLC__OrderNotExpired",type:"error"},{inputs:[],name:"NativeHTLC__OrderNotInitiated",type:"error"},{inputs:[],name:"NativeHTLC__SameInitiatorAndRedeemer",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAddressInitiator",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAddressRedeemer",type:"error"},{inputs:[],name:"NativeHTLC__ZeroAmount",type:"error"},{inputs:[],name:"NativeHTLC__ZeroTimelock",type:"error"},{inputs:[{internalType:"string",name:"str",type:"string"}],name:"StringTooLong",type:"error"},{anonymous:!1,inputs:[],name:"EIP712DomainChanged",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Initiated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"},{indexed:!0,internalType:"bytes32",name:"secretHash",type:"bytes32"},{indexed:!1,internalType:"bytes",name:"secret",type:"bytes"}],name:"Redeemed",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"Refunded",type:"event"},{inputs:[],name:"eip712Domain",outputs:[{internalType:"bytes1",name:"fields",type:"bytes1"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"version",type:"string"},{internalType:"uint256",name:"chainId",type:"uint256"},{internalType:"address",name:"verifyingContract",type:"address"},{internalType:"bytes32",name:"salt",type:"bytes32"},{internalType:"uint256[]",name:"extensions",type:"uint256[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiate",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"address payable",name:"initiator",type:"address"},{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"bytes32",name:"secretHash",type:"bytes32"}],name:"initiateOnBehalf",outputs:[],stateMutability:"payable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"signature",type:"bytes"}],name:"instantRefund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"instantRefundDigest",outputs:[{internalType:"bytes32",name:"",type:"bytes32"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"",type:"bytes32"}],name:"orders",outputs:[{internalType:"bool",name:"isFulfilled",type:"bool"},{internalType:"address payable",name:"initiator",type:"address"},{internalType:"address payable",name:"redeemer",type:"address"},{internalType:"uint256",name:"initiatedAt",type:"uint256"},{internalType:"uint256",name:"timelock",type:"uint256"},{internalType:"uint256",name:"amount",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"},{internalType:"bytes",name:"secret",type:"bytes"}],name:"redeem",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[{internalType:"bytes32",name:"orderID",type:"bytes32"}],name:"refund",outputs:[],stateMutability:"nonpayable",type:"function"},{inputs:[],name:"token",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"}];class cf{constructor(t,r,n){this.url=new j.Url("/relayer",t),this.auth=n,this.wallet=r}get htlcActorAddress(){if(!this.wallet.account)throw new Error("No account found");return this.wallet.account.address}async initiate(t){if(!this.wallet.account)return j.Err("No account found");if(this.wallet.account.address.toLowerCase()!==t.source_swap.initiator.toLowerCase())return j.Err("Account address and order initiator mismatch");if(!le.isEVM(t.source_swap.chain))return j.Err("Source chain is not an EVM chain");const r=await af(t.source_swap.chain,this.wallet);if(r.error)return j.Err(r.error);if(this.wallet=r.val.walletClient,!this.wallet.account)return j.Err("No account found");const{create_order:n,source_swap:i}=t;if(!i.amount||!i.redeemer||!n.timelock||!n.secret_hash)return j.Err("Invalid order");const s=j.with0x(n.secret_hash),o=BigInt(n.timelock),a=j.with0x(i.redeemer),u=BigInt(i.amount),h=await this.getTokenAddress(t.source_swap.asset);return h.error?j.Err(h.error):le.isEvmNativeToken(t.source_swap.chain,h.val)?this._initiateOnNativeHTLC(s,o,u,a,t.source_swap.asset):this._initiateOnErc20HTLC(s,o,u,a,t.source_swap.asset,h.val,n.create_id)}async getTokenAddress(t){try{const n=await nt.getContract({address:j.with0x(t),abi:oa,client:this.wallet}).read.token();return j.Ok(n)}catch(r){return j.Err("Failed to get token address",String(r))}}async _initiateOnNativeHTLC(t,r,n,i,s){if(!this.wallet.account)return j.Err("No account found");try{const a=await nt.getContract({address:j.with0x(s),abi:Sy,client:this.wallet}).write.initiate([i,r,n,t],{account:this.wallet.account,chain:this.wallet.chain,value:n});return j.Ok(a)}catch(o){return j.Err("Failed to initiate on native HTLC",String(o))}}async _initiateOnErc20HTLC(t,r,n,i,s,o,a){if(!this.wallet.account)return j.Err("No account found");try{const u=await this.auth.getAuthHeaders();if(u.error)return j.Err(u.error);const h=nt.getContract({address:j.with0x(s),abi:oa,client:this.wallet}),d=await j.checkAllowanceAndApprove(Number(n),o,s,this.wallet);if(d.error)return j.Err(d.error);const p=await h.read.eip712Domain(),v=await this.wallet.signTypedData({account:this.wallet.account,domain:{name:p[1],version:p[2],chainId:Number(p[3]),verifyingContract:p[4]},types:{Initiate:[{name:"redeemer",type:"address"},{name:"timelock",type:"uint256"},{name:"amount",type:"uint256"},{name:"secretHash",type:"bytes32"}]},primaryType:"Initiate",message:{redeemer:i,timelock:r,amount:n,secretHash:t}}),y={...u.val,"Content-Type":"application/json"},I=await xt.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:a,signature:v,perform_on:"Source"}),headers:y});return I.error?j.Err(I.error):I.result?j.Ok(I.result):j.Err("Init: No result found")}catch(u){return console.log("init error :",u),j.Err(String(u))}}async redeem(t,r){try{const n=await this.auth.getAuthHeaders();if(n.error)return j.Err(n.error);const i=await xt.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:tr(r),perform_on:"Destination"}),headers:{...n.val,"Content-Type":"application/json"}});return i.error?j.Err(i.error):i.result?j.Ok(i.result):j.Err("Redeem: No result found")}catch(n){return j.Err(String(n))}}async refund(){return j.Err("Refund not supported")}}const ff=[{name:"LockingContract",type:"impl",interface_name:"src::mintable_lock_interface::ILockingContract"},{name:"src::mintable_lock_interface::ILockingContract",type:"interface",items:[{name:"set_locking_contract",type:"function",inputs:[{name:"locking_contract",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"get_locking_contract",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"}]},{name:"LockAndDelegate",type:"impl",interface_name:"src::mintable_lock_interface::ILockAndDelegate"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"src::mintable_lock_interface::ILockAndDelegate",type:"interface",items:[{name:"lock_and_delegate",type:"function",inputs:[{name:"delegatee",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"lock_and_delegate_by_sig",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"delegatee",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"},{name:"nonce",type:"core::felt252"},{name:"expiry",type:"core::integer::u64"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"MintableToken",type:"impl",interface_name:"src::mintable_token_interface::IMintableToken"},{name:"src::mintable_token_interface::IMintableToken",type:"interface",items:[{name:"permissioned_mint",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"permissioned_burn",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"}]},{name:"MintableTokenCamelImpl",type:"impl",interface_name:"src::mintable_token_interface::IMintableTokenCamel"},{name:"src::mintable_token_interface::IMintableTokenCamel",type:"interface",items:[{name:"permissionedMint",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"},{name:"permissionedBurn",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[],state_mutability:"external"}]},{name:"Replaceable",type:"impl",interface_name:"src::replaceability_interface::IReplaceable"},{name:"core::array::Span::<core::felt252>",type:"struct",members:[{name:"snapshot",type:"@core::array::Array::<core::felt252>"}]},{name:"src::replaceability_interface::EICData",type:"struct",members:[{name:"eic_hash",type:"core::starknet::class_hash::ClassHash"},{name:"eic_init_data",type:"core::array::Span::<core::felt252>"}]},{name:"core::option::Option::<src::replaceability_interface::EICData>",type:"enum",variants:[{name:"Some",type:"src::replaceability_interface::EICData"},{name:"None",type:"()"}]},{name:"core::bool",type:"enum",variants:[{name:"False",type:"()"},{name:"True",type:"()"}]},{name:"src::replaceability_interface::ImplementationData",type:"struct",members:[{name:"impl_hash",type:"core::starknet::class_hash::ClassHash"},{name:"eic_data",type:"core::option::Option::<src::replaceability_interface::EICData>"},{name:"final",type:"core::bool"}]},{name:"src::replaceability_interface::IReplaceable",type:"interface",items:[{name:"get_upgrade_delay",type:"function",inputs:[],outputs:[{type:"core::integer::u64"}],state_mutability:"view"},{name:"get_impl_activation_time",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[{type:"core::integer::u64"}],state_mutability:"view"},{name:"add_new_implementation",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"},{name:"remove_implementation",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"},{name:"replace_to",type:"function",inputs:[{name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}],outputs:[],state_mutability:"external"}]},{name:"AccessControlImplExternal",type:"impl",interface_name:"src::access_control_interface::IAccessControl"},{name:"src::access_control_interface::IAccessControl",type:"interface",items:[{name:"has_role",type:"function",inputs:[{name:"role",type:"core::felt252"},{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"get_role_admin",type:"function",inputs:[{name:"role",type:"core::felt252"}],outputs:[{type:"core::felt252"}],state_mutability:"view"}]},{name:"RolesImpl",type:"impl",interface_name:"src::roles_interface::IMinimalRoles"},{name:"src::roles_interface::IMinimalRoles",type:"interface",items:[{name:"is_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"is_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::bool"}],state_mutability:"view"},{name:"register_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"remove_governance_admin",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"register_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"remove_upgrade_governor",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[],state_mutability:"external"},{name:"renounce",type:"function",inputs:[{name:"role",type:"core::felt252"}],outputs:[],state_mutability:"external"}]},{name:"ERC20Impl",type:"impl",interface_name:"openzeppelin::token::erc20::interface::IERC20"},{name:"openzeppelin::token::erc20::interface::IERC20",type:"interface",items:[{name:"name",type:"function",inputs:[],outputs:[{type:"core::felt252"}],state_mutability:"view"},{name:"symbol",type:"function",inputs:[],outputs:[{type:"core::felt252"}],state_mutability:"view"},{name:"decimals",type:"function",inputs:[],outputs:[{type:"core::integer::u8"}],state_mutability:"view"},{name:"total_supply",type:"function",inputs:[],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"balance_of",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"allowance",type:"function",inputs:[{name:"owner",type:"core::starknet::contract_address::ContractAddress"},{name:"spender",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"transfer",type:"function",inputs:[{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"transfer_from",type:"function",inputs:[{name:"sender",type:"core::starknet::contract_address::ContractAddress"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"approve",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"}]},{name:"ERC20CamelOnlyImpl",type:"impl",interface_name:"openzeppelin::token::erc20::interface::IERC20CamelOnly"},{name:"openzeppelin::token::erc20::interface::IERC20CamelOnly",type:"interface",items:[{name:"totalSupply",type:"function",inputs:[],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"balanceOf",type:"function",inputs:[{name:"account",type:"core::starknet::contract_address::ContractAddress"}],outputs:[{type:"core::integer::u256"}],state_mutability:"view"},{name:"transferFrom",type:"function",inputs:[{name:"sender",type:"core::starknet::contract_address::ContractAddress"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"amount",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"name",type:"core::felt252"},{name:"symbol",type:"core::felt252"},{name:"decimals",type:"core::integer::u8"},{name:"initial_supply",type:"core::integer::u256"},{name:"recipient",type:"core::starknet::contract_address::ContractAddress"},{name:"permitted_minter",type:"core::starknet::contract_address::ContractAddress"},{name:"provisional_governance_admin",type:"core::starknet::contract_address::ContractAddress"},{name:"upgrade_delay",type:"core::integer::u64"}]},{name:"increase_allowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"added_value",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"decrease_allowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"subtracted_value",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"increaseAllowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"addedValue",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{name:"decreaseAllowance",type:"function",inputs:[{name:"spender",type:"core::starknet::contract_address::ContractAddress"},{name:"subtractedValue",type:"core::integer::u256"}],outputs:[{type:"core::bool"}],state_mutability:"external"},{kind:"struct",name:"src::strk::erc20_lockable::ERC20Lockable::Transfer",type:"event",members:[{kind:"data",name:"from",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"to",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"value",type:"core::integer::u256"}]},{kind:"struct",name:"src::strk::erc20_lockable::ERC20Lockable::Approval",type:"event",members:[{kind:"data",name:"owner",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"spender",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"value",type:"core::integer::u256"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationAdded",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationRemoved",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationReplaced",type:"event",members:[{kind:"data",name:"implementation_data",type:"src::replaceability_interface::ImplementationData"}]},{kind:"struct",name:"src::replaceability_interface::ImplementationFinalized",type:"event",members:[{kind:"data",name:"impl_hash",type:"core::starknet::class_hash::ClassHash"}]},{kind:"struct",name:"src::access_control_interface::RoleGranted",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"sender",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::access_control_interface::RoleRevoked",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"sender",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::access_control_interface::RoleAdminChanged",type:"event",members:[{kind:"data",name:"role",type:"core::felt252"},{kind:"data",name:"previous_admin_role",type:"core::felt252"},{kind:"data",name:"new_admin_role",type:"core::felt252"}]},{kind:"struct",name:"src::roles_interface::GovernanceAdminAdded",type:"event",members:[{kind:"data",name:"added_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"added_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::GovernanceAdminRemoved",type:"event",members:[{kind:"data",name:"removed_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"removed_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::UpgradeGovernorAdded",type:"event",members:[{kind:"data",name:"added_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"added_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"src::roles_interface::UpgradeGovernorRemoved",type:"event",members:[{kind:"data",name:"removed_account",type:"core::starknet::contract_address::ContractAddress"},{kind:"data",name:"removed_by",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"enum",name:"src::strk::erc20_lockable::ERC20Lockable::Event",type:"event",variants:[{kind:"nested",name:"Transfer",type:"src::strk::erc20_lockable::ERC20Lockable::Transfer"},{kind:"nested",name:"Approval",type:"src::strk::erc20_lockable::ERC20Lockable::Approval"},{kind:"nested",name:"ImplementationAdded",type:"src::replaceability_interface::ImplementationAdded"},{kind:"nested",name:"ImplementationRemoved",type:"src::replaceability_interface::ImplementationRemoved"},{kind:"nested",name:"ImplementationReplaced",type:"src::replaceability_interface::ImplementationReplaced"},{kind:"nested",name:"ImplementationFinalized",type:"src::replaceability_interface::ImplementationFinalized"},{kind:"nested",name:"RoleGranted",type:"src::access_control_interface::RoleGranted"},{kind:"nested",name:"RoleRevoked",type:"src::access_control_interface::RoleRevoked"},{kind:"nested",name:"RoleAdminChanged",type:"src::access_control_interface::RoleAdminChanged"},{kind:"nested",name:"GovernanceAdminAdded",type:"src::roles_interface::GovernanceAdminAdded"},{kind:"nested",name:"GovernanceAdminRemoved",type:"src::roles_interface::GovernanceAdminRemoved"},{kind:"nested",name:"UpgradeGovernorAdded",type:"src::roles_interface::UpgradeGovernorAdded"},{kind:"nested",name:"UpgradeGovernorRemoved",type:"src::roles_interface::UpgradeGovernorRemoved"}]}],uf=async(e,t,r,n,i)=>{try{const s=new Ne.RpcProvider({nodeUrl:i}),o=await pa(e.address,t,r,i);if(o.error)return M(o.error);const a=Ne.cairo.uint256(BigInt(Ne.uint256.UINT_256_MAX));if(o.val<n){const u=await e.execute([{contractAddress:Mn(t),entrypoint:"approve",calldata:[r,a.low,a.high]}]);await s.waitForTransaction(u.transaction_hash,{retryInterval:3e3,successStates:[Ne.TransactionExecutionStatus.SUCCEEDED]}),await j.sleep(2e3);let h=0n;for(let d=0;d<20;d++){const p=await pa(e.address,t,r,i);if(p.error)return M(p.error);if(h=p.val,h>=n)break;await j.sleep(2e3)}return h<n?M("Allowance not approved"):re(u.transaction_hash)}return re("Allowance already approved")}catch(s){return M(`Failed to check or approve allowance: ${s instanceof Error?s.message:String(s)}`)}},pa=async(e,t,r,n)=>{try{const i=new Ne.RpcProvider({nodeUrl:n}),o=await new Ne.Contract(ff,Mn(t),i).call("allowance",[Mn(e),Mn(r)]);return re(BigInt((o==null?void 0:o.toString())||"0"))}catch(i){return M(`Failed to check allowance: ${i instanceof Error?i.message:String(i)}`)}},lf=[{name:"HTLC",type:"impl",interface_name:"starknet_htlc::interface::IHTLC"},{name:"core::integer::u256",type:"struct",members:[{name:"low",type:"core::integer::u128"},{name:"high",type:"core::integer::u128"}]},{name:"starknet_htlc::interface::IHTLC",type:"interface",items:[{name:"token",type:"function",inputs:[],outputs:[{type:"core::starknet::contract_address::ContractAddress"}],state_mutability:"view"},{name:"initiate",type:"function",inputs:[{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_on_behalf",type:"function",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u32; 8]"}],outputs:[],state_mutability:"external"},{name:"initiate_with_signature",type:"function",inputs:[{name:"initiator",type:"core::starknet::contract_address::ContractAddress"},{name:"redeemer",type:"core::starknet::contract_address::ContractAddress"},{name:"timelock",type:"core::integer::u128"},{name:"amount",type:"core::integer::u256"},{name:"secret_hash",type:"[core::integer::u32; 8]"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"},{name:"redeem",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"secret",type:"core::array::Array::<core::integer::u32>"}],outputs:[],state_mutability:"external"},{name:"refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"}],outputs:[],state_mutability:"external"},{name:"instant_refund",type:"function",inputs:[{name:"order_id",type:"core::felt252"},{name:"signature",type:"core::array::Array::<core::felt252>"}],outputs:[],state_mutability:"external"}]},{name:"constructor",type:"constructor",inputs:[{name:"token",type:"core::starknet::contract_address::ContractAddress"}]},{kind:"struct",name:"starknet_htlc::interface::events::Initiated",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"amount",type:"core::integer::u256"}]},{kind:"struct",name:"starknet_htlc::interface::events::Redeemed",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"},{kind:"data",name:"secret_hash",type:"[core::integer::u32; 8]"},{kind:"data",name:"secret",type:"core::array::Array::<core::integer::u32>"}]},{kind:"struct",name:"starknet_htlc::interface::events::Refunded",type:"event",members:[{kind:"key",name:"order_id",type:"core::felt252"}]},{kind:"enum",name:"starknet_htlc::htlc::HTLC::Event",type:"event",variants:[{kind:"nested",name:"Initiated",type:"starknet_htlc::interface::events::Initiated"},{kind:"nested",name:"Redeemed",type:"starknet_htlc::interface::events::Redeemed"},{kind:"nested",name:"Refunded",type:"starknet_htlc::interface::events::Refunded"}]}],Ty={name:"HTLC",version:Ne.shortString.encodeShortString("1"),chainId:"0x534e5f5345504f4c4941",revision:Ne.TypedDataRevision.ACTIVE},Ay={StarknetDomain:[{name:"name",type:"shortstring"},{name:"version",type:"shortstring"},{name:"chainId",type:"shortstring"},{name:"revision",type:"shortstring"}],Initiate:[{name:"redeemer",type:"ContractAddress"},{name:"amount",type:"u256"},{name:"timelock",type:"u128"},{name:"secretHash",type:"u128*"}]},ky={[j.Network.MAINNET]:"https://starknet-mainnet.public.blastapi.io/rpc/v0_8",[j.Network.TESTNET]:"https://starknet-sepolia.public.blastapi.io/rpc/v0_8"};class hf{constructor(t,r,n){this.nodeUrl=ky[n],this.url=new j.Url("/",t),this.account=r}get htlcActorAddress(){if(!this.account.address)throw new Error("No account found");return this.account.address}async initiate(t){if(!this.account.address)return M("No account address");const{create_order:r,source_swap:n}=t,{redeemer:i,amount:s}=n;if(!s||!i||!r.secret_hash||!r.timelock)return M("Invalid order");try{const o=new Ne.Contract(lf,t.source_swap.asset,this.account),a=await(o==null?void 0:o.token()),u=Ne.num.toHex(a),h=await uf(this.account,u,n.asset,BigInt(s),this.nodeUrl);if(h.error)return M(h.error);const d={domain:Ty,primaryType:"Initiate",types:Ay,message:{redeemer:i,amount:Ne.cairo.uint256(s),timelock:r.timelock,secretHash:j.hexToU32Array(r.secret_hash)}},p=await this.account.signMessage(d),v=kf(p);if(v.error)return M(v.error);const y=await xt.post(this.url.endpoint("initiate"),{body:JSON.stringify({order_id:r.create_id,signature:v.val,perform_on:"Source"}),headers:{"Content-Type":"application/json"},retryCount:5,retryDelay:2e3});return y.error?M(y.error):y.result?re(y.result):M("Init: No result found")}catch(o){return M(String(o))}}async redeem(t,r){try{const n=await xt.post(this.url.endpoint("redeem"),{body:JSON.stringify({order_id:t.create_order.create_id,secret:r,perform_on:"Destination"}),headers:{"Content-Type":"application/json"},retryCount:5,retryDelay:2e3});return n.error?M(n.error):n.result?re(n.result):M("Redeem: No result found")}catch(n){return M(String(n))}}async refund(){return M("Refund is taken care of by the relayer")}}class ro extends j.EventBroker{constructor(t){if(super(),this.environment=j.Environment.TESTNET,this.getOrderThreshold=20,this.refundSacpCache=new Map,this.bitcoinRedeemCache=new Jl,typeof t.digestKey=="string"){const n=j.DigestKey.from(t.digestKey);if(n.error)throw new Error(n.error);this._digestKey=n.val}else this._digestKey=t.digestKey;if(typeof t.environment=="string"){if(this.environment=t.environment,this._api=t.environment===j.Environment.MAINNET?fn.mainnet:t.environment===j.Environment.TESTNET?fn.testnet:void 0,!this._api)throw new Error("API not found, invalid environment "+t.environment)}else this._api=t.environment;this._quote=t.quote??new Ja(this._api.quote),this._auth=t.auth??j.Siwe.fromDigestKey(new j.Url(this._api.auth),this._digestKey),this._orderbook=t.orderbook??new le.Orderbook(new j.Url(this._api.orderbook)),this._evmHTLC=t.htlc.evm,this._starknetHTLC=t.htlc.starknet,this._secretManager=t.secretManager??bn.fromDigestKey(this._digestKey.digestKey),this.orderExecutorCache=new Xl,this._blockNumberFetcher=t.blockNumberFetcher??new Xa(this._api.info,this.environment);const r=new Or.BitcoinProvider(Tf(this.environment));this._btcWallet=Or.BitcoinWallet.fromPrivateKey(this._digestKey.digestKey,r)}static fromWallets(t){let r;if(typeof t.digestKey=="string"){const s=j.DigestKey.from(t.digestKey);if(s.error)throw new Error(s.error);r=s.val}else r=t.digestKey;let n;if(typeof t.environment=="string"?n=t.environment===j.Environment.MAINNET?fn.mainnet:t.environment===j.Environment.TESTNET?fn.testnet:void 0:n=t.environment,!n)throw new Error("API not found, invalid environment "+t.environment);const i={evm:t.wallets.evm?new cf(n.evmRelay,t.wallets.evm,j.Siwe.fromDigestKey(new j.Url(n.auth),r)):void 0,starknet:t.wallets.starknet?new hf(n.starknetRelay,t.wallets.starknet,t.environment===j.Environment.MAINNET?j.Network.MAINNET:j.Network.TESTNET):void 0};return new ro({htlc:i,...t})}get evmHTLC(){return this._evmHTLC}get starknetHTLC(){return this._starknetHTLC}get quote(){return this._quote}get btcWallet(){return this._btcWallet}get orderbook(){return this._orderbook}get blockNumberFetcher(){return this._blockNumberFetcher}get secretManager(){return this._secretManager}get auth(){return this._auth}get digestKey(){return this._digestKey}async swap(t){const r=await this.validateAndFillParams(t);if(r.error)return M(r.error);const{sendAddress:n,receiveAddress:i,timelock:s}=r.val,o=Date.now().toString(),a=await this._secretManager.generateSecret(o);if(a.error)return M(a.error);const{strategyId:u,btcAddress:h}=t.additionalData,d={strategy_id:u,...h&&{bitcoin_optional_recipient:h}},p={source_chain:t.fromAsset.chain,destination_chain:t.toAsset.chain,source_asset:t.fromAsset.atomicSwapAddress,destination_asset:t.toAsset.atomicSwapAddress,initiator_source_address:n,initiator_destination_address:i,source_amount:t.sendAmount,destination_amount:t.receiveAmount,fee:"1",nonce:o,timelock:s,secret_hash:tr(a.val.secretHash),min_destination_confirmations:t.minDestinationConfirmations??0,additional_data:d},v=await this._quote.getAttestedQuote(p);if(v.error)return M(v.error);const y=await this._orderbook.createOrder(v.val,this.auth);if(y.error)return M(y.error);const I=await this.pollOrder(y.val);return I.error?M(I.error):re(I.val)}async validateAndFillParams(t){if(!t.additionalData.strategyId)return M("StrategyId is required");if(!t.fromAsset||!t.toAsset)return M("Source and destination assets are required for swap");if(t.fromAsset.chain===t.toAsset.chain&&t.fromAsset.atomicSwapAddress===t.toAsset.atomicSwapAddress)return M("Source and destination assets cannot be the same");if(le.isMainnet(t.fromAsset.chain)&&!le.isMainnet(t.toAsset.chain)||!le.isMainnet(t.fromAsset.chain)&&le.isMainnet(t.toAsset.chain))return M("Both assets should be on the same network (either mainnet or testnet)");const r=this.validateAmount(t.sendAmount);if(r.error)return M(r.error);const n=this.validateAmount(t.receiveAmount);if(n.error)return M(n.error);if(r<n)return M("Send amount should be greater than receive amount");const i=le.getTimeLock(t.fromAsset.chain);if(!i)return M("Unsupported chain for timelock");if((le.isBitcoin(t.fromAsset.chain)||le.isBitcoin(t.toAsset.chain))&&!t.additionalData.btcAddress)return M("btcAddress in additionalData is required if source or destination chain is bitcoin, it is used as refund or redeem address.");const s=await this.getAddresses(t.fromAsset.chain);if(s.error)return M(s.error);const o=await this.getAddresses(t.toAsset.chain);return o.error?M(o.error):re({sendAddress:s.val,receiveAddress:o.val,timelock:t.timelock??i})}async getAddresses(t){var n;switch(le.getBlockchainType(t)){case le.BlockchainType.EVM:return this._evmHTLC?re(this._evmHTLC.htlcActorAddress):M("Please provide evmHTLC when initializing garden");case le.BlockchainType.Bitcoin:{const i=await((n=this._btcWallet)==null?void 0:n.getPublicKey());return!i||!xf(i)?M("Invalid btc public key"):re(Ft(i))}case le.BlockchainType.Starknet:return this._starknetHTLC?re(this._starknetHTLC.htlcActorAddress):M("Please provide starknetHTLC when initializing garden");default:return M("Unsupported chain")}}validateAmount(t){if(t==null||t.includes("."))return M("Invalid amount ",t);const r=new mf(t);return!r.isInteger()||r.isNaN()||r.lt(0)||r.isLessThanOrEqualTo(0)?M("Invalid amount ",t):re(r)}async pollOrder(t){let r=await this._orderbook.getOrder(t,!0),n=0;for(;n<this.getOrderThreshold;){if(await j.sleep(1e3),n++,r.error){if(!r.error.includes("result is undefined"))return M(r.error)}else if(r.val&&r.val.create_order.create_id.toLowerCase()===t.toLowerCase())return re(r.val);r=await this._orderbook.getOrder(t,!0)}return M(`Order not found, createOrder id: ${t}`)}async execute(t=5e3){return await this._orderbook.subscribeOrders(this._digestKey.userId,!0,t,async r=>{const n=await this.filterExpiredAndAssignStatus(r.data);if(!n.error&&(this.emit("onPendingOrdersChanged",n.val),r.data.length!==0))for(let i=0;i<n.val.length;i++){const s=n.val[i],o=Bs(s.status);if(le.isBitcoin(s.source_swap.chain)&&s.status===he.InitiateDetected){const a=this.btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");continue}await this.postRefundSACP(s,a)}switch(o){case Te.Redeem:{const a=await this._secretManager.generateSecret(s.create_order.nonce);if(a.error){this.emit("error",s,a.error);return}switch(le.getBlockchainType(s.destination_swap.chain)){case le.BlockchainType.EVM:{await this.evmRedeem(s,a.val.secret);break}case le.BlockchainType.Bitcoin:{const u=this.btcWallet;if(!u){this.emit("error",s,"BTC wallet not found");return}await this.btcRedeem(u,s,a.val.secret);break}case le.BlockchainType.Starknet:{await this.starknetRedeem(s,a.val.secret);break}default:this.emit("error",s,"Unsupported chain: "+s.destination_swap.chain)}break}case Te.Refund:{switch(le.getBlockchainType(s.source_swap.chain)){case le.BlockchainType.EVM:{this.emit("error",s,"EVM refund is automatically done by relay service");break}case le.BlockchainType.Bitcoin:{const a=this.btcWallet;if(!a){this.emit("error",s,"BTC wallet not found");return}await this.btcRefund(a,s);break}case le.BlockchainType.Starknet:{this.emit("error",s,"Starknet refund is automatically done by relay service");break}default:this.emit("error",s,"Unsupported chain: "+s.source_swap.chain)}break}}}},"pending",{per_page:500})}async evmRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing evm redeem"),this.orderExecutorCache.get(t,Te.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._evmHTLC){this.emit("error",t,"EVMHTLC is required");return}const i=await this._evmHTLC.redeem(t,r);if(i.error){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Te.Redeem,t.destination_swap.redeem_tx_hash);return}this.orderExecutorCache.set(t,Te.Redeem,i.val),this.emit("success",t,Te.Redeem,i.val)}async starknetRedeem(t,r){if(this.emit("log",t.create_order.create_id,"executing starknet redeem"),this.orderExecutorCache.get(t,Te.Redeem)){this.emit("log",t.create_order.create_id,"already redeemed");return}if(!this._starknetHTLC){this.emit("error",t,"StarknetHTLC is required");return}const i=await this._starknetHTLC.redeem(t,r);if(i.error){this.emit("error",t,i.error),i.error.includes("Order already redeemed")&&this.orderExecutorCache.set(t,Te.Redeem,t.destination_swap.redeem_tx_hash);return}i.val&&(this.orderExecutorCache.set(t,Te.Redeem,i.val),this.emit("success",t,Te.Redeem,i.val))}async btcRedeem(t,r,n){var a,u;const i=this.bitcoinRedeemCache.get(r.create_order.create_id),s=(a=r.destination_swap.initiate_tx_hash.split(",").at(-1))==null?void 0:a.split(":").at(0);if(!s){this.emit("error",r,"Failed to get initiate_tx_hash");return}let o=!1;if(i)if(i.redeemedFromUTXO&&i.redeemedFromUTXO!==s)o=!0,this.emit("log",r.create_order.create_id,"rbf btc redeem");else if(i.redeemedAt&&Date.now()-i.redeemedAt>1e3*60*15)this.emit("log",r.create_order.create_id,"redeem not confirmed in last 15 minutes"),o=!0;else{this.emit("log",r.create_order.create_id,"btcRedeem: already redeemed");return}else if(r.destination_swap.redeem_tx_hash&&!Number(r.destination_swap.redeem_block_number))try{const h=await(await t.getProvider()).getTransaction(r.destination_swap.redeem_tx_hash);let d=!1;for(const p of h.vin)if(p.txid===s){d=!0;break}if(d){this.emit("log",r.create_order.create_id,"already a valid redeem");let p=0;try{const[v]=await(await t.getProvider()).getTransactionTimes([r.destination_swap.redeem_tx_hash]);v!==0&&(p=v)}catch{p=Date.now()}this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:p,redeemTxHash:r.destination_swap.redeem_tx_hash});return}o=!0}catch(h){if(h.message.includes("Transaction not found"))o=!0;else{this.emit("error",r,"Failed to get redeem tx: "+h);return}}this.emit("log",r.create_order.create_id,"executing btc redeem");try{const d=await(await hn.from(t,Number(r.destination_swap.amount),r.create_order.secret_hash,Ft(r.destination_swap.initiator),Ft(r.destination_swap.redeemer),r.destination_swap.timelock,o?[s]:[])).getRedeemHex(tr(n),(u=r.create_order.additional_data)==null?void 0:u.bitcoin_optional_recipient),p=await this.broadcastRedeemTx(d,r.create_order.create_id);if(p.error||!p.val){this.emit("error",r,p.error||"Failed to broadcast redeem tx");return}o?(this.emit("log",r.create_order.create_id,"rbf: btc redeem success"),this.emit("rbf",r,p.val)):this.emit("success",r,Te.Redeem,p.val),this.bitcoinRedeemCache.set(r.create_order.create_id,{redeemedFromUTXO:s,redeemedAt:Date.now(),redeemTxHash:p.val})}catch(h){console.log("error",h),this.emit("error",r,"Failed btc redeem: "+h)}}async btcRefund(t,r){var n;if(!this.orderExecutorCache.get(r,Te.Refund)){this.emit("log",r.create_order.create_id,"executing btc refund");try{const s=await(await hn.from(t,Number(r.source_swap.amount),r.create_order.secret_hash,Ft(r.source_swap.initiator),Ft(r.source_swap.redeemer),r.source_swap.timelock)).refund((n=r.create_order.additional_data)==null?void 0:n.bitcoin_optional_recipient);this.orderExecutorCache.set(r,Te.Refund,s),this.emit("success",r,Te.Refund,s)}catch(i){this.emit("error",r,"Failed btc refund: "+i)}}}async postRefundSACP(t,r){const n=this.refundSacpCache.get(t.create_order.create_id);if((n==null?void 0:n.initTxHash)===t.source_swap.initiate_tx_hash)return;const i=await hn.from(r,Number(t.source_swap.amount),t.create_order.secret_hash,Ft(t.source_swap.initiator),Ft(t.source_swap.redeemer),t.source_swap.timelock),s=t.create_order.additional_data.bitcoin_optional_recipient;if(s)try{const o=await i.generateInstantRefundSACP(s);if(!this._api)return;const a=new j.Url(this._api.orderbook).endpoint("orders/bitcoin/"+t.create_order.create_id+"/instant-refund");(await xt.post(a,{headers:{"Content-Type":"application/json"},body:JSON.stringify({instant_refund_tx_bytes:o})})).status==="Ok"&&this.refundSacpCache.set(t.create_order.create_id,{initTxHash:t.source_swap.initiate_tx_hash})}catch(o){this.emit("error",t,"Failed to generate and post SACP: "+o);return}}async filterExpiredAndAssignStatus(t){var i;if(t.length===0)return re([]);const r=await((i=this._blockNumberFetcher)==null?void 0:i.fetchBlockNumbers());if(r.error)return M(r.error);const n=[];for(let s=0;s<t.length;s++){const o=t[s];if(ga(o))continue;const a=o.source_swap.chain,u=o.destination_swap.chain,h=r==null?void 0:r.val[a],d=r==null?void 0:r.val[u];if(!h||!d){this.emit("error",o,"Error while fetching CurrentBlockNumbers");continue}const p=ks(o,h,d);n.push({...o,status:p})}return re(n)}async broadcastRedeemTx(t,r){try{if(!this._api)return M("API not found");const n=new j.Url(this._api.evmRelay).endpoint("/bitcoin/redeem "),i=await this._auth.getAuthHeaders(),o=await(await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",...i.val},body:JSON.stringify({redeem_tx_bytes:t,order_id:r})})).json();return o.status==="Ok"&&o.result?re(o.result):M(o.error)}catch(n){return M("Failed to broadcast redeem tx: "+n)}}}const By="https://starknet-sepolia.public.blastapi.io/rpc/v0_7";class Iy{constructor(t,r){this.callData=new Ne.CallData(ff),this.nodeUrl=r||By,this.account=t}get htlcActorAddress(){return this.account.address}async getHTLCContract(t,r=!1){const n=r?t.destination_swap.asset:t.source_swap.asset;return new Ne.Contract(lf,n,this.account)}async initiate(t){try{const n=await(await this.getHTLCContract(t)).token();if(!n)throw new Error("Token address retrieval failed");const i=Ne.num.toHex(n),s=Ne.cairo.uint256(BigInt(t.source_swap.amount));try{const a=await uf(this.account,i,t.source_swap.asset,BigInt(t.source_swap.amount),this.nodeUrl);if(a.error)return M(a.error)}catch(a){return M(`Allowance check failed: ${a}`)}const o=await this.account.execute({contractAddress:t.source_swap.asset,entrypoint:"initiate",calldata:[t.source_swap.redeemer,BigInt(t.source_swap.timelock),s.low,s.high,...j.hexToU32Array(t.create_order.secret_hash)]});if(!o.transaction_hash)throw new Error("Failed to initiate HTLC transaction");return re(o.transaction_hash)}catch(r){return M(`HTLC Initiation Error: ${r}`)}}async redeem(t,r){try{const n=await this.getHTLCContract(t,!0),i=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,s=await this.account.execute({contractAddress:n.address,entrypoint:"redeem",calldata:Ne.CallData.compile({swap_id:i,secret:j.hexToU32Array(r)})});return s.transaction_hash?re(s.transaction_hash):M("Failed to redeem HTLC transaction")}catch{return M("HTLC Redeem Error")}}async refund(t){try{const r=t.create_order.source_chain.includes("starknet")?t.source_swap.swap_id:t.destination_swap.swap_id,n=await this.getHTLCContract(t),i=await this.account.execute({contractAddress:n.address,entrypoint:"refund",calldata:{orderId:r}});return i.transaction_hash?re(i.transaction_hash):M("Failed to refund HTLC transaction")}catch{return M("HTLC Refund Error")}}}exports.API=fn;exports.BlockNumberFetcher=Xa;exports.EvmRelay=cf;exports.Garden=ro;exports.OrderActions=Te;exports.OrderStatus=he;exports.ParseOrderStatus=ks;exports.ParseSwapStatus=hs;exports.Quote=Ja;exports.SecretManager=bn;exports.StarknetHTLC=Iy;exports.StarknetRelay=hf;exports.SwapStatus=be;exports.constructOrderPair=wa;exports.evmToViemChainMap=of;exports.filterDeadlineExpiredOrders=If;exports.hyperliquid=sf;exports.hyperliquidTestnet=nf;exports.isExpired=dn;exports.parseAction=Bf;exports.parseActionFromStatus=Bs;exports.switchOrAddNetwork=af;exports.toXOnly=Ft;exports.validateBTCAddress=Sf;
|