@omnity/ree-client-ts-sdk 0.5.7 → 0.5.9

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.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Hh=e=>{throw TypeError(e)};var Fh=(e,t,n)=>t.has(e)||Hh("Cannot "+n);var Fe=(e,t,n)=>(Fh(e,t,"read from private field"),n?n.call(e):t.get(e)),rn=(e,t,n)=>t.has(e)?Hh("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),zt=(e,t,n,r)=>(Fh(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Mh=(e,t,n,r)=>({set _(i){zt(e,t,i,n)},get _(){return Fe(e,t,r)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function A1(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in e)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function Py(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var vu={},zs={},qh;function v1(){if(qh)return zs;qh=1,zs.byteLength=c,zs.toByteArray=u,zs.fromByteArray=d;for(var e=[],t=[],n=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,s=r.length;i<s;++i)e[i]=r[i],t[r.charCodeAt(i)]=i;t[45]=62,t[95]=63;function o(y){var g=y.length;if(g%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=y.indexOf("=");m===-1&&(m=g);var E=m===g?0:4-m%4;return[m,E]}function c(y){var g=o(y),m=g[0],E=g[1];return(m+E)*3/4-E}function a(y,g,m){return(g+m)*3/4-m}function u(y){var g,m=o(y),E=m[0],_=m[1],S=new n(a(y,E,_)),w=0,T=_>0?E-4:E,O;for(O=0;O<T;O+=4)g=t[y.charCodeAt(O)]<<18|t[y.charCodeAt(O+1)]<<12|t[y.charCodeAt(O+2)]<<6|t[y.charCodeAt(O+3)],S[w++]=g>>16&255,S[w++]=g>>8&255,S[w++]=g&255;return _===2&&(g=t[y.charCodeAt(O)]<<2|t[y.charCodeAt(O+1)]>>4,S[w++]=g&255),_===1&&(g=t[y.charCodeAt(O)]<<10|t[y.charCodeAt(O+1)]<<4|t[y.charCodeAt(O+2)]>>2,S[w++]=g>>8&255,S[w++]=g&255),S}function f(y){return e[y>>18&63]+e[y>>12&63]+e[y>>6&63]+e[y&63]}function l(y,g,m){for(var E,_=[],S=g;S<m;S+=3)E=(y[S]<<16&16711680)+(y[S+1]<<8&65280)+(y[S+2]&255),_.push(f(E));return _.join("")}function d(y){for(var g,m=y.length,E=m%3,_=[],S=16383,w=0,T=m-E;w<T;w+=S)_.push(l(y,w,w+S>T?T:w+S));return E===1?(g=y[m-1],_.push(e[g>>2]+e[g<<4&63]+"==")):E===2&&(g=(y[m-2]<<8)+y[m-1],_.push(e[g>>10]+e[g>>4&63]+e[g<<2&63]+"=")),_.join("")}return zs}var Sc={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var Vh;function I1(){return Vh||(Vh=1,Sc.read=function(e,t,n,r,i){var s,o,c=i*8-r-1,a=(1<<c)-1,u=a>>1,f=-7,l=n?i-1:0,d=n?-1:1,y=e[t+l];for(l+=d,s=y&(1<<-f)-1,y>>=-f,f+=c;f>0;s=s*256+e[t+l],l+=d,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=r;f>0;o=o*256+e[t+l],l+=d,f-=8);if(s===0)s=1-u;else{if(s===a)return o?NaN:(y?-1:1)*(1/0);o=o+Math.pow(2,r),s=s-u}return(y?-1:1)*o*Math.pow(2,s-r)},Sc.write=function(e,t,n,r,i,s){var o,c,a,u=s*8-i-1,f=(1<<u)-1,l=f>>1,d=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=r?0:s-1,g=r?1:-1,m=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,o=f):(o=Math.floor(Math.log(t)/Math.LN2),t*(a=Math.pow(2,-o))<1&&(o--,a*=2),o+l>=1?t+=d/a:t+=d*Math.pow(2,1-l),t*a>=2&&(o++,a/=2),o+l>=f?(c=0,o=f):o+l>=1?(c=(t*a-1)*Math.pow(2,i),o=o+l):(c=t*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;e[n+y]=c&255,y+=g,c/=256,i-=8);for(o=o<<i|c,u+=i;u>0;e[n+y]=o&255,y+=g,o/=256,u-=8);e[n+y-g]|=m*128}),Sc}/*!
1
+ "use strict";var Hh=e=>{throw TypeError(e)};var Fh=(e,t,n)=>t.has(e)||Hh("Cannot "+n);var Fe=(e,t,n)=>(Fh(e,t,"read from private field"),n?n.call(e):t.get(e)),sn=(e,t,n)=>t.has(e)?Hh("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),zt=(e,t,n,r)=>(Fh(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var Mh=(e,t,n,r)=>({set _(i){zt(e,t,i,n)},get _(){return Fe(e,t,r)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function A1(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in e)){const s=Object.getOwnPropertyDescriptor(r,i);s&&Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function Py(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var vu={},zs={},qh;function v1(){if(qh)return zs;qh=1,zs.byteLength=c,zs.toByteArray=u,zs.fromByteArray=d;for(var e=[],t=[],n=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0,s=r.length;i<s;++i)e[i]=r[i],t[r.charCodeAt(i)]=i;t[45]=62,t[95]=63;function o(y){var g=y.length;if(g%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=y.indexOf("=");m===-1&&(m=g);var E=m===g?0:4-m%4;return[m,E]}function c(y){var g=o(y),m=g[0],E=g[1];return(m+E)*3/4-E}function a(y,g,m){return(g+m)*3/4-m}function u(y){var g,m=o(y),E=m[0],_=m[1],S=new n(a(y,E,_)),w=0,T=_>0?E-4:E,O;for(O=0;O<T;O+=4)g=t[y.charCodeAt(O)]<<18|t[y.charCodeAt(O+1)]<<12|t[y.charCodeAt(O+2)]<<6|t[y.charCodeAt(O+3)],S[w++]=g>>16&255,S[w++]=g>>8&255,S[w++]=g&255;return _===2&&(g=t[y.charCodeAt(O)]<<2|t[y.charCodeAt(O+1)]>>4,S[w++]=g&255),_===1&&(g=t[y.charCodeAt(O)]<<10|t[y.charCodeAt(O+1)]<<4|t[y.charCodeAt(O+2)]>>2,S[w++]=g>>8&255,S[w++]=g&255),S}function f(y){return e[y>>18&63]+e[y>>12&63]+e[y>>6&63]+e[y&63]}function l(y,g,m){for(var E,_=[],S=g;S<m;S+=3)E=(y[S]<<16&16711680)+(y[S+1]<<8&65280)+(y[S+2]&255),_.push(f(E));return _.join("")}function d(y){for(var g,m=y.length,E=m%3,_=[],S=16383,w=0,T=m-E;w<T;w+=S)_.push(l(y,w,w+S>T?T:w+S));return E===1?(g=y[m-1],_.push(e[g>>2]+e[g<<4&63]+"==")):E===2&&(g=(y[m-2]<<8)+y[m-1],_.push(e[g>>10]+e[g>>4&63]+e[g<<2&63]+"=")),_.join("")}return zs}var Sc={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var Vh;function I1(){return Vh||(Vh=1,Sc.read=function(e,t,n,r,i){var s,o,c=i*8-r-1,a=(1<<c)-1,u=a>>1,f=-7,l=n?i-1:0,d=n?-1:1,y=e[t+l];for(l+=d,s=y&(1<<-f)-1,y>>=-f,f+=c;f>0;s=s*256+e[t+l],l+=d,f-=8);for(o=s&(1<<-f)-1,s>>=-f,f+=r;f>0;o=o*256+e[t+l],l+=d,f-=8);if(s===0)s=1-u;else{if(s===a)return o?NaN:(y?-1:1)*(1/0);o=o+Math.pow(2,r),s=s-u}return(y?-1:1)*o*Math.pow(2,s-r)},Sc.write=function(e,t,n,r,i,s){var o,c,a,u=s*8-i-1,f=(1<<u)-1,l=f>>1,d=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,y=r?0:s-1,g=r?1:-1,m=t<0||t===0&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(c=isNaN(t)?1:0,o=f):(o=Math.floor(Math.log(t)/Math.LN2),t*(a=Math.pow(2,-o))<1&&(o--,a*=2),o+l>=1?t+=d/a:t+=d*Math.pow(2,1-l),t*a>=2&&(o++,a/=2),o+l>=f?(c=0,o=f):o+l>=1?(c=(t*a-1)*Math.pow(2,i),o=o+l):(c=t*Math.pow(2,l-1)*Math.pow(2,i),o=0));i>=8;e[n+y]=c&255,y+=g,c/=256,i-=8);for(o=o<<i|c,u+=i;u>0;e[n+y]=o&255,y+=g,o/=256,u-=8);e[n+y-g]|=m*128}),Sc}/*!
2
2
  * The buffer module from node.js, for the browser.
3
3
  *
4
4
  * @author Feross Aboukhadijeh <https://feross.org>
@@ -6,7 +6,7 @@
6
6
  */var Lh;function tc(){return Lh||(Lh=1,(function(e){const t=v1(),n=I1(),r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=c,e.SlowBuffer=S,e.INSPECT_MAX_BYTES=50;const i=2147483647;e.kMaxLength=i,c.TYPED_ARRAY_SUPPORT=s(),!c.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 k=new Uint8Array(1),p={foo:function(){return 42}};return Object.setPrototypeOf(p,Uint8Array.prototype),Object.setPrototypeOf(k,p),k.foo()===42}catch{return!1}}Object.defineProperty(c.prototype,"parent",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.buffer}}),Object.defineProperty(c.prototype,"offset",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.byteOffset}});function o(k){if(k>i)throw new RangeError('The value "'+k+'" is invalid for option "size"');const p=new Uint8Array(k);return Object.setPrototypeOf(p,c.prototype),p}function c(k,p,h){if(typeof k=="number"){if(typeof p=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return l(k)}return a(k,p,h)}c.poolSize=8192;function a(k,p,h){if(typeof k=="string")return d(k,p);if(ArrayBuffer.isView(k))return g(k);if(k==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof k);if(it(k,ArrayBuffer)||k&&it(k.buffer,ArrayBuffer)||typeof SharedArrayBuffer<"u"&&(it(k,SharedArrayBuffer)||k&&it(k.buffer,SharedArrayBuffer)))return m(k,p,h);if(typeof k=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');const b=k.valueOf&&k.valueOf();if(b!=null&&b!==k)return c.from(b,p,h);const I=E(k);if(I)return I;if(typeof Symbol<"u"&&Symbol.toPrimitive!=null&&typeof k[Symbol.toPrimitive]=="function")return c.from(k[Symbol.toPrimitive]("string"),p,h);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof k)}c.from=function(k,p,h){return a(k,p,h)},Object.setPrototypeOf(c.prototype,Uint8Array.prototype),Object.setPrototypeOf(c,Uint8Array);function u(k){if(typeof k!="number")throw new TypeError('"size" argument must be of type number');if(k<0)throw new RangeError('The value "'+k+'" is invalid for option "size"')}function f(k,p,h){return u(k),k<=0?o(k):p!==void 0?typeof h=="string"?o(k).fill(p,h):o(k).fill(p):o(k)}c.alloc=function(k,p,h){return f(k,p,h)};function l(k){return u(k),o(k<0?0:_(k)|0)}c.allocUnsafe=function(k){return l(k)},c.allocUnsafeSlow=function(k){return l(k)};function d(k,p){if((typeof p!="string"||p==="")&&(p="utf8"),!c.isEncoding(p))throw new TypeError("Unknown encoding: "+p);const h=w(k,p)|0;let b=o(h);const I=b.write(k,p);return I!==h&&(b=b.slice(0,I)),b}function y(k){const p=k.length<0?0:_(k.length)|0,h=o(p);for(let b=0;b<p;b+=1)h[b]=k[b]&255;return h}function g(k){if(it(k,Uint8Array)){const p=new Uint8Array(k);return m(p.buffer,p.byteOffset,p.byteLength)}return y(k)}function m(k,p,h){if(p<0||k.byteLength<p)throw new RangeError('"offset" is outside of buffer bounds');if(k.byteLength<p+(h||0))throw new RangeError('"length" is outside of buffer bounds');let b;return p===void 0&&h===void 0?b=new Uint8Array(k):h===void 0?b=new Uint8Array(k,p):b=new Uint8Array(k,p,h),Object.setPrototypeOf(b,c.prototype),b}function E(k){if(c.isBuffer(k)){const p=_(k.length)|0,h=o(p);return h.length===0||k.copy(h,0,0,p),h}if(k.length!==void 0)return typeof k.length!="number"||Ce(k.length)?o(0):y(k);if(k.type==="Buffer"&&Array.isArray(k.data))return y(k.data)}function _(k){if(k>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return k|0}function S(k){return+k!=k&&(k=0),c.alloc(+k)}c.isBuffer=function(p){return p!=null&&p._isBuffer===!0&&p!==c.prototype},c.compare=function(p,h){if(it(p,Uint8Array)&&(p=c.from(p,p.offset,p.byteLength)),it(h,Uint8Array)&&(h=c.from(h,h.offset,h.byteLength)),!c.isBuffer(p)||!c.isBuffer(h))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(p===h)return 0;let b=p.length,I=h.length;for(let C=0,j=Math.min(b,I);C<j;++C)if(p[C]!==h[C]){b=p[C],I=h[C];break}return b<I?-1:I<b?1:0},c.isEncoding=function(p){switch(String(p).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}},c.concat=function(p,h){if(!Array.isArray(p))throw new TypeError('"list" argument must be an Array of Buffers');if(p.length===0)return c.alloc(0);let b;if(h===void 0)for(h=0,b=0;b<p.length;++b)h+=p[b].length;const I=c.allocUnsafe(h);let C=0;for(b=0;b<p.length;++b){let j=p[b];if(it(j,Uint8Array))C+j.length>I.length?(c.isBuffer(j)||(j=c.from(j)),j.copy(I,C)):Uint8Array.prototype.set.call(I,j,C);else if(c.isBuffer(j))j.copy(I,C);else throw new TypeError('"list" argument must be an Array of Buffers');C+=j.length}return I};function w(k,p){if(c.isBuffer(k))return k.length;if(ArrayBuffer.isView(k)||it(k,ArrayBuffer))return k.byteLength;if(typeof k!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof k);const h=k.length,b=arguments.length>2&&arguments[2]===!0;if(!b&&h===0)return 0;let I=!1;for(;;)switch(p){case"ascii":case"latin1":case"binary":return h;case"utf8":case"utf-8":return tt(k).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return h*2;case"hex":return h>>>1;case"base64":return Oe(k).length;default:if(I)return b?-1:tt(k).length;p=(""+p).toLowerCase(),I=!0}}c.byteLength=w;function T(k,p,h){let b=!1;if((p===void 0||p<0)&&(p=0),p>this.length||((h===void 0||h>this.length)&&(h=this.length),h<=0)||(h>>>=0,p>>>=0,h<=p))return"";for(k||(k="utf8");;)switch(k){case"hex":return B(this,p,h);case"utf8":case"utf-8":return $(this,p,h);case"ascii":return F(this,p,h);case"latin1":case"binary":return x(this,p,h);case"base64":return H(this,p,h);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return q(this,p,h);default:if(b)throw new TypeError("Unknown encoding: "+k);k=(k+"").toLowerCase(),b=!0}}c.prototype._isBuffer=!0;function O(k,p,h){const b=k[p];k[p]=k[h],k[h]=b}c.prototype.swap16=function(){const p=this.length;if(p%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let h=0;h<p;h+=2)O(this,h,h+1);return this},c.prototype.swap32=function(){const p=this.length;if(p%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let h=0;h<p;h+=4)O(this,h,h+3),O(this,h+1,h+2);return this},c.prototype.swap64=function(){const p=this.length;if(p%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let h=0;h<p;h+=8)O(this,h,h+7),O(this,h+1,h+6),O(this,h+2,h+5),O(this,h+3,h+4);return this},c.prototype.toString=function(){const p=this.length;return p===0?"":arguments.length===0?$(this,0,p):T.apply(this,arguments)},c.prototype.toLocaleString=c.prototype.toString,c.prototype.equals=function(p){if(!c.isBuffer(p))throw new TypeError("Argument must be a Buffer");return this===p?!0:c.compare(this,p)===0},c.prototype.inspect=function(){let p="";const h=e.INSPECT_MAX_BYTES;return p=this.toString("hex",0,h).replace(/(.{2})/g,"$1 ").trim(),this.length>h&&(p+=" ... "),"<Buffer "+p+">"},r&&(c.prototype[r]=c.prototype.inspect),c.prototype.compare=function(p,h,b,I,C){if(it(p,Uint8Array)&&(p=c.from(p,p.offset,p.byteLength)),!c.isBuffer(p))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof p);if(h===void 0&&(h=0),b===void 0&&(b=p?p.length:0),I===void 0&&(I=0),C===void 0&&(C=this.length),h<0||b>p.length||I<0||C>this.length)throw new RangeError("out of range index");if(I>=C&&h>=b)return 0;if(I>=C)return-1;if(h>=b)return 1;if(h>>>=0,b>>>=0,I>>>=0,C>>>=0,this===p)return 0;let j=C-I,W=b-h;const ie=Math.min(j,W),Q=this.slice(I,C),fe=p.slice(h,b);for(let he=0;he<ie;++he)if(Q[he]!==fe[he]){j=Q[he],W=fe[he];break}return j<W?-1:W<j?1:0};function A(k,p,h,b,I){if(k.length===0)return-1;if(typeof h=="string"?(b=h,h=0):h>2147483647?h=2147483647:h<-2147483648&&(h=-2147483648),h=+h,Ce(h)&&(h=I?0:k.length-1),h<0&&(h=k.length+h),h>=k.length){if(I)return-1;h=k.length-1}else if(h<0)if(I)h=0;else return-1;if(typeof p=="string"&&(p=c.from(p,b)),c.isBuffer(p))return p.length===0?-1:R(k,p,h,b,I);if(typeof p=="number")return p=p&255,typeof Uint8Array.prototype.indexOf=="function"?I?Uint8Array.prototype.indexOf.call(k,p,h):Uint8Array.prototype.lastIndexOf.call(k,p,h):R(k,[p],h,b,I);throw new TypeError("val must be string, number or Buffer")}function R(k,p,h,b,I){let C=1,j=k.length,W=p.length;if(b!==void 0&&(b=String(b).toLowerCase(),b==="ucs2"||b==="ucs-2"||b==="utf16le"||b==="utf-16le")){if(k.length<2||p.length<2)return-1;C=2,j/=2,W/=2,h/=2}function ie(fe,he){return C===1?fe[he]:fe.readUInt16BE(he*C)}let Q;if(I){let fe=-1;for(Q=h;Q<j;Q++)if(ie(k,Q)===ie(p,fe===-1?0:Q-fe)){if(fe===-1&&(fe=Q),Q-fe+1===W)return fe*C}else fe!==-1&&(Q-=Q-fe),fe=-1}else for(h+W>j&&(h=j-W),Q=h;Q>=0;Q--){let fe=!0;for(let he=0;he<W;he++)if(ie(k,Q+he)!==ie(p,he)){fe=!1;break}if(fe)return Q}return-1}c.prototype.includes=function(p,h,b){return this.indexOf(p,h,b)!==-1},c.prototype.indexOf=function(p,h,b){return A(this,p,h,b,!0)},c.prototype.lastIndexOf=function(p,h,b){return A(this,p,h,b,!1)};function M(k,p,h,b){h=Number(h)||0;const I=k.length-h;b?(b=Number(b),b>I&&(b=I)):b=I;const C=p.length;b>C/2&&(b=C/2);let j;for(j=0;j<b;++j){const W=parseInt(p.substr(j*2,2),16);if(Ce(W))return j;k[h+j]=W}return j}function v(k,p,h,b){return mn(tt(p,k.length-h),k,h,b)}function U(k,p,h,b){return mn(ut(p),k,h,b)}function V(k,p,h,b){return mn(Oe(p),k,h,b)}function K(k,p,h,b){return mn(It(p,k.length-h),k,h,b)}c.prototype.write=function(p,h,b,I){if(h===void 0)I="utf8",b=this.length,h=0;else if(b===void 0&&typeof h=="string")I=h,b=this.length,h=0;else if(isFinite(h))h=h>>>0,isFinite(b)?(b=b>>>0,I===void 0&&(I="utf8")):(I=b,b=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");const C=this.length-h;if((b===void 0||b>C)&&(b=C),p.length>0&&(b<0||h<0)||h>this.length)throw new RangeError("Attempt to write outside buffer bounds");I||(I="utf8");let j=!1;for(;;)switch(I){case"hex":return M(this,p,h,b);case"utf8":case"utf-8":return v(this,p,h,b);case"ascii":case"latin1":case"binary":return U(this,p,h,b);case"base64":return V(this,p,h,b);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return K(this,p,h,b);default:if(j)throw new TypeError("Unknown encoding: "+I);I=(""+I).toLowerCase(),j=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function H(k,p,h){return p===0&&h===k.length?t.fromByteArray(k):t.fromByteArray(k.slice(p,h))}function $(k,p,h){h=Math.min(k.length,h);const b=[];let I=p;for(;I<h;){const C=k[I];let j=null,W=C>239?4:C>223?3:C>191?2:1;if(I+W<=h){let ie,Q,fe,he;switch(W){case 1:C<128&&(j=C);break;case 2:ie=k[I+1],(ie&192)===128&&(he=(C&31)<<6|ie&63,he>127&&(j=he));break;case 3:ie=k[I+1],Q=k[I+2],(ie&192)===128&&(Q&192)===128&&(he=(C&15)<<12|(ie&63)<<6|Q&63,he>2047&&(he<55296||he>57343)&&(j=he));break;case 4:ie=k[I+1],Q=k[I+2],fe=k[I+3],(ie&192)===128&&(Q&192)===128&&(fe&192)===128&&(he=(C&15)<<18|(ie&63)<<12|(Q&63)<<6|fe&63,he>65535&&he<1114112&&(j=he))}}j===null?(j=65533,W=1):j>65535&&(j-=65536,b.push(j>>>10&1023|55296),j=56320|j&1023),b.push(j),I+=W}return D(b)}const P=4096;function D(k){const p=k.length;if(p<=P)return String.fromCharCode.apply(String,k);let h="",b=0;for(;b<p;)h+=String.fromCharCode.apply(String,k.slice(b,b+=P));return h}function F(k,p,h){let b="";h=Math.min(k.length,h);for(let I=p;I<h;++I)b+=String.fromCharCode(k[I]&127);return b}function x(k,p,h){let b="";h=Math.min(k.length,h);for(let I=p;I<h;++I)b+=String.fromCharCode(k[I]);return b}function B(k,p,h){const b=k.length;(!p||p<0)&&(p=0),(!h||h<0||h>b)&&(h=b);let I="";for(let C=p;C<h;++C)I+=oe[k[C]];return I}function q(k,p,h){const b=k.slice(p,h);let I="";for(let C=0;C<b.length-1;C+=2)I+=String.fromCharCode(b[C]+b[C+1]*256);return I}c.prototype.slice=function(p,h){const b=this.length;p=~~p,h=h===void 0?b:~~h,p<0?(p+=b,p<0&&(p=0)):p>b&&(p=b),h<0?(h+=b,h<0&&(h=0)):h>b&&(h=b),h<p&&(h=p);const I=this.subarray(p,h);return Object.setPrototypeOf(I,c.prototype),I};function N(k,p,h){if(k%1!==0||k<0)throw new RangeError("offset is not uint");if(k+p>h)throw new RangeError("Trying to access beyond buffer length")}c.prototype.readUintLE=c.prototype.readUIntLE=function(p,h,b){p=p>>>0,h=h>>>0,b||N(p,h,this.length);let I=this[p],C=1,j=0;for(;++j<h&&(C*=256);)I+=this[p+j]*C;return I},c.prototype.readUintBE=c.prototype.readUIntBE=function(p,h,b){p=p>>>0,h=h>>>0,b||N(p,h,this.length);let I=this[p+--h],C=1;for(;h>0&&(C*=256);)I+=this[p+--h]*C;return I},c.prototype.readUint8=c.prototype.readUInt8=function(p,h){return p=p>>>0,h||N(p,1,this.length),this[p]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(p,h){return p=p>>>0,h||N(p,2,this.length),this[p]|this[p+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(p,h){return p=p>>>0,h||N(p,2,this.length),this[p]<<8|this[p+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(p,h){return p=p>>>0,h||N(p,4,this.length),(this[p]|this[p+1]<<8|this[p+2]<<16)+this[p+3]*16777216},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(p,h){return p=p>>>0,h||N(p,4,this.length),this[p]*16777216+(this[p+1]<<16|this[p+2]<<8|this[p+3])},c.prototype.readBigUInt64LE=ne(function(p){p=p>>>0,J(p,"offset");const h=this[p],b=this[p+7];(h===void 0||b===void 0)&&le(p,this.length-8);const I=h+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,C=this[++p]+this[++p]*2**8+this[++p]*2**16+b*2**24;return BigInt(I)+(BigInt(C)<<BigInt(32))}),c.prototype.readBigUInt64BE=ne(function(p){p=p>>>0,J(p,"offset");const h=this[p],b=this[p+7];(h===void 0||b===void 0)&&le(p,this.length-8);const I=h*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],C=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+b;return(BigInt(I)<<BigInt(32))+BigInt(C)}),c.prototype.readIntLE=function(p,h,b){p=p>>>0,h=h>>>0,b||N(p,h,this.length);let I=this[p],C=1,j=0;for(;++j<h&&(C*=256);)I+=this[p+j]*C;return C*=128,I>=C&&(I-=Math.pow(2,8*h)),I},c.prototype.readIntBE=function(p,h,b){p=p>>>0,h=h>>>0,b||N(p,h,this.length);let I=h,C=1,j=this[p+--I];for(;I>0&&(C*=256);)j+=this[p+--I]*C;return C*=128,j>=C&&(j-=Math.pow(2,8*h)),j},c.prototype.readInt8=function(p,h){return p=p>>>0,h||N(p,1,this.length),this[p]&128?(255-this[p]+1)*-1:this[p]},c.prototype.readInt16LE=function(p,h){p=p>>>0,h||N(p,2,this.length);const b=this[p]|this[p+1]<<8;return b&32768?b|4294901760:b},c.prototype.readInt16BE=function(p,h){p=p>>>0,h||N(p,2,this.length);const b=this[p+1]|this[p]<<8;return b&32768?b|4294901760:b},c.prototype.readInt32LE=function(p,h){return p=p>>>0,h||N(p,4,this.length),this[p]|this[p+1]<<8|this[p+2]<<16|this[p+3]<<24},c.prototype.readInt32BE=function(p,h){return p=p>>>0,h||N(p,4,this.length),this[p]<<24|this[p+1]<<16|this[p+2]<<8|this[p+3]},c.prototype.readBigInt64LE=ne(function(p){p=p>>>0,J(p,"offset");const h=this[p],b=this[p+7];(h===void 0||b===void 0)&&le(p,this.length-8);const I=this[p+4]+this[p+5]*2**8+this[p+6]*2**16+(b<<24);return(BigInt(I)<<BigInt(32))+BigInt(h+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24)}),c.prototype.readBigInt64BE=ne(function(p){p=p>>>0,J(p,"offset");const h=this[p],b=this[p+7];(h===void 0||b===void 0)&&le(p,this.length-8);const I=(h<<24)+this[++p]*2**16+this[++p]*2**8+this[++p];return(BigInt(I)<<BigInt(32))+BigInt(this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+b)}),c.prototype.readFloatLE=function(p,h){return p=p>>>0,h||N(p,4,this.length),n.read(this,p,!0,23,4)},c.prototype.readFloatBE=function(p,h){return p=p>>>0,h||N(p,4,this.length),n.read(this,p,!1,23,4)},c.prototype.readDoubleLE=function(p,h){return p=p>>>0,h||N(p,8,this.length),n.read(this,p,!0,52,8)},c.prototype.readDoubleBE=function(p,h){return p=p>>>0,h||N(p,8,this.length),n.read(this,p,!1,52,8)};function L(k,p,h,b,I,C){if(!c.isBuffer(k))throw new TypeError('"buffer" argument must be a Buffer instance');if(p>I||p<C)throw new RangeError('"value" argument is out of bounds');if(h+b>k.length)throw new RangeError("Index out of range")}c.prototype.writeUintLE=c.prototype.writeUIntLE=function(p,h,b,I){if(p=+p,h=h>>>0,b=b>>>0,!I){const W=Math.pow(2,8*b)-1;L(this,p,h,b,W,0)}let C=1,j=0;for(this[h]=p&255;++j<b&&(C*=256);)this[h+j]=p/C&255;return h+b},c.prototype.writeUintBE=c.prototype.writeUIntBE=function(p,h,b,I){if(p=+p,h=h>>>0,b=b>>>0,!I){const W=Math.pow(2,8*b)-1;L(this,p,h,b,W,0)}let C=b-1,j=1;for(this[h+C]=p&255;--C>=0&&(j*=256);)this[h+C]=p/j&255;return h+b},c.prototype.writeUint8=c.prototype.writeUInt8=function(p,h,b){return p=+p,h=h>>>0,b||L(this,p,h,1,255,0),this[h]=p&255,h+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(p,h,b){return p=+p,h=h>>>0,b||L(this,p,h,2,65535,0),this[h]=p&255,this[h+1]=p>>>8,h+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(p,h,b){return p=+p,h=h>>>0,b||L(this,p,h,2,65535,0),this[h]=p>>>8,this[h+1]=p&255,h+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(p,h,b){return p=+p,h=h>>>0,b||L(this,p,h,4,4294967295,0),this[h+3]=p>>>24,this[h+2]=p>>>16,this[h+1]=p>>>8,this[h]=p&255,h+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(p,h,b){return p=+p,h=h>>>0,b||L(this,p,h,4,4294967295,0),this[h]=p>>>24,this[h+1]=p>>>16,this[h+2]=p>>>8,this[h+3]=p&255,h+4};function G(k,p,h,b,I){ye(p,b,I,k,h,7);let C=Number(p&BigInt(4294967295));k[h++]=C,C=C>>8,k[h++]=C,C=C>>8,k[h++]=C,C=C>>8,k[h++]=C;let j=Number(p>>BigInt(32)&BigInt(4294967295));return k[h++]=j,j=j>>8,k[h++]=j,j=j>>8,k[h++]=j,j=j>>8,k[h++]=j,h}function X(k,p,h,b,I){ye(p,b,I,k,h,7);let C=Number(p&BigInt(4294967295));k[h+7]=C,C=C>>8,k[h+6]=C,C=C>>8,k[h+5]=C,C=C>>8,k[h+4]=C;let j=Number(p>>BigInt(32)&BigInt(4294967295));return k[h+3]=j,j=j>>8,k[h+2]=j,j=j>>8,k[h+1]=j,j=j>>8,k[h]=j,h+8}c.prototype.writeBigUInt64LE=ne(function(p,h=0){return G(this,p,h,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeBigUInt64BE=ne(function(p,h=0){return X(this,p,h,BigInt(0),BigInt("0xffffffffffffffff"))}),c.prototype.writeIntLE=function(p,h,b,I){if(p=+p,h=h>>>0,!I){const ie=Math.pow(2,8*b-1);L(this,p,h,b,ie-1,-ie)}let C=0,j=1,W=0;for(this[h]=p&255;++C<b&&(j*=256);)p<0&&W===0&&this[h+C-1]!==0&&(W=1),this[h+C]=(p/j>>0)-W&255;return h+b},c.prototype.writeIntBE=function(p,h,b,I){if(p=+p,h=h>>>0,!I){const ie=Math.pow(2,8*b-1);L(this,p,h,b,ie-1,-ie)}let C=b-1,j=1,W=0;for(this[h+C]=p&255;--C>=0&&(j*=256);)p<0&&W===0&&this[h+C+1]!==0&&(W=1),this[h+C]=(p/j>>0)-W&255;return h+b},c.prototype.writeInt8=function(p,h,b){return p=+p,h=h>>>0,b||L(this,p,h,1,127,-128),p<0&&(p=255+p+1),this[h]=p&255,h+1},c.prototype.writeInt16LE=function(p,h,b){return p=+p,h=h>>>0,b||L(this,p,h,2,32767,-32768),this[h]=p&255,this[h+1]=p>>>8,h+2},c.prototype.writeInt16BE=function(p,h,b){return p=+p,h=h>>>0,b||L(this,p,h,2,32767,-32768),this[h]=p>>>8,this[h+1]=p&255,h+2},c.prototype.writeInt32LE=function(p,h,b){return p=+p,h=h>>>0,b||L(this,p,h,4,2147483647,-2147483648),this[h]=p&255,this[h+1]=p>>>8,this[h+2]=p>>>16,this[h+3]=p>>>24,h+4},c.prototype.writeInt32BE=function(p,h,b){return p=+p,h=h>>>0,b||L(this,p,h,4,2147483647,-2147483648),p<0&&(p=4294967295+p+1),this[h]=p>>>24,this[h+1]=p>>>16,this[h+2]=p>>>8,this[h+3]=p&255,h+4},c.prototype.writeBigInt64LE=ne(function(p,h=0){return G(this,p,h,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),c.prototype.writeBigInt64BE=ne(function(p,h=0){return X(this,p,h,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function Y(k,p,h,b,I,C){if(h+b>k.length)throw new RangeError("Index out of range");if(h<0)throw new RangeError("Index out of range")}function ce(k,p,h,b,I){return p=+p,h=h>>>0,I||Y(k,p,h,4),n.write(k,p,h,b,23,4),h+4}c.prototype.writeFloatLE=function(p,h,b){return ce(this,p,h,!0,b)},c.prototype.writeFloatBE=function(p,h,b){return ce(this,p,h,!1,b)};function ue(k,p,h,b,I){return p=+p,h=h>>>0,I||Y(k,p,h,8),n.write(k,p,h,b,52,8),h+8}c.prototype.writeDoubleLE=function(p,h,b){return ue(this,p,h,!0,b)},c.prototype.writeDoubleBE=function(p,h,b){return ue(this,p,h,!1,b)},c.prototype.copy=function(p,h,b,I){if(!c.isBuffer(p))throw new TypeError("argument should be a Buffer");if(b||(b=0),!I&&I!==0&&(I=this.length),h>=p.length&&(h=p.length),h||(h=0),I>0&&I<b&&(I=b),I===b||p.length===0||this.length===0)return 0;if(h<0)throw new RangeError("targetStart out of bounds");if(b<0||b>=this.length)throw new RangeError("Index out of range");if(I<0)throw new RangeError("sourceEnd out of bounds");I>this.length&&(I=this.length),p.length-h<I-b&&(I=p.length-h+b);const C=I-b;return this===p&&typeof Uint8Array.prototype.copyWithin=="function"?this.copyWithin(h,b,I):Uint8Array.prototype.set.call(p,this.subarray(b,I),h),C},c.prototype.fill=function(p,h,b,I){if(typeof p=="string"){if(typeof h=="string"?(I=h,h=0,b=this.length):typeof b=="string"&&(I=b,b=this.length),I!==void 0&&typeof I!="string")throw new TypeError("encoding must be a string");if(typeof I=="string"&&!c.isEncoding(I))throw new TypeError("Unknown encoding: "+I);if(p.length===1){const j=p.charCodeAt(0);(I==="utf8"&&j<128||I==="latin1")&&(p=j)}}else typeof p=="number"?p=p&255:typeof p=="boolean"&&(p=Number(p));if(h<0||this.length<h||this.length<b)throw new RangeError("Out of range index");if(b<=h)return this;h=h>>>0,b=b===void 0?this.length:b>>>0,p||(p=0);let C;if(typeof p=="number")for(C=h;C<b;++C)this[C]=p;else{const j=c.isBuffer(p)?p:c.from(p,I),W=j.length;if(W===0)throw new TypeError('The value "'+p+'" is invalid for argument "value"');for(C=0;C<b-h;++C)this[C+h]=j[C%W]}return this};const te={};function Z(k,p,h){te[k]=class extends h{constructor(){super(),Object.defineProperty(this,"message",{value:p.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${k}]`,this.stack,delete this.name}get code(){return k}set code(I){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:I,writable:!0})}toString(){return`${this.name} [${k}]: ${this.message}`}}}Z("ERR_BUFFER_OUT_OF_BOUNDS",function(k){return k?`${k} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),Z("ERR_INVALID_ARG_TYPE",function(k,p){return`The "${k}" argument must be of type number. Received type ${typeof p}`},TypeError),Z("ERR_OUT_OF_RANGE",function(k,p,h){let b=`The value of "${k}" is out of range.`,I=h;return Number.isInteger(h)&&Math.abs(h)>2**32?I=ae(String(h)):typeof h=="bigint"&&(I=String(h),(h>BigInt(2)**BigInt(32)||h<-(BigInt(2)**BigInt(32)))&&(I=ae(I)),I+="n"),b+=` It must be ${p}. Received ${I}`,b},RangeError);function ae(k){let p="",h=k.length;const b=k[0]==="-"?1:0;for(;h>=b+4;h-=3)p=`_${k.slice(h-3,h)}${p}`;return`${k.slice(0,h)}${p}`}function we(k,p,h){J(p,"offset"),(k[p]===void 0||k[p+h]===void 0)&&le(p,k.length-(h+1))}function ye(k,p,h,b,I,C){if(k>h||k<p){const j=typeof p=="bigint"?"n":"";let W;throw p===0||p===BigInt(0)?W=`>= 0${j} and < 2${j} ** ${(C+1)*8}${j}`:W=`>= -(2${j} ** ${(C+1)*8-1}${j}) and < 2 ** ${(C+1)*8-1}${j}`,new te.ERR_OUT_OF_RANGE("value",W,k)}we(b,I,C)}function J(k,p){if(typeof k!="number")throw new te.ERR_INVALID_ARG_TYPE(p,"number",k)}function le(k,p,h){throw Math.floor(k)!==k?(J(k,h),new te.ERR_OUT_OF_RANGE("offset","an integer",k)):p<0?new te.ERR_BUFFER_OUT_OF_BOUNDS:new te.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${p}`,k)}const Ae=/[^+/0-9A-Za-z-_]/g;function qe(k){if(k=k.split("=")[0],k=k.trim().replace(Ae,""),k.length<2)return"";for(;k.length%4!==0;)k=k+"=";return k}function tt(k,p){p=p||1/0;let h;const b=k.length;let I=null;const C=[];for(let j=0;j<b;++j){if(h=k.charCodeAt(j),h>55295&&h<57344){if(!I){if(h>56319){(p-=3)>-1&&C.push(239,191,189);continue}else if(j+1===b){(p-=3)>-1&&C.push(239,191,189);continue}I=h;continue}if(h<56320){(p-=3)>-1&&C.push(239,191,189),I=h;continue}h=(I-55296<<10|h-56320)+65536}else I&&(p-=3)>-1&&C.push(239,191,189);if(I=null,h<128){if((p-=1)<0)break;C.push(h)}else if(h<2048){if((p-=2)<0)break;C.push(h>>6|192,h&63|128)}else if(h<65536){if((p-=3)<0)break;C.push(h>>12|224,h>>6&63|128,h&63|128)}else if(h<1114112){if((p-=4)<0)break;C.push(h>>18|240,h>>12&63|128,h>>6&63|128,h&63|128)}else throw new Error("Invalid code point")}return C}function ut(k){const p=[];for(let h=0;h<k.length;++h)p.push(k.charCodeAt(h)&255);return p}function It(k,p){let h,b,I;const C=[];for(let j=0;j<k.length&&!((p-=2)<0);++j)h=k.charCodeAt(j),b=h>>8,I=h%256,C.push(I),C.push(b);return C}function Oe(k){return t.toByteArray(qe(k))}function mn(k,p,h,b){let I;for(I=0;I<b&&!(I+h>=p.length||I>=k.length);++I)p[I+h]=k[I];return I}function it(k,p){return k instanceof p||k!=null&&k.constructor!=null&&k.constructor.name!=null&&k.constructor.name===p.name}function Ce(k){return k!==k}const oe=(function(){const k="0123456789abcdef",p=new Array(256);for(let h=0;h<16;++h){const b=h*16;for(let I=0;I<16;++I)p[b+I]=k[h]+k[I]}return p})();function ne(k){return typeof BigInt>"u"?re:k}function re(){throw new Error("BigInt not supported")}})(vu)),vu}var O1=tc(),Iu={exports:{}},$h;function B1(){if($h)return Iu.exports;$h=1;var e=Iu.exports={},t,n;function r(){throw new Error("setTimeout has not been defined")}function i(){throw new Error("clearTimeout has not been defined")}(function(){try{typeof setTimeout=="function"?t=setTimeout:t=r}catch{t=r}try{typeof clearTimeout=="function"?n=clearTimeout:n=i}catch{n=i}})();function s(m){if(t===setTimeout)return setTimeout(m,0);if((t===r||!t)&&setTimeout)return t=setTimeout,setTimeout(m,0);try{return t(m,0)}catch{try{return t.call(null,m,0)}catch{return t.call(this,m,0)}}}function o(m){if(n===clearTimeout)return clearTimeout(m);if((n===i||!n)&&clearTimeout)return n=clearTimeout,clearTimeout(m);try{return n(m)}catch{try{return n.call(null,m)}catch{return n.call(this,m)}}}var c=[],a=!1,u,f=-1;function l(){!a||!u||(a=!1,u.length?c=u.concat(c):f=-1,c.length&&d())}function d(){if(!a){var m=s(l);a=!0;for(var E=c.length;E;){for(u=c,c=[];++f<E;)u&&u[f].run();f=-1,E=c.length}u=null,a=!1,o(m)}}e.nextTick=function(m){var E=new Array(arguments.length-1);if(arguments.length>1)for(var _=1;_<arguments.length;_++)E[_-1]=arguments[_];c.push(new y(m,E)),c.length===1&&!a&&s(d)};function y(m,E){this.fun=m,this.array=E}y.prototype.run=function(){this.fun.apply(null,this.array)},e.title="browser",e.browser=!0,e.env={},e.argv=[],e.version="",e.versions={};function g(){}return e.on=g,e.addListener=g,e.once=g,e.off=g,e.removeListener=g,e.removeAllListeners=g,e.emit=g,e.prependListener=g,e.prependOnceListener=g,e.listeners=function(m){return[]},e.binding=function(m){throw new Error("process.binding is not supported")},e.cwd=function(){return"/"},e.chdir=function(m){throw new Error("process.chdir is not supported")},e.umask=function(){return 0},Iu.exports}var N1=B1();const k1=Py(N1);typeof globalThis>"u"&&(globalThis.global=globalThis);typeof globalThis.Buffer>"u"&&(globalThis.Buffer=O1.Buffer);typeof globalThis.process>"u"&&(globalThis.process=k1);var st={},Ou={},We={},qt={},Bu={},Ys={},Dh;function P1(){return Dh||(Dh=1,Object.defineProperty(Ys,"__esModule",{value:!0}),Ys.crypto=void 0,Ys.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0),Ys}var jh;function ui(){return jh||(jh=1,(function(e){/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */Object.defineProperty(e,"__esModule",{value:!0}),e.wrapXOFConstructorWithOpts=e.wrapConstructorWithOpts=e.wrapConstructor=e.Hash=e.nextTick=e.swap32IfBE=e.byteSwapIfBE=e.swap8IfBE=e.isLE=void 0,e.isBytes=n,e.anumber=r,e.abytes=i,e.ahash=s,e.aexists=o,e.aoutput=c,e.u8=a,e.u32=u,e.clean=f,e.createView=l,e.rotr=d,e.rotl=y,e.byteSwap=g,e.byteSwap32=m,e.bytesToHex=S,e.hexToBytes=O,e.asyncLoop=R,e.utf8ToBytes=M,e.bytesToUtf8=v,e.toBytes=U,e.kdfInputToBytes=V,e.concatBytes=K,e.checkOpts=H,e.createHasher=P,e.createOptHasher=D,e.createXOFer=F,e.randomBytes=x;const t=P1();function n(B){return B instanceof Uint8Array||ArrayBuffer.isView(B)&&B.constructor.name==="Uint8Array"}function r(B){if(!Number.isSafeInteger(B)||B<0)throw new Error("positive integer expected, got "+B)}function i(B,...q){if(!n(B))throw new Error("Uint8Array expected");if(q.length>0&&!q.includes(B.length))throw new Error("Uint8Array expected of length "+q+", got length="+B.length)}function s(B){if(typeof B!="function"||typeof B.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");r(B.outputLen),r(B.blockLen)}function o(B,q=!0){if(B.destroyed)throw new Error("Hash instance has been destroyed");if(q&&B.finished)throw new Error("Hash#digest() has already been called")}function c(B,q){i(B);const N=q.outputLen;if(B.length<N)throw new Error("digestInto() expects output buffer of length at least "+N)}function a(B){return new Uint8Array(B.buffer,B.byteOffset,B.byteLength)}function u(B){return new Uint32Array(B.buffer,B.byteOffset,Math.floor(B.byteLength/4))}function f(...B){for(let q=0;q<B.length;q++)B[q].fill(0)}function l(B){return new DataView(B.buffer,B.byteOffset,B.byteLength)}function d(B,q){return B<<32-q|B>>>q}function y(B,q){return B<<q|B>>>32-q>>>0}e.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function g(B){return B<<24&4278190080|B<<8&16711680|B>>>8&65280|B>>>24&255}e.swap8IfBE=e.isLE?B=>B:B=>g(B),e.byteSwapIfBE=e.swap8IfBE;function m(B){for(let q=0;q<B.length;q++)B[q]=g(B[q]);return B}e.swap32IfBE=e.isLE?B=>B:m;const E=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",_=Array.from({length:256},(B,q)=>q.toString(16).padStart(2,"0"));function S(B){if(i(B),E)return B.toHex();let q="";for(let N=0;N<B.length;N++)q+=_[B[N]];return q}const w={_0:48,_9:57,A:65,F:70,a:97,f:102};function T(B){if(B>=w._0&&B<=w._9)return B-w._0;if(B>=w.A&&B<=w.F)return B-(w.A-10);if(B>=w.a&&B<=w.f)return B-(w.a-10)}function O(B){if(typeof B!="string")throw new Error("hex string expected, got "+typeof B);if(E)return Uint8Array.fromHex(B);const q=B.length,N=q/2;if(q%2)throw new Error("hex string expected, got unpadded hex of length "+q);const L=new Uint8Array(N);for(let G=0,X=0;G<N;G++,X+=2){const Y=T(B.charCodeAt(X)),ce=T(B.charCodeAt(X+1));if(Y===void 0||ce===void 0){const ue=B[X]+B[X+1];throw new Error('hex string expected, got non-hex character "'+ue+'" at index '+X)}L[G]=Y*16+ce}return L}const A=async()=>{};e.nextTick=A;async function R(B,q,N){let L=Date.now();for(let G=0;G<B;G++){N(G);const X=Date.now()-L;X>=0&&X<q||(await(0,e.nextTick)(),L+=X)}}function M(B){if(typeof B!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(B))}function v(B){return new TextDecoder().decode(B)}function U(B){return typeof B=="string"&&(B=M(B)),i(B),B}function V(B){return typeof B=="string"&&(B=M(B)),i(B),B}function K(...B){let q=0;for(let L=0;L<B.length;L++){const G=B[L];i(G),q+=G.length}const N=new Uint8Array(q);for(let L=0,G=0;L<B.length;L++){const X=B[L];N.set(X,G),G+=X.length}return N}function H(B,q){if(q!==void 0&&{}.toString.call(q)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(B,q)}class ${}e.Hash=$;function P(B){const q=L=>B().update(U(L)).digest(),N=B();return q.outputLen=N.outputLen,q.blockLen=N.blockLen,q.create=()=>B(),q}function D(B){const q=(L,G)=>B(G).update(U(L)).digest(),N=B({});return q.outputLen=N.outputLen,q.blockLen=N.blockLen,q.create=L=>B(L),q}function F(B){const q=(L,G)=>B(G).update(U(L)).digest(),N=B({});return q.outputLen=N.outputLen,q.blockLen=N.blockLen,q.create=L=>B(L),q}e.wrapConstructor=P,e.wrapConstructorWithOpts=D,e.wrapXOFConstructorWithOpts=F;function x(B=32){if(t.crypto&&typeof t.crypto.getRandomValues=="function")return t.crypto.getRandomValues(new Uint8Array(B));if(t.crypto&&typeof t.crypto.randomBytes=="function")return Uint8Array.from(t.crypto.randomBytes(B));throw new Error("crypto.getRandomValues must be defined")}})(Bu)),Bu}var Kh;function Ry(){if(Kh)return qt;Kh=1,Object.defineProperty(qt,"__esModule",{value:!0}),qt.SHA512_IV=qt.SHA384_IV=qt.SHA224_IV=qt.SHA256_IV=qt.HashMD=void 0,qt.setBigUint64=t,qt.Chi=n,qt.Maj=r;const e=ui();function t(s,o,c,a){if(typeof s.setBigUint64=="function")return s.setBigUint64(o,c,a);const u=BigInt(32),f=BigInt(4294967295),l=Number(c>>u&f),d=Number(c&f),y=a?4:0,g=a?0:4;s.setUint32(o+y,l,a),s.setUint32(o+g,d,a)}function n(s,o,c){return s&o^~s&c}function r(s,o,c){return s&o^s&c^o&c}class i extends e.Hash{constructor(o,c,a,u){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=o,this.outputLen=c,this.padOffset=a,this.isLE=u,this.buffer=new Uint8Array(o),this.view=(0,e.createView)(this.buffer)}update(o){(0,e.aexists)(this),o=(0,e.toBytes)(o),(0,e.abytes)(o);const{view:c,buffer:a,blockLen:u}=this,f=o.length;for(let l=0;l<f;){const d=Math.min(u-this.pos,f-l);if(d===u){const y=(0,e.createView)(o);for(;u<=f-l;l+=u)this.process(y,l);continue}a.set(o.subarray(l,l+d),this.pos),this.pos+=d,l+=d,this.pos===u&&(this.process(c,0),this.pos=0)}return this.length+=o.length,this.roundClean(),this}digestInto(o){(0,e.aexists)(this),(0,e.aoutput)(o,this),this.finished=!0;const{buffer:c,view:a,blockLen:u,isLE:f}=this;let{pos:l}=this;c[l++]=128,(0,e.clean)(this.buffer.subarray(l)),this.padOffset>u-l&&(this.process(a,0),l=0);for(let E=l;E<u;E++)c[E]=0;t(a,u-8,BigInt(this.length*8),f),this.process(a,0);const d=(0,e.createView)(o),y=this.outputLen;if(y%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const g=y/4,m=this.get();if(g>m.length)throw new Error("_sha2: outputLen bigger than state");for(let E=0;E<g;E++)d.setUint32(4*E,m[E],f)}digest(){const{buffer:o,outputLen:c}=this;this.digestInto(o);const a=o.slice(0,c);return this.destroy(),a}_cloneInto(o){o||(o=new this.constructor),o.set(...this.get());const{blockLen:c,buffer:a,length:u,finished:f,destroyed:l,pos:d}=this;return o.destroyed=l,o.finished=f,o.length=u,o.pos=d,u%c&&o.buffer.set(a),o}clone(){return this._cloneInto()}}return qt.HashMD=i,qt.SHA256_IV=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),qt.SHA224_IV=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),qt.SHA384_IV=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),qt.SHA512_IV=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),qt}var Ie={},Gh;function R1(){if(Gh)return Ie;Gh=1,Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.toBig=Ie.shrSL=Ie.shrSH=Ie.rotrSL=Ie.rotrSH=Ie.rotrBL=Ie.rotrBH=Ie.rotr32L=Ie.rotr32H=Ie.rotlSL=Ie.rotlSH=Ie.rotlBL=Ie.rotlBH=Ie.add5L=Ie.add5H=Ie.add4L=Ie.add4H=Ie.add3L=Ie.add3H=void 0,Ie.add=_,Ie.fromBig=n,Ie.split=r;const e=BigInt(2**32-1),t=BigInt(32);function n(v,U=!1){return U?{h:Number(v&e),l:Number(v>>t&e)}:{h:Number(v>>t&e)|0,l:Number(v&e)|0}}function r(v,U=!1){const V=v.length;let K=new Uint32Array(V),H=new Uint32Array(V);for(let $=0;$<V;$++){const{h:P,l:D}=n(v[$],U);[K[$],H[$]]=[P,D]}return[K,H]}const i=(v,U)=>BigInt(v>>>0)<<t|BigInt(U>>>0);Ie.toBig=i;const s=(v,U,V)=>v>>>V;Ie.shrSH=s;const o=(v,U,V)=>v<<32-V|U>>>V;Ie.shrSL=o;const c=(v,U,V)=>v>>>V|U<<32-V;Ie.rotrSH=c;const a=(v,U,V)=>v<<32-V|U>>>V;Ie.rotrSL=a;const u=(v,U,V)=>v<<64-V|U>>>V-32;Ie.rotrBH=u;const f=(v,U,V)=>v>>>V-32|U<<64-V;Ie.rotrBL=f;const l=(v,U)=>U;Ie.rotr32H=l;const d=(v,U)=>v;Ie.rotr32L=d;const y=(v,U,V)=>v<<V|U>>>32-V;Ie.rotlSH=y;const g=(v,U,V)=>U<<V|v>>>32-V;Ie.rotlSL=g;const m=(v,U,V)=>U<<V-32|v>>>64-V;Ie.rotlBH=m;const E=(v,U,V)=>v<<V-32|U>>>64-V;Ie.rotlBL=E;function _(v,U,V,K){const H=(U>>>0)+(K>>>0);return{h:v+V+(H/2**32|0)|0,l:H|0}}const S=(v,U,V)=>(v>>>0)+(U>>>0)+(V>>>0);Ie.add3L=S;const w=(v,U,V,K)=>U+V+K+(v/2**32|0)|0;Ie.add3H=w;const T=(v,U,V,K)=>(v>>>0)+(U>>>0)+(V>>>0)+(K>>>0);Ie.add4L=T;const O=(v,U,V,K,H)=>U+V+K+H+(v/2**32|0)|0;Ie.add4H=O;const A=(v,U,V,K,H)=>(v>>>0)+(U>>>0)+(V>>>0)+(K>>>0)+(H>>>0);Ie.add5L=A;const R=(v,U,V,K,H,$)=>U+V+K+H+$+(v/2**32|0)|0;Ie.add5H=R;const M={fromBig:n,split:r,toBig:i,shrSH:s,shrSL:o,rotrSH:c,rotrSL:a,rotrBH:u,rotrBL:f,rotr32H:l,rotr32L:d,rotlSH:y,rotlSL:g,rotlBH:m,rotlBL:E,add:_,add3L:S,add3H:w,add4L:T,add4H:O,add5H:R,add5L:A};return Ie.default=M,Ie}var Wh;function Uy(){if(Wh)return We;Wh=1,Object.defineProperty(We,"__esModule",{value:!0}),We.sha512_224=We.sha512_256=We.sha384=We.sha512=We.sha224=We.sha256=We.SHA512_256=We.SHA512_224=We.SHA384=We.SHA512=We.SHA224=We.SHA256=void 0;const e=Ry(),t=R1(),n=ui(),r=Uint32Array.from([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]),i=new Uint32Array(64);class s extends e.HashMD{constructor(w=32){super(64,w,8,!1),this.A=e.SHA256_IV[0]|0,this.B=e.SHA256_IV[1]|0,this.C=e.SHA256_IV[2]|0,this.D=e.SHA256_IV[3]|0,this.E=e.SHA256_IV[4]|0,this.F=e.SHA256_IV[5]|0,this.G=e.SHA256_IV[6]|0,this.H=e.SHA256_IV[7]|0}get(){const{A:w,B:T,C:O,D:A,E:R,F:M,G:v,H:U}=this;return[w,T,O,A,R,M,v,U]}set(w,T,O,A,R,M,v,U){this.A=w|0,this.B=T|0,this.C=O|0,this.D=A|0,this.E=R|0,this.F=M|0,this.G=v|0,this.H=U|0}process(w,T){for(let H=0;H<16;H++,T+=4)i[H]=w.getUint32(T,!1);for(let H=16;H<64;H++){const $=i[H-15],P=i[H-2],D=(0,n.rotr)($,7)^(0,n.rotr)($,18)^$>>>3,F=(0,n.rotr)(P,17)^(0,n.rotr)(P,19)^P>>>10;i[H]=F+i[H-7]+D+i[H-16]|0}let{A:O,B:A,C:R,D:M,E:v,F:U,G:V,H:K}=this;for(let H=0;H<64;H++){const $=(0,n.rotr)(v,6)^(0,n.rotr)(v,11)^(0,n.rotr)(v,25),P=K+$+(0,e.Chi)(v,U,V)+r[H]+i[H]|0,F=((0,n.rotr)(O,2)^(0,n.rotr)(O,13)^(0,n.rotr)(O,22))+(0,e.Maj)(O,A,R)|0;K=V,V=U,U=v,v=M+P|0,M=R,R=A,A=O,O=P+F|0}O=O+this.A|0,A=A+this.B|0,R=R+this.C|0,M=M+this.D|0,v=v+this.E|0,U=U+this.F|0,V=V+this.G|0,K=K+this.H|0,this.set(O,A,R,M,v,U,V,K)}roundClean(){(0,n.clean)(i)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,n.clean)(this.buffer)}}We.SHA256=s;class o extends s{constructor(){super(28),this.A=e.SHA224_IV[0]|0,this.B=e.SHA224_IV[1]|0,this.C=e.SHA224_IV[2]|0,this.D=e.SHA224_IV[3]|0,this.E=e.SHA224_IV[4]|0,this.F=e.SHA224_IV[5]|0,this.G=e.SHA224_IV[6]|0,this.H=e.SHA224_IV[7]|0}}We.SHA224=o;const c=t.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(S=>BigInt(S))),a=c[0],u=c[1],f=new Uint32Array(80),l=new Uint32Array(80);class d extends e.HashMD{constructor(w=64){super(128,w,16,!1),this.Ah=e.SHA512_IV[0]|0,this.Al=e.SHA512_IV[1]|0,this.Bh=e.SHA512_IV[2]|0,this.Bl=e.SHA512_IV[3]|0,this.Ch=e.SHA512_IV[4]|0,this.Cl=e.SHA512_IV[5]|0,this.Dh=e.SHA512_IV[6]|0,this.Dl=e.SHA512_IV[7]|0,this.Eh=e.SHA512_IV[8]|0,this.El=e.SHA512_IV[9]|0,this.Fh=e.SHA512_IV[10]|0,this.Fl=e.SHA512_IV[11]|0,this.Gh=e.SHA512_IV[12]|0,this.Gl=e.SHA512_IV[13]|0,this.Hh=e.SHA512_IV[14]|0,this.Hl=e.SHA512_IV[15]|0}get(){const{Ah:w,Al:T,Bh:O,Bl:A,Ch:R,Cl:M,Dh:v,Dl:U,Eh:V,El:K,Fh:H,Fl:$,Gh:P,Gl:D,Hh:F,Hl:x}=this;return[w,T,O,A,R,M,v,U,V,K,H,$,P,D,F,x]}set(w,T,O,A,R,M,v,U,V,K,H,$,P,D,F,x){this.Ah=w|0,this.Al=T|0,this.Bh=O|0,this.Bl=A|0,this.Ch=R|0,this.Cl=M|0,this.Dh=v|0,this.Dl=U|0,this.Eh=V|0,this.El=K|0,this.Fh=H|0,this.Fl=$|0,this.Gh=P|0,this.Gl=D|0,this.Hh=F|0,this.Hl=x|0}process(w,T){for(let N=0;N<16;N++,T+=4)f[N]=w.getUint32(T),l[N]=w.getUint32(T+=4);for(let N=16;N<80;N++){const L=f[N-15]|0,G=l[N-15]|0,X=t.rotrSH(L,G,1)^t.rotrSH(L,G,8)^t.shrSH(L,G,7),Y=t.rotrSL(L,G,1)^t.rotrSL(L,G,8)^t.shrSL(L,G,7),ce=f[N-2]|0,ue=l[N-2]|0,te=t.rotrSH(ce,ue,19)^t.rotrBH(ce,ue,61)^t.shrSH(ce,ue,6),Z=t.rotrSL(ce,ue,19)^t.rotrBL(ce,ue,61)^t.shrSL(ce,ue,6),ae=t.add4L(Y,Z,l[N-7],l[N-16]),we=t.add4H(ae,X,te,f[N-7],f[N-16]);f[N]=we|0,l[N]=ae|0}let{Ah:O,Al:A,Bh:R,Bl:M,Ch:v,Cl:U,Dh:V,Dl:K,Eh:H,El:$,Fh:P,Fl:D,Gh:F,Gl:x,Hh:B,Hl:q}=this;for(let N=0;N<80;N++){const L=t.rotrSH(H,$,14)^t.rotrSH(H,$,18)^t.rotrBH(H,$,41),G=t.rotrSL(H,$,14)^t.rotrSL(H,$,18)^t.rotrBL(H,$,41),X=H&P^~H&F,Y=$&D^~$&x,ce=t.add5L(q,G,Y,u[N],l[N]),ue=t.add5H(ce,B,L,X,a[N],f[N]),te=ce|0,Z=t.rotrSH(O,A,28)^t.rotrBH(O,A,34)^t.rotrBH(O,A,39),ae=t.rotrSL(O,A,28)^t.rotrBL(O,A,34)^t.rotrBL(O,A,39),we=O&R^O&v^R&v,ye=A&M^A&U^M&U;B=F|0,q=x|0,F=P|0,x=D|0,P=H|0,D=$|0,{h:H,l:$}=t.add(V|0,K|0,ue|0,te|0),V=v|0,K=U|0,v=R|0,U=M|0,R=O|0,M=A|0;const J=t.add3L(te,ae,ye);O=t.add3H(J,ue,Z,we),A=J|0}({h:O,l:A}=t.add(this.Ah|0,this.Al|0,O|0,A|0)),{h:R,l:M}=t.add(this.Bh|0,this.Bl|0,R|0,M|0),{h:v,l:U}=t.add(this.Ch|0,this.Cl|0,v|0,U|0),{h:V,l:K}=t.add(this.Dh|0,this.Dl|0,V|0,K|0),{h:H,l:$}=t.add(this.Eh|0,this.El|0,H|0,$|0),{h:P,l:D}=t.add(this.Fh|0,this.Fl|0,P|0,D|0),{h:F,l:x}=t.add(this.Gh|0,this.Gl|0,F|0,x|0),{h:B,l:q}=t.add(this.Hh|0,this.Hl|0,B|0,q|0),this.set(O,A,R,M,v,U,V,K,H,$,P,D,F,x,B,q)}roundClean(){(0,n.clean)(f,l)}destroy(){(0,n.clean)(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}We.SHA512=d;class y extends d{constructor(){super(48),this.Ah=e.SHA384_IV[0]|0,this.Al=e.SHA384_IV[1]|0,this.Bh=e.SHA384_IV[2]|0,this.Bl=e.SHA384_IV[3]|0,this.Ch=e.SHA384_IV[4]|0,this.Cl=e.SHA384_IV[5]|0,this.Dh=e.SHA384_IV[6]|0,this.Dl=e.SHA384_IV[7]|0,this.Eh=e.SHA384_IV[8]|0,this.El=e.SHA384_IV[9]|0,this.Fh=e.SHA384_IV[10]|0,this.Fl=e.SHA384_IV[11]|0,this.Gh=e.SHA384_IV[12]|0,this.Gl=e.SHA384_IV[13]|0,this.Hh=e.SHA384_IV[14]|0,this.Hl=e.SHA384_IV[15]|0}}We.SHA384=y;const g=Uint32Array.from([2352822216,424955298,1944164710,2312950998,502970286,855612546,1738396948,1479516111,258812777,2077511080,2011393907,79989058,1067287976,1780299464,286451373,2446758561]),m=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class E extends d{constructor(){super(28),this.Ah=g[0]|0,this.Al=g[1]|0,this.Bh=g[2]|0,this.Bl=g[3]|0,this.Ch=g[4]|0,this.Cl=g[5]|0,this.Dh=g[6]|0,this.Dl=g[7]|0,this.Eh=g[8]|0,this.El=g[9]|0,this.Fh=g[10]|0,this.Fl=g[11]|0,this.Gh=g[12]|0,this.Gl=g[13]|0,this.Hh=g[14]|0,this.Hl=g[15]|0}}We.SHA512_224=E;class _ extends d{constructor(){super(32),this.Ah=m[0]|0,this.Al=m[1]|0,this.Bh=m[2]|0,this.Bl=m[3]|0,this.Ch=m[4]|0,this.Cl=m[5]|0,this.Dh=m[6]|0,this.Dl=m[7]|0,this.Eh=m[8]|0,this.El=m[9]|0,this.Fh=m[10]|0,this.Fl=m[11]|0,this.Gh=m[12]|0,this.Gl=m[13]|0,this.Hh=m[14]|0,this.Hl=m[15]|0}}return We.SHA512_256=_,We.sha256=(0,n.createHasher)(()=>new s),We.sha224=(0,n.createHasher)(()=>new o),We.sha512=(0,n.createHasher)(()=>new d),We.sha384=(0,n.createHasher)(()=>new y),We.sha512_256=(0,n.createHasher)(()=>new _),We.sha512_224=(0,n.createHasher)(()=>new E),We}var Zs={},Nu={},ku={},Xh;function U1(){return Xh||(Xh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.hmac=e.HMAC=void 0;const t=ui();class n extends t.Hash{constructor(s,o){super(),this.finished=!1,this.destroyed=!1,(0,t.ahash)(s);const c=(0,t.toBytes)(o);if(this.iHash=s.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const a=this.blockLen,u=new Uint8Array(a);u.set(c.length>a?s.create().update(c).digest():c);for(let f=0;f<u.length;f++)u[f]^=54;this.iHash.update(u),this.oHash=s.create();for(let f=0;f<u.length;f++)u[f]^=106;this.oHash.update(u),(0,t.clean)(u)}update(s){return(0,t.aexists)(this),this.iHash.update(s),this}digestInto(s){(0,t.aexists)(this),(0,t.abytes)(s,this.outputLen),this.finished=!0,this.iHash.digestInto(s),this.oHash.update(s),this.oHash.digestInto(s),this.destroy()}digest(){const s=new Uint8Array(this.oHash.outputLen);return this.digestInto(s),s}_cloneInto(s){s||(s=Object.create(Object.getPrototypeOf(this),{}));const{oHash:o,iHash:c,finished:a,destroyed:u,blockLen:f,outputLen:l}=this;return s=s,s.finished=a,s.destroyed=u,s.blockLen=f,s.outputLen=l,s.oHash=o._cloneInto(s.oHash),s.iHash=c._cloneInto(s.iHash),s}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}e.HMAC=n;const r=(i,s,o)=>new n(i,s).update(o).digest();e.hmac=r,e.hmac.create=(i,s)=>new n(i,s)})(ku)),ku}var Pu={},zh;function Ms(){return zh||(zh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.notImplemented=e.bitMask=e.utf8ToBytes=e.randomBytes=e.isBytes=e.hexToBytes=e.concatBytes=e.bytesToUtf8=e.bytesToHex=e.anumber=e.abytes=void 0,e.abool=s,e._abool2=o,e._abytes2=c,e.numberToHexUnpadded=a,e.hexToNumber=u,e.bytesToNumberBE=f,e.bytesToNumberLE=l,e.numberToBytesBE=d,e.numberToBytesLE=y,e.numberToVarBytesBE=g,e.ensureBytes=m,e.equalBytes=E,e.copyBytes=_,e.asciiToBytes=S,e.inRange=T,e.aInRange=O,e.bitLen=A,e.bitGet=R,e.bitSet=M,e.createHmacDrbg=U,e.validateObject=K,e.isHash=H,e._validateObject=$,e.memoized=D;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=ui();var n=ui();Object.defineProperty(e,"abytes",{enumerable:!0,get:function(){return n.abytes}}),Object.defineProperty(e,"anumber",{enumerable:!0,get:function(){return n.anumber}}),Object.defineProperty(e,"bytesToHex",{enumerable:!0,get:function(){return n.bytesToHex}}),Object.defineProperty(e,"bytesToUtf8",{enumerable:!0,get:function(){return n.bytesToUtf8}}),Object.defineProperty(e,"concatBytes",{enumerable:!0,get:function(){return n.concatBytes}}),Object.defineProperty(e,"hexToBytes",{enumerable:!0,get:function(){return n.hexToBytes}}),Object.defineProperty(e,"isBytes",{enumerable:!0,get:function(){return n.isBytes}}),Object.defineProperty(e,"randomBytes",{enumerable:!0,get:function(){return n.randomBytes}}),Object.defineProperty(e,"utf8ToBytes",{enumerable:!0,get:function(){return n.utf8ToBytes}});const r=BigInt(0),i=BigInt(1);function s(F,x){if(typeof x!="boolean")throw new Error(F+" boolean expected, got "+x)}function o(F,x=""){if(typeof F!="boolean"){const B=x&&`"${x}"`;throw new Error(B+"expected boolean, got type="+typeof F)}return F}function c(F,x,B=""){const q=(0,t.isBytes)(F),N=F?.length,L=x!==void 0;if(!q||L&&N!==x){const G=B&&`"${B}" `,X=L?` of length ${x}`:"",Y=q?`length=${N}`:`type=${typeof F}`;throw new Error(G+"expected Uint8Array"+X+", got "+Y)}return F}function a(F){const x=F.toString(16);return x.length&1?"0"+x:x}function u(F){if(typeof F!="string")throw new Error("hex string expected, got "+typeof F);return F===""?r:BigInt("0x"+F)}function f(F){return u((0,t.bytesToHex)(F))}function l(F){return(0,t.abytes)(F),u((0,t.bytesToHex)(Uint8Array.from(F).reverse()))}function d(F,x){return(0,t.hexToBytes)(F.toString(16).padStart(x*2,"0"))}function y(F,x){return d(F,x).reverse()}function g(F){return(0,t.hexToBytes)(a(F))}function m(F,x,B){let q;if(typeof x=="string")try{q=(0,t.hexToBytes)(x)}catch(L){throw new Error(F+" must be hex string or Uint8Array, cause: "+L)}else if((0,t.isBytes)(x))q=Uint8Array.from(x);else throw new Error(F+" must be hex string or Uint8Array");const N=q.length;if(typeof B=="number"&&N!==B)throw new Error(F+" of length "+B+" expected, got "+N);return q}function E(F,x){if(F.length!==x.length)return!1;let B=0;for(let q=0;q<F.length;q++)B|=F[q]^x[q];return B===0}function _(F){return Uint8Array.from(F)}function S(F){return Uint8Array.from(F,(x,B)=>{const q=x.charCodeAt(0);if(x.length!==1||q>127)throw new Error(`string contains non-ASCII character "${F[B]}" with code ${q} at position ${B}`);return q})}const w=F=>typeof F=="bigint"&&r<=F;function T(F,x,B){return w(F)&&w(x)&&w(B)&&x<=F&&F<B}function O(F,x,B,q){if(!T(x,B,q))throw new Error("expected valid "+F+": "+B+" <= n < "+q+", got "+x)}function A(F){let x;for(x=0;F>r;F>>=i,x+=1);return x}function R(F,x){return F>>BigInt(x)&i}function M(F,x,B){return F|(B?i:r)<<BigInt(x)}const v=F=>(i<<BigInt(F))-i;e.bitMask=v;function U(F,x,B){if(typeof F!="number"||F<2)throw new Error("hashLen must be a number");if(typeof x!="number"||x<2)throw new Error("qByteLen must be a number");if(typeof B!="function")throw new Error("hmacFn must be a function");const q=ae=>new Uint8Array(ae),N=ae=>Uint8Array.of(ae);let L=q(F),G=q(F),X=0;const Y=()=>{L.fill(1),G.fill(0),X=0},ce=(...ae)=>B(G,L,...ae),ue=(ae=q(0))=>{G=ce(N(0),ae),L=ce(),ae.length!==0&&(G=ce(N(1),ae),L=ce())},te=()=>{if(X++>=1e3)throw new Error("drbg: tried 1000 values");let ae=0;const we=[];for(;ae<x;){L=ce();const ye=L.slice();we.push(ye),ae+=L.length}return(0,t.concatBytes)(...we)};return(ae,we)=>{Y(),ue(ae);let ye;for(;!(ye=we(te()));)ue();return Y(),ye}}const V={bigint:F=>typeof F=="bigint",function:F=>typeof F=="function",boolean:F=>typeof F=="boolean",string:F=>typeof F=="string",stringOrUint8Array:F=>typeof F=="string"||(0,t.isBytes)(F),isSafeInteger:F=>Number.isSafeInteger(F),array:F=>Array.isArray(F),field:(F,x)=>x.Fp.isValid(F),hash:F=>typeof F=="function"&&Number.isSafeInteger(F.outputLen)};function K(F,x,B={}){const q=(N,L,G)=>{const X=V[L];if(typeof X!="function")throw new Error("invalid validator function");const Y=F[N];if(!(G&&Y===void 0)&&!X(Y,F))throw new Error("param "+String(N)+" is invalid. Expected "+L+", got "+Y)};for(const[N,L]of Object.entries(x))q(N,L,!1);for(const[N,L]of Object.entries(B))q(N,L,!0);return F}function H(F){return typeof F=="function"&&Number.isSafeInteger(F.outputLen)}function $(F,x,B={}){if(!F||typeof F!="object")throw new Error("expected valid options object");function q(N,L,G){const X=F[N];if(G&&X===void 0)return;const Y=typeof X;if(Y!==L||X===null)throw new Error(`param "${N}" is invalid: expected ${L}, got ${Y}`)}Object.entries(x).forEach(([N,L])=>q(N,L,!1)),Object.entries(B).forEach(([N,L])=>q(N,L,!0))}const P=()=>{throw new Error("not implemented")};e.notImplemented=P;function D(F){const x=new WeakMap;return(B,...q)=>{const N=x.get(B);if(N!==void 0)return N;const L=F(B,...q);return x.set(B,L),L}}})(Pu)),Pu}var Sn={},Je={},Yh;function nc(){if(Yh)return Je;Yh=1,Object.defineProperty(Je,"__esModule",{value:!0}),Je.isNegativeLE=void 0,Je.mod=l,Je.pow=d,Je.pow2=y,Je.invert=g,Je.tonelliShanks=w,Je.FpSqrt=T,Je.validateField=R,Je.FpPow=M,Je.FpInvertBatch=v,Je.FpDiv=U,Je.FpLegendre=V,Je.FpIsSquare=K,Je.nLength=H,Je.Field=$,Je.FpSqrtOdd=P,Je.FpSqrtEven=D,Je.hashToPrivateScalar=F,Je.getFieldBytesLength=x,Je.getMinHashLength=B,Je.mapHashToField=q;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const e=Ms(),t=BigInt(0),n=BigInt(1),r=BigInt(2),i=BigInt(3),s=BigInt(4),o=BigInt(5),c=BigInt(7),a=BigInt(8),u=BigInt(9),f=BigInt(16);function l(N,L){const G=N%L;return G>=t?G:L+G}function d(N,L,G){return M($(G),N,L)}function y(N,L,G){let X=N;for(;L-- >t;)X*=X,X%=G;return X}function g(N,L){if(N===t)throw new Error("invert: expected non-zero number");if(L<=t)throw new Error("invert: expected positive modulus, got "+L);let G=l(N,L),X=L,Y=t,ce=n;for(;G!==t;){const te=X/G,Z=X%G,ae=Y-ce*te;X=G,G=Z,Y=ce,ce=ae}if(X!==n)throw new Error("invert: does not exist");return l(Y,L)}function m(N,L,G){if(!N.eql(N.sqr(L),G))throw new Error("Cannot find square root")}function E(N,L){const G=(N.ORDER+n)/s,X=N.pow(L,G);return m(N,X,L),X}function _(N,L){const G=(N.ORDER-o)/a,X=N.mul(L,r),Y=N.pow(X,G),ce=N.mul(L,Y),ue=N.mul(N.mul(ce,r),Y),te=N.mul(ce,N.sub(ue,N.ONE));return m(N,te,L),te}function S(N){const L=$(N),G=w(N),X=G(L,L.neg(L.ONE)),Y=G(L,X),ce=G(L,L.neg(X)),ue=(N+c)/f;return(te,Z)=>{let ae=te.pow(Z,ue),we=te.mul(ae,X);const ye=te.mul(ae,Y),J=te.mul(ae,ce),le=te.eql(te.sqr(we),Z),Ae=te.eql(te.sqr(ye),Z);ae=te.cmov(ae,we,le),we=te.cmov(J,ye,Ae);const qe=te.eql(te.sqr(we),Z),tt=te.cmov(ae,we,qe);return m(te,tt,Z),tt}}function w(N){if(N<i)throw new Error("sqrt is not defined for small field");let L=N-n,G=0;for(;L%r===t;)L/=r,G++;let X=r;const Y=$(N);for(;V(Y,X)===1;)if(X++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(G===1)return E;let ce=Y.pow(X,L);const ue=(L+n)/r;return function(Z,ae){if(Z.is0(ae))return ae;if(V(Z,ae)!==1)throw new Error("Cannot find square root");let we=G,ye=Z.mul(Z.ONE,ce),J=Z.pow(ae,L),le=Z.pow(ae,ue);for(;!Z.eql(J,Z.ONE);){if(Z.is0(J))return Z.ZERO;let Ae=1,qe=Z.sqr(J);for(;!Z.eql(qe,Z.ONE);)if(Ae++,qe=Z.sqr(qe),Ae===we)throw new Error("Cannot find square root");const tt=n<<BigInt(we-Ae-1),ut=Z.pow(ye,tt);we=Ae,ye=Z.sqr(ut),J=Z.mul(J,ye),le=Z.mul(le,ut)}return le}}function T(N){return N%s===i?E:N%a===o?_:N%f===u?S(N):w(N)}const O=(N,L)=>(l(N,L)&n)===n;Je.isNegativeLE=O;const A=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function R(N){const L={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},G=A.reduce((X,Y)=>(X[Y]="function",X),L);return(0,e._validateObject)(N,G),N}function M(N,L,G){if(G<t)throw new Error("invalid exponent, negatives unsupported");if(G===t)return N.ONE;if(G===n)return L;let X=N.ONE,Y=L;for(;G>t;)G&n&&(X=N.mul(X,Y)),Y=N.sqr(Y),G>>=n;return X}function v(N,L,G=!1){const X=new Array(L.length).fill(G?N.ZERO:void 0),Y=L.reduce((ue,te,Z)=>N.is0(te)?ue:(X[Z]=ue,N.mul(ue,te)),N.ONE),ce=N.inv(Y);return L.reduceRight((ue,te,Z)=>N.is0(te)?ue:(X[Z]=N.mul(ue,X[Z]),N.mul(ue,te)),ce),X}function U(N,L,G){return N.mul(L,typeof G=="bigint"?g(G,N.ORDER):N.inv(G))}function V(N,L){const G=(N.ORDER-n)/r,X=N.pow(L,G),Y=N.eql(X,N.ONE),ce=N.eql(X,N.ZERO),ue=N.eql(X,N.neg(N.ONE));if(!Y&&!ce&&!ue)throw new Error("invalid Legendre symbol result");return Y?1:ce?0:-1}function K(N,L){return V(N,L)===1}function H(N,L){L!==void 0&&(0,e.anumber)(L);const G=L!==void 0?L:N.toString(2).length,X=Math.ceil(G/8);return{nBitLength:G,nByteLength:X}}function $(N,L,G=!1,X={}){if(N<=t)throw new Error("invalid field: expected ORDER > 0, got "+N);let Y,ce,ue=!1,te;if(typeof L=="object"&&L!=null){if(X.sqrt||G)throw new Error("cannot specify opts in two arguments");const J=L;J.BITS&&(Y=J.BITS),J.sqrt&&(ce=J.sqrt),typeof J.isLE=="boolean"&&(G=J.isLE),typeof J.modFromBytes=="boolean"&&(ue=J.modFromBytes),te=J.allowedLengths}else typeof L=="number"&&(Y=L),X.sqrt&&(ce=X.sqrt);const{nBitLength:Z,nByteLength:ae}=H(N,Y);if(ae>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let we;const ye=Object.freeze({ORDER:N,isLE:G,BITS:Z,BYTES:ae,MASK:(0,e.bitMask)(Z),ZERO:t,ONE:n,allowedLengths:te,create:J=>l(J,N),isValid:J=>{if(typeof J!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof J);return t<=J&&J<N},is0:J=>J===t,isValidNot0:J=>!ye.is0(J)&&ye.isValid(J),isOdd:J=>(J&n)===n,neg:J=>l(-J,N),eql:(J,le)=>J===le,sqr:J=>l(J*J,N),add:(J,le)=>l(J+le,N),sub:(J,le)=>l(J-le,N),mul:(J,le)=>l(J*le,N),pow:(J,le)=>M(ye,J,le),div:(J,le)=>l(J*g(le,N),N),sqrN:J=>J*J,addN:(J,le)=>J+le,subN:(J,le)=>J-le,mulN:(J,le)=>J*le,inv:J=>g(J,N),sqrt:ce||(J=>(we||(we=T(N)),we(ye,J))),toBytes:J=>G?(0,e.numberToBytesLE)(J,ae):(0,e.numberToBytesBE)(J,ae),fromBytes:(J,le=!0)=>{if(te){if(!te.includes(J.length)||J.length>ae)throw new Error("Field.fromBytes: expected "+te+" bytes, got "+J.length);const qe=new Uint8Array(ae);qe.set(J,G?0:qe.length-J.length),J=qe}if(J.length!==ae)throw new Error("Field.fromBytes: expected "+ae+" bytes, got "+J.length);let Ae=G?(0,e.bytesToNumberLE)(J):(0,e.bytesToNumberBE)(J);if(ue&&(Ae=l(Ae,N)),!le&&!ye.isValid(Ae))throw new Error("invalid field element: outside of range 0..ORDER");return Ae},invertBatch:J=>v(ye,J),cmov:(J,le,Ae)=>Ae?le:J});return Object.freeze(ye)}function P(N,L){if(!N.isOdd)throw new Error("Field doesn't have isOdd");const G=N.sqrt(L);return N.isOdd(G)?G:N.neg(G)}function D(N,L){if(!N.isOdd)throw new Error("Field doesn't have isOdd");const G=N.sqrt(L);return N.isOdd(G)?N.neg(G):G}function F(N,L,G=!1){N=(0,e.ensureBytes)("privateHash",N);const X=N.length,Y=H(L).nByteLength+8;if(Y<24||X<Y||X>1024)throw new Error("hashToPrivateScalar: expected "+Y+"-1024 bytes of input, got "+X);const ce=G?(0,e.bytesToNumberLE)(N):(0,e.bytesToNumberBE)(N);return l(ce,L-n)+n}function x(N){if(typeof N!="bigint")throw new Error("field order must be bigint");const L=N.toString(2).length;return Math.ceil(L/8)}function B(N){const L=x(N);return L+Math.ceil(L/2)}function q(N,L,G=!1){const X=N.length,Y=x(L),ce=B(L);if(X<16||X<ce||X>1024)throw new Error("expected "+ce+"-1024 bytes of input, got "+X);const ue=G?(0,e.bytesToNumberLE)(N):(0,e.bytesToNumberBE)(N),te=l(ue,L-n)+n;return G?(0,e.numberToBytesLE)(te,Y):(0,e.numberToBytesBE)(te,Y)}return Je}var Zh;function C1(){if(Zh)return Sn;Zh=1,Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.wNAF=void 0,Sn.negateCt=i,Sn.normalizeZ=s,Sn.mulEndoUnsafe=E,Sn.pippenger=_,Sn.precomputeMSMUnsafe=S,Sn.validateBasic=w,Sn._createCurveFields=O;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const e=Ms(),t=nc(),n=BigInt(0),r=BigInt(1);function i(A,R){const M=R.negate();return A?M:R}function s(A,R){const M=(0,t.FpInvertBatch)(A.Fp,R.map(v=>v.Z));return R.map((v,U)=>A.fromAffine(v.toAffine(M[U])))}function o(A,R){if(!Number.isSafeInteger(A)||A<=0||A>R)throw new Error("invalid window size, expected [1.."+R+"], got W="+A)}function c(A,R){o(A,R);const M=Math.ceil(R/A)+1,v=2**(A-1),U=2**A,V=(0,e.bitMask)(A),K=BigInt(A);return{windows:M,windowSize:v,mask:V,maxNumber:U,shiftBy:K}}function a(A,R,M){const{windowSize:v,mask:U,maxNumber:V,shiftBy:K}=M;let H=Number(A&U),$=A>>K;H>v&&(H-=V,$+=r);const P=R*v,D=P+Math.abs(H)-1,F=H===0,x=H<0,B=R%2!==0;return{nextN:$,offset:D,isZero:F,isNeg:x,isNegF:B,offsetF:P}}function u(A,R){if(!Array.isArray(A))throw new Error("array expected");A.forEach((M,v)=>{if(!(M instanceof R))throw new Error("invalid point at index "+v)})}function f(A,R){if(!Array.isArray(A))throw new Error("array of scalars expected");A.forEach((M,v)=>{if(!R.isValid(M))throw new Error("invalid scalar at index "+v)})}const l=new WeakMap,d=new WeakMap;function y(A){return d.get(A)||1}function g(A){if(A!==n)throw new Error("invalid wNAF")}class m{constructor(R,M){this.BASE=R.BASE,this.ZERO=R.ZERO,this.Fn=R.Fn,this.bits=M}_unsafeLadder(R,M,v=this.ZERO){let U=R;for(;M>n;)M&r&&(v=v.add(U)),U=U.double(),M>>=r;return v}precomputeWindow(R,M){const{windows:v,windowSize:U}=c(M,this.bits),V=[];let K=R,H=K;for(let $=0;$<v;$++){H=K,V.push(H);for(let P=1;P<U;P++)H=H.add(K),V.push(H);K=H.double()}return V}wNAF(R,M,v){if(!this.Fn.isValid(v))throw new Error("invalid scalar");let U=this.ZERO,V=this.BASE;const K=c(R,this.bits);for(let H=0;H<K.windows;H++){const{nextN:$,offset:P,isZero:D,isNeg:F,isNegF:x,offsetF:B}=a(v,H,K);v=$,D?V=V.add(i(x,M[B])):U=U.add(i(F,M[P]))}return g(v),{p:U,f:V}}wNAFUnsafe(R,M,v,U=this.ZERO){const V=c(R,this.bits);for(let K=0;K<V.windows&&v!==n;K++){const{nextN:H,offset:$,isZero:P,isNeg:D}=a(v,K,V);if(v=H,!P){const F=M[$];U=U.add(D?F.negate():F)}}return g(v),U}getPrecomputes(R,M,v){let U=l.get(M);return U||(U=this.precomputeWindow(M,R),R!==1&&(typeof v=="function"&&(U=v(U)),l.set(M,U))),U}cached(R,M,v){const U=y(R);return this.wNAF(U,this.getPrecomputes(U,R,v),M)}unsafe(R,M,v,U){const V=y(R);return V===1?this._unsafeLadder(R,M,U):this.wNAFUnsafe(V,this.getPrecomputes(V,R,v),M,U)}createCache(R,M){o(M,this.bits),d.set(R,M),l.delete(R)}hasCache(R){return y(R)!==1}}Sn.wNAF=m;function E(A,R,M,v){let U=R,V=A.ZERO,K=A.ZERO;for(;M>n||v>n;)M&r&&(V=V.add(U)),v&r&&(K=K.add(U)),U=U.double(),M>>=r,v>>=r;return{p1:V,p2:K}}function _(A,R,M,v){u(M,A),f(v,R);const U=M.length,V=v.length;if(U!==V)throw new Error("arrays of points and scalars must have equal length");const K=A.ZERO,H=(0,e.bitLen)(BigInt(U));let $=1;H>12?$=H-3:H>4?$=H-2:H>0&&($=2);const P=(0,e.bitMask)($),D=new Array(Number(P)+1).fill(K),F=Math.floor((R.BITS-1)/$)*$;let x=K;for(let B=F;B>=0;B-=$){D.fill(K);for(let N=0;N<V;N++){const L=v[N],G=Number(L>>BigInt(B)&P);D[G]=D[G].add(M[N])}let q=K;for(let N=D.length-1,L=K;N>0;N--)L=L.add(D[N]),q=q.add(L);if(x=x.add(q),B!==0)for(let N=0;N<$;N++)x=x.double()}return x}function S(A,R,M,v){o(v,R.BITS),u(M,A);const U=A.ZERO,V=2**v-1,K=Math.ceil(R.BITS/v),H=(0,e.bitMask)(v),$=M.map(P=>{const D=[];for(let F=0,x=P;F<V;F++)D.push(x),x=x.add(P);return D});return P=>{if(f(P,R),P.length>M.length)throw new Error("array of scalars must be smaller than array of points");let D=U;for(let F=0;F<K;F++){if(D!==U)for(let B=0;B<v;B++)D=D.double();const x=BigInt(K*v-(F+1)*v);for(let B=0;B<P.length;B++){const q=P[B],N=Number(q>>x&H);N&&(D=D.add($[B][N-1]))}}return D}}function w(A){return(0,t.validateField)(A.Fp),(0,e.validateObject)(A,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...(0,t.nLength)(A.n,A.nBitLength),...A,p:A.Fp.ORDER})}function T(A,R,M){if(R){if(R.ORDER!==A)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return(0,t.validateField)(R),R}else return(0,t.Field)(A,{isLE:M})}function O(A,R,M={},v){if(v===void 0&&(v=A==="edwards"),!R||typeof R!="object")throw new Error(`expected valid ${A} CURVE object`);for(const $ of["p","n","h"]){const P=R[$];if(!(typeof P=="bigint"&&P>n))throw new Error(`CURVE.${$} must be positive bigint`)}const U=T(R.p,M.Fp,v),V=T(R.n,M.Fn,v),H=["Gx","Gy","a",A==="weierstrass"?"b":"d"];for(const $ of H)if(!U.isValid(R[$]))throw new Error(`CURVE.${$} must be valid field element of CURVE.Fp`);return R=Object.freeze(Object.assign({},R)),{CURVE:R,Fp:U,Fn:V}}return Sn}var Jh;function Cy(){return Jh||(Jh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.DER=e.DERErr=void 0,e._splitEndoScalar=c,e._normFnElement=E,e.weierstrassN=_,e.SWUFpSqrtRatio=w,e.mapToCurveSimpleSWU=T,e.ecdh=A,e.ecdsa=R,e.weierstrassPoints=M,e._legacyHelperEquat=V,e.weierstrass=$;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=U1(),n=ui(),r=Ms(),i=C1(),s=nc(),o=(P,D)=>(P+(P>=0?D:-D)/y)/D;function c(P,D,F){const[[x,B],[q,N]]=D,L=o(N*P,F),G=o(-B*P,F);let X=P-L*x-G*q,Y=-L*B-G*N;const ce=X<l,ue=Y<l;ce&&(X=-X),ue&&(Y=-Y);const te=(0,r.bitMask)(Math.ceil((0,r.bitLen)(F)/2))+d;if(X<l||X>=te||Y<l||Y>=te)throw new Error("splitScalar (endomorphism): failed, k="+P);return{k1neg:ce,k1:X,k2neg:ue,k2:Y}}function a(P){if(!["compact","recovered","der"].includes(P))throw new Error('Signature format must be "compact", "recovered", or "der"');return P}function u(P,D){const F={};for(let x of Object.keys(D))F[x]=P[x]===void 0?D[x]:P[x];return(0,r._abool2)(F.lowS,"lowS"),(0,r._abool2)(F.prehash,"prehash"),F.format!==void 0&&a(F.format),F}class f extends Error{constructor(D=""){super(D)}}e.DERErr=f,e.DER={Err:f,_tlv:{encode:(P,D)=>{const{Err:F}=e.DER;if(P<0||P>256)throw new F("tlv.encode: wrong tag");if(D.length&1)throw new F("tlv.encode: unpadded data");const x=D.length/2,B=(0,r.numberToHexUnpadded)(x);if(B.length/2&128)throw new F("tlv.encode: long form length too big");const q=x>127?(0,r.numberToHexUnpadded)(B.length/2|128):"";return(0,r.numberToHexUnpadded)(P)+q+B+D},decode(P,D){const{Err:F}=e.DER;let x=0;if(P<0||P>256)throw new F("tlv.encode: wrong tag");if(D.length<2||D[x++]!==P)throw new F("tlv.decode: wrong tlv");const B=D[x++],q=!!(B&128);let N=0;if(!q)N=B;else{const G=B&127;if(!G)throw new F("tlv.decode(long): indefinite length not supported");if(G>4)throw new F("tlv.decode(long): byte length is too big");const X=D.subarray(x,x+G);if(X.length!==G)throw new F("tlv.decode: length bytes not complete");if(X[0]===0)throw new F("tlv.decode(long): zero leftmost byte");for(const Y of X)N=N<<8|Y;if(x+=G,N<128)throw new F("tlv.decode(long): not minimal encoding")}const L=D.subarray(x,x+N);if(L.length!==N)throw new F("tlv.decode: wrong value length");return{v:L,l:D.subarray(x+N)}}},_int:{encode(P){const{Err:D}=e.DER;if(P<l)throw new D("integer: negative integers are not allowed");let F=(0,r.numberToHexUnpadded)(P);if(Number.parseInt(F[0],16)&8&&(F="00"+F),F.length&1)throw new D("unexpected DER parsing assertion: unpadded hex");return F},decode(P){const{Err:D}=e.DER;if(P[0]&128)throw new D("invalid signature integer: negative");if(P[0]===0&&!(P[1]&128))throw new D("invalid signature integer: unnecessary leading zero");return(0,r.bytesToNumberBE)(P)}},toSig(P){const{Err:D,_int:F,_tlv:x}=e.DER,B=(0,r.ensureBytes)("signature",P),{v:q,l:N}=x.decode(48,B);if(N.length)throw new D("invalid signature: left bytes after parsing");const{v:L,l:G}=x.decode(2,q),{v:X,l:Y}=x.decode(2,G);if(Y.length)throw new D("invalid signature: left bytes after parsing");return{r:F.decode(L),s:F.decode(X)}},hexFromSig(P){const{_tlv:D,_int:F}=e.DER,x=D.encode(2,F.encode(P.r)),B=D.encode(2,F.encode(P.s)),q=x+B;return D.encode(48,q)}};const l=BigInt(0),d=BigInt(1),y=BigInt(2),g=BigInt(3),m=BigInt(4);function E(P,D){const{BYTES:F}=P;let x;if(typeof D=="bigint")x=D;else{let B=(0,r.ensureBytes)("private key",D);try{x=P.fromBytes(B)}catch{throw new Error(`invalid private key: expected ui8a of size ${F}, got ${typeof D}`)}}if(!P.isValidNot0(x))throw new Error("invalid private key: out of range [1..N-1]");return x}function _(P,D={}){const F=(0,i._createCurveFields)("weierstrass",P,D),{Fp:x,Fn:B}=F;let q=F.CURVE;const{h:N,n:L}=q;(0,r._validateObject)(D,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:G}=D;if(G&&(!x.is0(q.a)||typeof G.beta!="bigint"||!Array.isArray(G.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const X=O(x,B);function Y(){if(!x.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function ce(Ce,oe,ne){const{x:re,y:k}=oe.toAffine(),p=x.toBytes(re);if((0,r._abool2)(ne,"isCompressed"),ne){Y();const h=!x.isOdd(k);return(0,r.concatBytes)(S(h),p)}else return(0,r.concatBytes)(Uint8Array.of(4),p,x.toBytes(k))}function ue(Ce){(0,r._abytes2)(Ce,void 0,"Point");const{publicKey:oe,publicKeyUncompressed:ne}=X,re=Ce.length,k=Ce[0],p=Ce.subarray(1);if(re===oe&&(k===2||k===3)){const h=x.fromBytes(p);if(!x.isValid(h))throw new Error("bad point: is not on curve, wrong x");const b=ae(h);let I;try{I=x.sqrt(b)}catch(W){const ie=W instanceof Error?": "+W.message:"";throw new Error("bad point: is not on curve, sqrt error"+ie)}Y();const C=x.isOdd(I);return(k&1)===1!==C&&(I=x.neg(I)),{x:h,y:I}}else if(re===ne&&k===4){const h=x.BYTES,b=x.fromBytes(p.subarray(0,h)),I=x.fromBytes(p.subarray(h,h*2));if(!we(b,I))throw new Error("bad point: is not on curve");return{x:b,y:I}}else throw new Error(`bad point: got length ${re}, expected compressed=${oe} or uncompressed=${ne}`)}const te=D.toBytes||ce,Z=D.fromBytes||ue;function ae(Ce){const oe=x.sqr(Ce),ne=x.mul(oe,Ce);return x.add(x.add(ne,x.mul(Ce,q.a)),q.b)}function we(Ce,oe){const ne=x.sqr(oe),re=ae(Ce);return x.eql(ne,re)}if(!we(q.Gx,q.Gy))throw new Error("bad curve params: generator point");const ye=x.mul(x.pow(q.a,g),m),J=x.mul(x.sqr(q.b),BigInt(27));if(x.is0(x.add(ye,J)))throw new Error("bad curve params: a or b");function le(Ce,oe,ne=!1){if(!x.isValid(oe)||ne&&x.is0(oe))throw new Error(`bad point coordinate ${Ce}`);return oe}function Ae(Ce){if(!(Ce instanceof Oe))throw new Error("ProjectivePoint expected")}function qe(Ce){if(!G||!G.basises)throw new Error("no endo");return c(Ce,G.basises,B.ORDER)}const tt=(0,r.memoized)((Ce,oe)=>{const{X:ne,Y:re,Z:k}=Ce;if(x.eql(k,x.ONE))return{x:ne,y:re};const p=Ce.is0();oe==null&&(oe=p?x.ONE:x.inv(k));const h=x.mul(ne,oe),b=x.mul(re,oe),I=x.mul(k,oe);if(p)return{x:x.ZERO,y:x.ZERO};if(!x.eql(I,x.ONE))throw new Error("invZ was invalid");return{x:h,y:b}}),ut=(0,r.memoized)(Ce=>{if(Ce.is0()){if(D.allowInfinityPoint&&!x.is0(Ce.Y))return;throw new Error("bad point: ZERO")}const{x:oe,y:ne}=Ce.toAffine();if(!x.isValid(oe)||!x.isValid(ne))throw new Error("bad point: x or y not field elements");if(!we(oe,ne))throw new Error("bad point: equation left != right");if(!Ce.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function It(Ce,oe,ne,re,k){return ne=new Oe(x.mul(ne.X,Ce),ne.Y,ne.Z),oe=(0,i.negateCt)(re,oe),ne=(0,i.negateCt)(k,ne),oe.add(ne)}class Oe{constructor(oe,ne,re){this.X=le("x",oe),this.Y=le("y",ne,!0),this.Z=le("z",re),Object.freeze(this)}static CURVE(){return q}static fromAffine(oe){const{x:ne,y:re}=oe||{};if(!oe||!x.isValid(ne)||!x.isValid(re))throw new Error("invalid affine point");if(oe instanceof Oe)throw new Error("projective point not allowed");return x.is0(ne)&&x.is0(re)?Oe.ZERO:new Oe(ne,re,x.ONE)}static fromBytes(oe){const ne=Oe.fromAffine(Z((0,r._abytes2)(oe,void 0,"point")));return ne.assertValidity(),ne}static fromHex(oe){return Oe.fromBytes((0,r.ensureBytes)("pointHex",oe))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(oe=8,ne=!0){return it.createCache(this,oe),ne||this.multiply(g),this}assertValidity(){ut(this)}hasEvenY(){const{y:oe}=this.toAffine();if(!x.isOdd)throw new Error("Field doesn't support isOdd");return!x.isOdd(oe)}equals(oe){Ae(oe);const{X:ne,Y:re,Z:k}=this,{X:p,Y:h,Z:b}=oe,I=x.eql(x.mul(ne,b),x.mul(p,k)),C=x.eql(x.mul(re,b),x.mul(h,k));return I&&C}negate(){return new Oe(this.X,x.neg(this.Y),this.Z)}double(){const{a:oe,b:ne}=q,re=x.mul(ne,g),{X:k,Y:p,Z:h}=this;let b=x.ZERO,I=x.ZERO,C=x.ZERO,j=x.mul(k,k),W=x.mul(p,p),ie=x.mul(h,h),Q=x.mul(k,p);return Q=x.add(Q,Q),C=x.mul(k,h),C=x.add(C,C),b=x.mul(oe,C),I=x.mul(re,ie),I=x.add(b,I),b=x.sub(W,I),I=x.add(W,I),I=x.mul(b,I),b=x.mul(Q,b),C=x.mul(re,C),ie=x.mul(oe,ie),Q=x.sub(j,ie),Q=x.mul(oe,Q),Q=x.add(Q,C),C=x.add(j,j),j=x.add(C,j),j=x.add(j,ie),j=x.mul(j,Q),I=x.add(I,j),ie=x.mul(p,h),ie=x.add(ie,ie),j=x.mul(ie,Q),b=x.sub(b,j),C=x.mul(ie,W),C=x.add(C,C),C=x.add(C,C),new Oe(b,I,C)}add(oe){Ae(oe);const{X:ne,Y:re,Z:k}=this,{X:p,Y:h,Z:b}=oe;let I=x.ZERO,C=x.ZERO,j=x.ZERO;const W=q.a,ie=x.mul(q.b,g);let Q=x.mul(ne,p),fe=x.mul(re,h),he=x.mul(k,b),Ne=x.add(ne,re),Pe=x.add(p,h);Ne=x.mul(Ne,Pe),Pe=x.add(Q,fe),Ne=x.sub(Ne,Pe),Pe=x.add(ne,k);let nt=x.add(p,b);return Pe=x.mul(Pe,nt),nt=x.add(Q,he),Pe=x.sub(Pe,nt),nt=x.add(re,k),I=x.add(h,b),nt=x.mul(nt,I),I=x.add(fe,he),nt=x.sub(nt,I),j=x.mul(W,Pe),I=x.mul(ie,he),j=x.add(I,j),I=x.sub(fe,j),j=x.add(fe,j),C=x.mul(I,j),fe=x.add(Q,Q),fe=x.add(fe,Q),he=x.mul(W,he),Pe=x.mul(ie,Pe),fe=x.add(fe,he),he=x.sub(Q,he),he=x.mul(W,he),Pe=x.add(Pe,he),Q=x.mul(fe,Pe),C=x.add(C,Q),Q=x.mul(nt,Pe),I=x.mul(Ne,I),I=x.sub(I,Q),Q=x.mul(Ne,fe),j=x.mul(nt,j),j=x.add(j,Q),new Oe(I,C,j)}subtract(oe){return this.add(oe.negate())}is0(){return this.equals(Oe.ZERO)}multiply(oe){const{endo:ne}=D;if(!B.isValidNot0(oe))throw new Error("invalid scalar: out of range");let re,k;const p=h=>it.cached(this,h,b=>(0,i.normalizeZ)(Oe,b));if(ne){const{k1neg:h,k1:b,k2neg:I,k2:C}=qe(oe),{p:j,f:W}=p(b),{p:ie,f:Q}=p(C);k=W.add(Q),re=It(ne.beta,j,ie,h,I)}else{const{p:h,f:b}=p(oe);re=h,k=b}return(0,i.normalizeZ)(Oe,[re,k])[0]}multiplyUnsafe(oe){const{endo:ne}=D,re=this;if(!B.isValid(oe))throw new Error("invalid scalar: out of range");if(oe===l||re.is0())return Oe.ZERO;if(oe===d)return re;if(it.hasCache(this))return this.multiply(oe);if(ne){const{k1neg:k,k1:p,k2neg:h,k2:b}=qe(oe),{p1:I,p2:C}=(0,i.mulEndoUnsafe)(Oe,re,p,b);return It(ne.beta,I,C,k,h)}else return it.unsafe(re,oe)}multiplyAndAddUnsafe(oe,ne,re){const k=this.multiplyUnsafe(ne).add(oe.multiplyUnsafe(re));return k.is0()?void 0:k}toAffine(oe){return tt(this,oe)}isTorsionFree(){const{isTorsionFree:oe}=D;return N===d?!0:oe?oe(Oe,this):it.unsafe(this,L).is0()}clearCofactor(){const{clearCofactor:oe}=D;return N===d?this:oe?oe(Oe,this):this.multiplyUnsafe(N)}isSmallOrder(){return this.multiplyUnsafe(N).is0()}toBytes(oe=!0){return(0,r._abool2)(oe,"isCompressed"),this.assertValidity(),te(Oe,this,oe)}toHex(oe=!0){return(0,r.bytesToHex)(this.toBytes(oe))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(oe=!0){return this.toBytes(oe)}_setWindowSize(oe){this.precompute(oe)}static normalizeZ(oe){return(0,i.normalizeZ)(Oe,oe)}static msm(oe,ne){return(0,i.pippenger)(Oe,B,oe,ne)}static fromPrivateKey(oe){return Oe.BASE.multiply(E(B,oe))}}Oe.BASE=new Oe(q.Gx,q.Gy,x.ONE),Oe.ZERO=new Oe(x.ZERO,x.ONE,x.ZERO),Oe.Fp=x,Oe.Fn=B;const mn=B.BITS,it=new i.wNAF(Oe,D.endo?Math.ceil(mn/2):mn);return Oe.BASE.precompute(8),Oe}function S(P){return Uint8Array.of(P?2:3)}function w(P,D){const F=P.ORDER;let x=l;for(let Z=F-d;Z%y===l;Z/=y)x+=d;const B=x,q=y<<B-d-d,N=q*y,L=(F-d)/N,G=(L-d)/y,X=N-d,Y=q,ce=P.pow(D,L),ue=P.pow(D,(L+d)/y);let te=(Z,ae)=>{let we=ce,ye=P.pow(ae,X),J=P.sqr(ye);J=P.mul(J,ae);let le=P.mul(Z,J);le=P.pow(le,G),le=P.mul(le,ye),ye=P.mul(le,ae),J=P.mul(le,Z);let Ae=P.mul(J,ye);le=P.pow(Ae,Y);let qe=P.eql(le,P.ONE);ye=P.mul(J,ue),le=P.mul(Ae,we),J=P.cmov(ye,J,qe),Ae=P.cmov(le,Ae,qe);for(let tt=B;tt>d;tt--){let ut=tt-y;ut=y<<ut-d;let It=P.pow(Ae,ut);const Oe=P.eql(It,P.ONE);ye=P.mul(J,we),we=P.mul(we,we),It=P.mul(Ae,we),J=P.cmov(ye,J,Oe),Ae=P.cmov(It,Ae,Oe)}return{isValid:qe,value:J}};if(P.ORDER%m===g){const Z=(P.ORDER-g)/m,ae=P.sqrt(P.neg(D));te=(we,ye)=>{let J=P.sqr(ye);const le=P.mul(we,ye);J=P.mul(J,le);let Ae=P.pow(J,Z);Ae=P.mul(Ae,le);const qe=P.mul(Ae,ae),tt=P.mul(P.sqr(Ae),ye),ut=P.eql(tt,we);let It=P.cmov(qe,Ae,ut);return{isValid:ut,value:It}}}return te}function T(P,D){(0,s.validateField)(P);const{A:F,B:x,Z:B}=D;if(!P.isValid(F)||!P.isValid(x)||!P.isValid(B))throw new Error("mapToCurveSimpleSWU: invalid opts");const q=w(P,B);if(!P.isOdd)throw new Error("Field does not have .isOdd()");return N=>{let L,G,X,Y,ce,ue,te,Z;L=P.sqr(N),L=P.mul(L,B),G=P.sqr(L),G=P.add(G,L),X=P.add(G,P.ONE),X=P.mul(X,x),Y=P.cmov(B,P.neg(G),!P.eql(G,P.ZERO)),Y=P.mul(Y,F),G=P.sqr(X),ue=P.sqr(Y),ce=P.mul(ue,F),G=P.add(G,ce),G=P.mul(G,X),ue=P.mul(ue,Y),ce=P.mul(ue,x),G=P.add(G,ce),te=P.mul(L,X);const{isValid:ae,value:we}=q(G,ue);Z=P.mul(L,N),Z=P.mul(Z,we),te=P.cmov(te,X,ae),Z=P.cmov(Z,we,ae);const ye=P.isOdd(N)===P.isOdd(Z);Z=P.cmov(P.neg(Z),Z,ye);const J=(0,s.FpInvertBatch)(P,[Y],!0)[0];return te=P.mul(te,J),{x:te,y:Z}}}function O(P,D){return{secretKey:D.BYTES,publicKey:1+P.BYTES,publicKeyUncompressed:1+2*P.BYTES,publicKeyHasPrefix:!0,signature:2*D.BYTES}}function A(P,D={}){const{Fn:F}=P,x=D.randomBytes||r.randomBytes,B=Object.assign(O(P.Fp,F),{seed:(0,s.getMinHashLength)(F.ORDER)});function q(te){try{return!!E(F,te)}catch{return!1}}function N(te,Z){const{publicKey:ae,publicKeyUncompressed:we}=B;try{const ye=te.length;return Z===!0&&ye!==ae||Z===!1&&ye!==we?!1:!!P.fromBytes(te)}catch{return!1}}function L(te=x(B.seed)){return(0,s.mapHashToField)((0,r._abytes2)(te,B.seed,"seed"),F.ORDER)}function G(te,Z=!0){return P.BASE.multiply(E(F,te)).toBytes(Z)}function X(te){const Z=L(te);return{secretKey:Z,publicKey:G(Z)}}function Y(te){if(typeof te=="bigint")return!1;if(te instanceof P)return!0;const{secretKey:Z,publicKey:ae,publicKeyUncompressed:we}=B;if(F.allowedLengths||Z===ae)return;const ye=(0,r.ensureBytes)("key",te).length;return ye===ae||ye===we}function ce(te,Z,ae=!0){if(Y(te)===!0)throw new Error("first arg must be private key");if(Y(Z)===!1)throw new Error("second arg must be public key");const we=E(F,te);return P.fromHex(Z).multiply(we).toBytes(ae)}return Object.freeze({getPublicKey:G,getSharedSecret:ce,keygen:X,Point:P,utils:{isValidSecretKey:q,isValidPublicKey:N,randomSecretKey:L,isValidPrivateKey:q,randomPrivateKey:L,normPrivateKeyToScalar:te=>E(F,te),precompute(te=8,Z=P.BASE){return Z.precompute(te,!1)}},lengths:B})}function R(P,D,F={}){(0,n.ahash)(D),(0,r._validateObject)(F,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const x=F.randomBytes||r.randomBytes,B=F.hmac||((ne,...re)=>(0,t.hmac)(D,ne,(0,r.concatBytes)(...re))),{Fp:q,Fn:N}=P,{ORDER:L,BITS:G}=N,{keygen:X,getPublicKey:Y,getSharedSecret:ce,utils:ue,lengths:te}=A(P,F),Z={prehash:!1,lowS:typeof F.lowS=="boolean"?F.lowS:!1,format:void 0,extraEntropy:!1},ae="compact";function we(ne){const re=L>>d;return ne>re}function ye(ne,re){if(!N.isValidNot0(re))throw new Error(`invalid signature ${ne}: out of range 1..Point.Fn.ORDER`);return re}function J(ne,re){a(re);const k=te.signature,p=re==="compact"?k:re==="recovered"?k+1:void 0;return(0,r._abytes2)(ne,p,`${re} signature`)}class le{constructor(re,k,p){this.r=ye("r",re),this.s=ye("s",k),p!=null&&(this.recovery=p),Object.freeze(this)}static fromBytes(re,k=ae){J(re,k);let p;if(k==="der"){const{r:C,s:j}=e.DER.toSig((0,r._abytes2)(re));return new le(C,j)}k==="recovered"&&(p=re[0],k="compact",re=re.subarray(1));const h=N.BYTES,b=re.subarray(0,h),I=re.subarray(h,h*2);return new le(N.fromBytes(b),N.fromBytes(I),p)}static fromHex(re,k){return this.fromBytes((0,r.hexToBytes)(re),k)}addRecoveryBit(re){return new le(this.r,this.s,re)}recoverPublicKey(re){const k=q.ORDER,{r:p,s:h,recovery:b}=this;if(b==null||![0,1,2,3].includes(b))throw new Error("recovery id invalid");if(L*y<k&&b>1)throw new Error("recovery id is ambiguous for h>1 curve");const C=b===2||b===3?p+L:p;if(!q.isValid(C))throw new Error("recovery id 2 or 3 invalid");const j=q.toBytes(C),W=P.fromBytes((0,r.concatBytes)(S((b&1)===0),j)),ie=N.inv(C),Q=qe((0,r.ensureBytes)("msgHash",re)),fe=N.create(-Q*ie),he=N.create(h*ie),Ne=P.BASE.multiplyUnsafe(fe).add(W.multiplyUnsafe(he));if(Ne.is0())throw new Error("point at infinify");return Ne.assertValidity(),Ne}hasHighS(){return we(this.s)}toBytes(re=ae){if(a(re),re==="der")return(0,r.hexToBytes)(e.DER.hexFromSig(this));const k=N.toBytes(this.r),p=N.toBytes(this.s);if(re==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return(0,r.concatBytes)(Uint8Array.of(this.recovery),k,p)}return(0,r.concatBytes)(k,p)}toHex(re){return(0,r.bytesToHex)(this.toBytes(re))}assertValidity(){}static fromCompact(re){return le.fromBytes((0,r.ensureBytes)("sig",re),"compact")}static fromDER(re){return le.fromBytes((0,r.ensureBytes)("sig",re),"der")}normalizeS(){return this.hasHighS()?new le(this.r,N.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return(0,r.bytesToHex)(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return(0,r.bytesToHex)(this.toBytes("compact"))}}const Ae=F.bits2int||function(re){if(re.length>8192)throw new Error("input is too large");const k=(0,r.bytesToNumberBE)(re),p=re.length*8-G;return p>0?k>>BigInt(p):k},qe=F.bits2int_modN||function(re){return N.create(Ae(re))},tt=(0,r.bitMask)(G);function ut(ne){return(0,r.aInRange)("num < 2^"+G,ne,l,tt),N.toBytes(ne)}function It(ne,re){return(0,r._abytes2)(ne,void 0,"message"),re?(0,r._abytes2)(D(ne),void 0,"prehashed message"):ne}function Oe(ne,re,k){if(["recovered","canonical"].some(fe=>fe in k))throw new Error("sign() legacy options not supported");const{lowS:p,prehash:h,extraEntropy:b}=u(k,Z);ne=It(ne,h);const I=qe(ne),C=E(N,re),j=[ut(C),ut(I)];if(b!=null&&b!==!1){const fe=b===!0?x(te.secretKey):b;j.push((0,r.ensureBytes)("extraEntropy",fe))}const W=(0,r.concatBytes)(...j),ie=I;function Q(fe){const he=Ae(fe);if(!N.isValidNot0(he))return;const Ne=N.inv(he),Pe=P.BASE.multiply(he).toAffine(),nt=N.create(Pe.x);if(nt===l)return;const je=N.create(Ne*N.create(ie+nt*C));if(je===l)return;let Xn=(Pe.x===nt?0:2)|Number(Pe.y&d),Ch=je;return p&&we(je)&&(Ch=N.neg(je),Xn^=1),new le(nt,Ch,Xn)}return{seed:W,k2sig:Q}}function mn(ne,re,k={}){ne=(0,r.ensureBytes)("message",ne);const{seed:p,k2sig:h}=Oe(ne,re,k);return(0,r.createHmacDrbg)(D.outputLen,N.BYTES,B)(p,h)}function it(ne){let re;const k=typeof ne=="string"||(0,r.isBytes)(ne),p=!k&&ne!==null&&typeof ne=="object"&&typeof ne.r=="bigint"&&typeof ne.s=="bigint";if(!k&&!p)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(p)re=new le(ne.r,ne.s);else if(k){try{re=le.fromBytes((0,r.ensureBytes)("sig",ne),"der")}catch(h){if(!(h instanceof e.DER.Err))throw h}if(!re)try{re=le.fromBytes((0,r.ensureBytes)("sig",ne),"compact")}catch{return!1}}return re||!1}function Ce(ne,re,k,p={}){const{lowS:h,prehash:b,format:I}=u(p,Z);if(k=(0,r.ensureBytes)("publicKey",k),re=It((0,r.ensureBytes)("message",re),b),"strict"in p)throw new Error("options.strict was renamed to lowS");const C=I===void 0?it(ne):le.fromBytes((0,r.ensureBytes)("sig",ne),I);if(C===!1)return!1;try{const j=P.fromBytes(k);if(h&&C.hasHighS())return!1;const{r:W,s:ie}=C,Q=qe(re),fe=N.inv(ie),he=N.create(Q*fe),Ne=N.create(W*fe),Pe=P.BASE.multiplyUnsafe(he).add(j.multiplyUnsafe(Ne));return Pe.is0()?!1:N.create(Pe.x)===W}catch{return!1}}function oe(ne,re,k={}){const{prehash:p}=u(k,Z);return re=It(re,p),le.fromBytes(ne,"recovered").recoverPublicKey(re).toBytes()}return Object.freeze({keygen:X,getPublicKey:Y,getSharedSecret:ce,utils:ue,lengths:te,Point:P,sign:mn,verify:Ce,recoverPublicKey:oe,Signature:le,hash:D})}function M(P){const{CURVE:D,curveOpts:F}=v(P),x=_(D,F);return K(P,x)}function v(P){const D={a:P.a,b:P.b,p:P.Fp.ORDER,n:P.n,h:P.h,Gx:P.Gx,Gy:P.Gy},F=P.Fp;let x=P.allowedPrivateKeyLengths?Array.from(new Set(P.allowedPrivateKeyLengths.map(N=>Math.ceil(N/2)))):void 0;const B=(0,s.Field)(D.n,{BITS:P.nBitLength,allowedLengths:x,modFromBytes:P.wrapPrivateKey}),q={Fp:F,Fn:B,allowInfinityPoint:P.allowInfinityPoint,endo:P.endo,isTorsionFree:P.isTorsionFree,clearCofactor:P.clearCofactor,fromBytes:P.fromBytes,toBytes:P.toBytes};return{CURVE:D,curveOpts:q}}function U(P){const{CURVE:D,curveOpts:F}=v(P),x={hmac:P.hmac,randomBytes:P.randomBytes,lowS:P.lowS,bits2int:P.bits2int,bits2int_modN:P.bits2int_modN};return{CURVE:D,curveOpts:F,hash:P.hash,ecdsaOpts:x}}function V(P,D,F){function x(B){const q=P.sqr(B),N=P.mul(q,B);return P.add(P.add(N,P.mul(B,D)),F)}return x}function K(P,D){const{Fp:F,Fn:x}=D;function B(N){return(0,r.inRange)(N,d,x.ORDER)}const q=V(F,P.a,P.b);return Object.assign({},{CURVE:P,Point:D,ProjectivePoint:D,normPrivateKeyToScalar:N=>E(x,N),weierstrassEquation:q,isWithinCurveOrder:B})}function H(P,D){const F=D.Point;return Object.assign({},D,{ProjectivePoint:F,CURVE:Object.assign({},P,(0,s.nLength)(F.Fn.ORDER,F.Fn.BITS))})}function $(P){const{CURVE:D,curveOpts:F,hash:x,ecdsaOpts:B}=U(P),q=_(D,F),N=R(q,x,B);return H(P,N)}})(Nu)),Nu}var Qh;function H1(){if(Qh)return Zs;Qh=1,Object.defineProperty(Zs,"__esModule",{value:!0}),Zs.getHash=t,Zs.createCurve=n;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const e=Cy();function t(r){return{hash:r}}function n(r,i){const s=o=>(0,e.weierstrass)({...r,hash:o});return{...s(i),create:s}}return Zs}var Ru={},ed;function F1(){return ed||(ed=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e._DST_scalar=void 0,e.expand_message_xmd=a,e.expand_message_xof=u,e.hash_to_field=f,e.isogenyMap=l,e.createHasher=d;const t=Ms(),n=nc(),r=t.bytesToNumberBE;function i(y,g){if(o(y),o(g),y<0||y>=1<<8*g)throw new Error("invalid I2OSP input: "+y);const m=Array.from({length:g}).fill(0);for(let E=g-1;E>=0;E--)m[E]=y&255,y>>>=8;return new Uint8Array(m)}function s(y,g){const m=new Uint8Array(y.length);for(let E=0;E<y.length;E++)m[E]=y[E]^g[E];return m}function o(y){if(!Number.isSafeInteger(y))throw new Error("number expected")}function c(y){if(!(0,t.isBytes)(y)&&typeof y!="string")throw new Error("DST must be Uint8Array or string");return typeof y=="string"?(0,t.utf8ToBytes)(y):y}function a(y,g,m,E){(0,t.abytes)(y),o(m),g=c(g),g.length>255&&(g=E((0,t.concatBytes)((0,t.utf8ToBytes)("H2C-OVERSIZE-DST-"),g)));const{outputLen:_,blockLen:S}=E,w=Math.ceil(m/_);if(m>65535||w>255)throw new Error("expand_message_xmd: invalid lenInBytes");const T=(0,t.concatBytes)(g,i(g.length,1)),O=i(0,S),A=i(m,2),R=new Array(w),M=E((0,t.concatBytes)(O,y,A,i(0,1),T));R[0]=E((0,t.concatBytes)(M,i(1,1),T));for(let U=1;U<=w;U++){const V=[s(M,R[U-1]),i(U+1,1),T];R[U]=E((0,t.concatBytes)(...V))}return(0,t.concatBytes)(...R).slice(0,m)}function u(y,g,m,E,_){if((0,t.abytes)(y),o(m),g=c(g),g.length>255){const S=Math.ceil(2*E/8);g=_.create({dkLen:S}).update((0,t.utf8ToBytes)("H2C-OVERSIZE-DST-")).update(g).digest()}if(m>65535||g.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return _.create({dkLen:m}).update(y).update(i(m,2)).update(g).update(i(g.length,1)).digest()}function f(y,g,m){(0,t._validateObject)(m,{p:"bigint",m:"number",k:"number",hash:"function"});const{p:E,k:_,m:S,hash:w,expand:T,DST:O}=m;if(!(0,t.isHash)(m.hash))throw new Error("expected valid hash");(0,t.abytes)(y),o(g);const A=E.toString(2).length,R=Math.ceil((A+_)/8),M=g*S*R;let v;if(T==="xmd")v=a(y,O,M,w);else if(T==="xof")v=u(y,O,M,_,w);else if(T==="_internal_pass")v=y;else throw new Error('expand must be "xmd" or "xof"');const U=new Array(g);for(let V=0;V<g;V++){const K=new Array(S);for(let H=0;H<S;H++){const $=R*(H+V*S),P=v.subarray($,$+R);K[H]=(0,n.mod)(r(P),E)}U[V]=K}return U}function l(y,g){const m=g.map(E=>Array.from(E).reverse());return(E,_)=>{const[S,w,T,O]=m.map(M=>M.reduce((v,U)=>y.add(y.mul(v,E),U))),[A,R]=(0,n.FpInvertBatch)(y,[w,O],!0);return E=y.mul(S,A),_=y.mul(_,y.mul(T,R)),{x:E,y:_}}}e._DST_scalar=(0,t.utf8ToBytes)("HashToScalar-");function d(y,g,m){if(typeof g!="function")throw new Error("mapToCurve() must be defined");function E(S){return y.fromAffine(g(S))}function _(S){const w=S.clearCofactor();return w.equals(y.ZERO)?y.ZERO:(w.assertValidity(),w)}return{defaults:m,hashToCurve(S,w){const T=Object.assign({},m,w),O=f(S,2,T),A=E(O[0]),R=E(O[1]);return _(A.add(R))},encodeToCurve(S,w){const T=m.encodeDST?{DST:m.encodeDST}:{},O=Object.assign({},m,T,w),A=f(S,1,O),R=E(A[0]);return _(R)},mapToCurve(S){if(!Array.isArray(S))throw new Error("expected array of bigints");for(const w of S)if(typeof w!="bigint")throw new Error("expected array of bigints");return _(E(S))},hashToScalar(S,w){const T=y.Fn.ORDER,O=Object.assign({},m,{p:T,m:1,DST:e._DST_scalar},w);return f(S,1,O)[0][0]}}}})(Ru)),Ru}var td;function M1(){return td||(td=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.encodeToCurve=e.hashToCurve=e.secp256k1_hasher=e.schnorr=e.secp256k1=void 0;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=Uy(),n=ui(),r=H1(),i=F1(),s=nc(),o=Cy(),c=Ms(),a={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},u={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},f=BigInt(0),l=BigInt(1),d=BigInt(2);function y(H){const $=a.p,P=BigInt(3),D=BigInt(6),F=BigInt(11),x=BigInt(22),B=BigInt(23),q=BigInt(44),N=BigInt(88),L=H*H*H%$,G=L*L*H%$,X=(0,s.pow2)(G,P,$)*G%$,Y=(0,s.pow2)(X,P,$)*G%$,ce=(0,s.pow2)(Y,d,$)*L%$,ue=(0,s.pow2)(ce,F,$)*ce%$,te=(0,s.pow2)(ue,x,$)*ue%$,Z=(0,s.pow2)(te,q,$)*te%$,ae=(0,s.pow2)(Z,N,$)*Z%$,we=(0,s.pow2)(ae,q,$)*te%$,ye=(0,s.pow2)(we,P,$)*G%$,J=(0,s.pow2)(ye,B,$)*ue%$,le=(0,s.pow2)(J,D,$)*L%$,Ae=(0,s.pow2)(le,d,$);if(!g.eql(g.sqr(Ae),H))throw new Error("Cannot find square root");return Ae}const g=(0,s.Field)(a.p,{sqrt:y});e.secp256k1=(0,r.createCurve)({...a,Fp:g,lowS:!0,endo:u},t.sha256);const m={};function E(H,...$){let P=m[H];if(P===void 0){const D=(0,t.sha256)((0,c.utf8ToBytes)(H));P=(0,c.concatBytes)(D,D),m[H]=P}return(0,t.sha256)((0,c.concatBytes)(P,...$))}const _=H=>H.toBytes(!0).slice(1),S=e.secp256k1.Point,w=H=>H%d===f;function T(H){const{Fn:$,BASE:P}=S,D=(0,o._normFnElement)($,H),F=P.multiply(D);return{scalar:w(F.y)?D:$.neg(D),bytes:_(F)}}function O(H){const $=g;if(!$.isValidNot0(H))throw new Error("invalid x: Fail if x ≥ p");const P=$.create(H*H),D=$.create(P*H+BigInt(7));let F=$.sqrt(D);w(F)||(F=$.neg(F));const x=S.fromAffine({x:H,y:F});return x.assertValidity(),x}const A=c.bytesToNumberBE;function R(...H){return S.Fn.create(A(E("BIP0340/challenge",...H)))}function M(H){return T(H).bytes}function v(H,$,P=(0,n.randomBytes)(32)){const{Fn:D}=S,F=(0,c.ensureBytes)("message",H),{bytes:x,scalar:B}=T($),q=(0,c.ensureBytes)("auxRand",P,32),N=D.toBytes(B^A(E("BIP0340/aux",q))),L=E("BIP0340/nonce",N,x,F),{bytes:G,scalar:X}=T(L),Y=R(G,x,F),ce=new Uint8Array(64);if(ce.set(G,0),ce.set(D.toBytes(D.create(X+Y*B)),32),!U(ce,F,x))throw new Error("sign: Invalid signature produced");return ce}function U(H,$,P){const{Fn:D,BASE:F}=S,x=(0,c.ensureBytes)("signature",H,64),B=(0,c.ensureBytes)("message",$),q=(0,c.ensureBytes)("publicKey",P,32);try{const N=O(A(q)),L=A(x.subarray(0,32));if(!(0,c.inRange)(L,l,a.p))return!1;const G=A(x.subarray(32,64));if(!(0,c.inRange)(G,l,a.n))return!1;const X=R(D.toBytes(L),_(N),B),Y=F.multiplyUnsafe(G).add(N.multiplyUnsafe(D.neg(X))),{x:ce,y:ue}=Y.toAffine();return!(Y.is0()||!w(ue)||ce!==L)}catch{return!1}}e.schnorr=(()=>{const P=(F=(0,n.randomBytes)(48))=>(0,s.mapHashToField)(F,a.n);e.secp256k1.utils.randomSecretKey;function D(F){const x=P(F);return{secretKey:x,publicKey:M(x)}}return{keygen:D,getPublicKey:M,sign:v,verify:U,Point:S,utils:{randomSecretKey:P,randomPrivateKey:P,taggedHash:E,lift_x:O,pointToBytes:_,numberToBytesBE:c.numberToBytesBE,bytesToNumberBE:c.bytesToNumberBE,mod:s.mod},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();const V=(0,i.isogenyMap)(g,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(H=>H.map($=>BigInt($)))),K=(0,o.mapToCurveSimpleSWU)(g,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:g.create(BigInt("-11"))});e.secp256k1_hasher=(0,i.createHasher)(e.secp256k1.Point,H=>{const{x:$,y:P}=K(g.create(H[0]));return V($,P)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:g.ORDER,m:1,k:128,expand:"xmd",hash:t.sha256}),e.hashToCurve=e.secp256k1_hasher.hashToCurve,e.encodeToCurve=e.secp256k1_hasher.encodeToCurve})(Ou)),Ou}var pe={},nd;function q1(){if(nd)return pe;nd=1,Object.defineProperty(pe,"__esModule",{value:!0}),pe.isHash=pe.validateObject=pe.memoized=pe.notImplemented=pe.createHmacDrbg=pe.bitMask=pe.bitSet=pe.bitGet=pe.bitLen=pe.aInRange=pe.inRange=pe.asciiToBytes=pe.copyBytes=pe.equalBytes=pe.ensureBytes=pe.numberToVarBytesBE=pe.numberToBytesLE=pe.numberToBytesBE=pe.bytesToNumberLE=pe.bytesToNumberBE=pe.hexToNumber=pe.numberToHexUnpadded=pe.abool=pe.utf8ToBytes=pe.randomBytes=pe.isBytes=pe.hexToBytes=pe.concatBytes=pe.bytesToUtf8=pe.bytesToHex=pe.anumber=pe.abytes=void 0;const e=Ms();return pe.abytes=e.abytes,pe.anumber=e.anumber,pe.bytesToHex=e.bytesToHex,pe.bytesToUtf8=e.bytesToUtf8,pe.concatBytes=e.concatBytes,pe.hexToBytes=e.hexToBytes,pe.isBytes=e.isBytes,pe.randomBytes=e.randomBytes,pe.utf8ToBytes=e.utf8ToBytes,pe.abool=e.abool,pe.numberToHexUnpadded=e.numberToHexUnpadded,pe.hexToNumber=e.hexToNumber,pe.bytesToNumberBE=e.bytesToNumberBE,pe.bytesToNumberLE=e.bytesToNumberLE,pe.numberToBytesBE=e.numberToBytesBE,pe.numberToBytesLE=e.numberToBytesLE,pe.numberToVarBytesBE=e.numberToVarBytesBE,pe.ensureBytes=e.ensureBytes,pe.equalBytes=e.equalBytes,pe.copyBytes=e.copyBytes,pe.asciiToBytes=e.asciiToBytes,pe.inRange=e.inRange,pe.aInRange=e.aInRange,pe.bitLen=e.bitLen,pe.bitGet=e.bitGet,pe.bitSet=e.bitSet,pe.bitMask=e.bitMask,pe.createHmacDrbg=e.createHmacDrbg,pe.notImplemented=e.notImplemented,pe.memoized=e.memoized,pe.validateObject=e.validateObject,pe.isHash=e.isHash,pe}var rd;function V1(){if(rd)return st;rd=1;var e=M1(),t=nc(),n=q1();function r(p){var h=Object.create(null);return p&&Object.keys(p).forEach(function(b){if(b!=="default"){var I=Object.getOwnPropertyDescriptor(p,b);Object.defineProperty(h,b,I.get?I:{enumerable:!0,get:function(){return p[b]}})}}),h.default=p,Object.freeze(h)}var i=r(t),s=r(n);const o=e.secp256k1.ProjectivePoint,c="Expected Private",a="Expected Point",u="Expected Tweak",f="Expected Hash",l="Expected Signature",d="Expected Extra Data (32 bytes)",y="Expected Scalar",g="Bad Recovery Id",m=32,E=32,_=new Uint8Array([255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,254,186,174,220,230,175,72,160,59,191,210,94,140,208,54,65,65]),S=32,w=new Uint8Array(32),T=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,69,81,35,25,80,183,95,196,64,45,161,114,47,201,186,238]),O=BigInt(1);function A(p){return p instanceof Uint8Array}function R(p,h){for(let b=0;b<32;++b)if(p[b]!==h[b])return p[b]<h[b]?-1:1;return 0}function M(p){return R(p,w)===0}function v(p){return!(!(p instanceof Uint8Array)||p.length!==E||R(p,_)>=0)}function U(p){return p instanceof Uint8Array&&p.length===64&&R(p.subarray(0,32),_)<0&&R(p.subarray(32,64),_)<0}function V(p){return A(p)&&p.length===64&&R(p.subarray(0,32),T)<0}function K(p){return!(M(p.subarray(0,32))||M(p.subarray(32,64)))}function H(p){return p instanceof Uint8Array&&p.length===m}function $(p){return p===void 0||p instanceof Uint8Array&&p.length===S}function P(p){let h;if(typeof p=="bigint")h=p;else if(typeof p=="number"&&Number.isSafeInteger(p)&&p>=0)h=BigInt(p);else if(typeof p=="string"){if(p.length!==64)throw new Error("Expected 32 bytes of private scalar");h=s.hexToNumber(p)}else if(p instanceof Uint8Array){if(p.length!==32)throw new Error("Expected 32 bytes of private scalar");h=s.bytesToNumberBE(p)}else throw new TypeError("Expected valid private scalar");if(h<0)throw new Error("Expected private scalar >= 0");return h}function D(p){return e.secp256k1.utils.normPrivateKeyToScalar(p)}function F(p,h){const b=D(p),I=P(h),C=s.numberToBytesBE(i.mod(b+I,e.secp256k1.CURVE.n),32);return e.secp256k1.utils.isValidPrivateKey(C)?C:null}function x(p,h){const b=D(p),I=P(h),C=s.numberToBytesBE(i.mod(b-I,e.secp256k1.CURVE.n),32);return e.secp256k1.utils.isValidPrivateKey(C)?C:null}function B(p){const h=D(p),b=s.numberToBytesBE(e.secp256k1.CURVE.n-h,32);return e.secp256k1.utils.isValidPrivateKey(b)?b:null}function q(p,h,b){const I=Y(p),C=P(h),j=o.BASE.multiplyAndAddUnsafe(I,C,O);if(!j)throw new Error("Tweaked point at infinity");return j.toRawBytes(b)}function N(p,h,b){const I=Y(p),C=typeof h=="string"?h:s.bytesToHex(h),j=s.hexToNumber(C);return I.multiply(j).toRawBytes(b)}function L(p,h){return p===void 0?h!==void 0?te(h):!0:!!p}function G(p){try{return p()}catch{return null}}function X(p){return e.schnorr.utils.lift_x(s.bytesToNumberBE(p))}function Y(p){return p.length===32?X(p):o.fromHex(p)}function ce(p,h){if(p.length===32!==h)return!1;try{return h?!!X(p):!!o.fromHex(p)}catch{return!1}}function ue(p){return ce(p,!1)}function te(p){return ce(p,!1)&&p.length===33}function Z(p){return e.secp256k1.utils.isValidPrivateKey(p)}function ae(p){return ce(p,!0)}function we(p,h){if(!ae(p))throw new Error(a);if(!v(h))throw new Error(u);return G(()=>{const b=q(p,h,!0);return{parity:b[0]%2===1?1:0,xOnlyPubkey:b.slice(1)}})}function ye(p){if(!ue(p))throw new Error(a);return p.slice(1,33)}function J(p,h){if(!Z(p))throw new Error(c);return G(()=>e.secp256k1.getPublicKey(p,L(h)))}function le(p){if(!Z(p))throw new Error(c);return ye(J(p))}function Ae(p,h){if(!ue(p))throw new Error(a);return Y(p).toRawBytes(L(h,p))}function qe(p,h,b){if(!ue(p))throw new Error(a);if(!v(h))throw new Error(u);return G(()=>N(p,h,L(b,p)))}function tt(p,h,b){if(!ue(p)||!ue(h))throw new Error(a);return G(()=>{const I=Y(p),C=Y(h);return I.equals(C.negate())?null:I.add(C).toRawBytes(L(b,p))})}function ut(p,h,b){if(!ue(p))throw new Error(a);if(!v(h))throw new Error(u);return G(()=>q(p,h,L(b,p)))}function It(p,h){if(!Z(p))throw new Error(c);if(!v(h))throw new Error(u);return G(()=>F(p,h))}function Oe(p,h){if(!Z(p))throw new Error(c);if(!v(h))throw new Error(u);return G(()=>x(p,h))}function mn(p){if(!Z(p))throw new Error(c);return B(p)}function it(p,h,b){if(!Z(h))throw new Error(c);if(!H(p))throw new Error(y);if(!$(b))throw new Error(d);return e.secp256k1.sign(p,h,{extraEntropy:b}).toCompactRawBytes()}function Ce(p,h,b){if(!Z(h))throw new Error(c);if(!H(p))throw new Error(y);if(!$(b))throw new Error(d);const I=e.secp256k1.sign(p,h,{extraEntropy:b});return{signature:I.toCompactRawBytes(),recoveryId:I.recovery}}function oe(p,h,b){if(!Z(h))throw new Error(c);if(!H(p))throw new Error(y);if(!$(b))throw new Error(d);return e.schnorr.sign(p,h,b)}function ne(p,h,b,I){if(!H(p))throw new Error(f);if(!U(h)||!K(h))throw new Error(l);if(b&2&&!V(h))throw new Error(g);if(!ae(h.subarray(0,32)))throw new Error(l);const j=e.secp256k1.Signature.fromCompact(h).addRecoveryBit(b).recoverPublicKey(p);if(!j)throw new Error(l);return j.toRawBytes(L(I))}function re(p,h,b,I){if(!ue(h))throw new Error(a);if(!U(b))throw new Error(l);if(!H(p))throw new Error(y);return e.secp256k1.verify(b,p,h,{lowS:I})}function k(p,h,b){if(!ae(h))throw new Error(a);if(!U(b))throw new Error(l);if(!H(p))throw new Error(y);return e.schnorr.verify(b,p,h)}return st.isPoint=ue,st.isPointCompressed=te,st.isPrivate=Z,st.isXOnlyPoint=ae,st.pointAdd=tt,st.pointAddScalar=ut,st.pointCompress=Ae,st.pointFromScalar=J,st.pointMultiply=qe,st.privateAdd=It,st.privateNegate=mn,st.privateSub=Oe,st.recover=ne,st.sign=it,st.signRecoverable=Ce,st.signSchnorr=oe,st.verify=re,st.verifySchnorr=k,st.xOnlyPointAddTweak=we,st.xOnlyPointFromPoint=ye,st.xOnlyPointFromScalar=le,st}var Hy=V1();const L1=Py(Hy),$1=A1({__proto__:null,default:L1},[Hy]),Pn={messagePrefix:`Bitcoin Signed Message:
7
7
  `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},D1={messagePrefix:`Bitcoin Signed Message:
8
8
  `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},Fy={messagePrefix:`Bitcoin Signed Message:
9
- `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};function j1(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 n=e[5+t];return!(n===0||6+t+n!==e.length||e[4]&128||t>1&&e[4]===0&&!(e[5]&128)||e[t+6]&128||n>1&&e[t+6]===0&&!(e[t+7]&128))}function K1(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 n=e[5+t];if(n===0)throw new Error("S length is zero");if(6+t+n!==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(n>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)}}function G1(e,t){const n=e.length,r=t.length;if(n===0)throw new Error("R length is zero");if(r===0)throw new Error("S length is zero");if(n>33)throw new Error("R length is too long");if(r>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(n>1&&e[0]===0&&!(e[1]&128))throw new Error("R value excessively padded");if(r>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");const i=new Uint8Array(6+n+r);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=e.length,i.set(e,4),i[4+n]=2,i[5+n]=t.length,i.set(t,6+n),i}const Ge={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},My={};for(const e of Object.keys(Ge)){const t=Ge[e];My[t]=e}const aa="0123456789abcdefABCDEF",ua=aa.split("").map(e=>e.codePointAt(0)),fa=Array(256).fill(!0).map((e,t)=>{const n=String.fromCodePoint(t),r=aa.indexOf(n);return r<0?void 0:r<16?r:r-6}),qy=new TextEncoder,Vy=new TextDecoder;function W1(e){return Vy.decode(e)}function X1(e){return qy.encode(e)}function at(e){const t=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(t);let r=0;for(const i of e)n.set(i,r),r+=i.length;return n}function xe(e){const t=e||new Uint8Array;return t.length>512?Y1(t):z1(t)}function z1(e){let t="";for(let n=0;n<e.length;++n)t+=aa[fa[ua[e[n]>>4]]],t+=aa[fa[ua[e[n]&15]]];return t}function Y1(e){const t=new Uint8Array(e.length*2);for(let n=0;n<e.length;++n)t[n*2]=ua[e[n]>>4],t[n*2+1]=ua[e[n]&15];return Vy.decode(t)}function kr(e){const t=qy.encode(e||""),n=new Uint8Array(Math.floor(t.length/2));let r;for(r=0;r<n.length;r++){const i=fa[t[r*2]],s=fa[t[r*2+1]];if(i===void 0||s===void 0)break;n[r]=i<<4|s}return r===n.length?n:n.slice(0,r)}function Z1(e){return btoa(String.fromCharCode(...e))}function Ly(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function de(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;++r)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return e.length===t.length?0:e.length>t.length?1:-1}function bn(e,t,n){if(t+1>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n>255)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= 255. Received ${n}`);return e[t]=n,t+1}function J1(e,t,n,r){if(t+2>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>65535)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= 65535. Received ${n}`);return r==="LE"?(e[t]=n&255,e[t+1]=n>>8&255):(e[t]=n>>8&255,e[t+1]=n&255),t+2}function rc(e,t,n,r){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>4294967295)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${4294967295}. Received ${n}`);return r==="LE"?(e[t]=n&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255):(e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255),t+4}function Q1(e,t,n,r){if(t+8>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>0xffffffffffffffffn)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${n}`);return r==="LE"?(e[t]=Number(n&0xffn),e[t+1]=Number(n>>8n&0xffn),e[t+2]=Number(n>>16n&0xffn),e[t+3]=Number(n>>24n&0xffn),e[t+4]=Number(n>>32n&0xffn),e[t+5]=Number(n>>40n&0xffn),e[t+6]=Number(n>>48n&0xffn),e[t+7]=Number(n>>56n&0xffn)):(e[t]=Number(n>>56n&0xffn),e[t+1]=Number(n>>48n&0xffn),e[t+2]=Number(n>>40n&0xffn),e[t+3]=Number(n>>32n&0xffn),e[t+4]=Number(n>>24n&0xffn),e[t+5]=Number(n>>16n&0xffn),e[t+6]=Number(n>>8n&0xffn),e[t+7]=Number(n&0xffn)),t+8}function vr(e,t){if(t+1>e.length)throw new Error("Offset is outside the bounds of Uint8Array");return e[t]}function eb(e,t,n){if(t+2>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){let r=0;return r=(r<<8)+e[t+1],r=(r<<8)+e[t],r}else{let r=0;return r=(r<<8)+e[t],r=(r<<8)+e[t+1],r}}function qs(e,t,n){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){let r=0;return r=(r<<8)+e[t+3]>>>0,r=(r<<8)+e[t+2]>>>0,r=(r<<8)+e[t+1]>>>0,r=(r<<8)+e[t]>>>0,r}else{let r=0;return r=(r<<8)+e[t]>>>0,r=(r<<8)+e[t+1]>>>0,r=(r<<8)+e[t+2]>>>0,r=(r<<8)+e[t+3]>>>0,r}}function $y(e,t,n,r){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n>2147483647||n<-2147483648)throw new Error(`The value of "value" is out of range. It must be >= -2147483648 and <= 2147483647. Received ${n}`);return r=r.toUpperCase(),r==="LE"?(e[t]=n&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255):(e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255),t+4}function Dy(e,t,n,r){if(t+8>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n>0x7fffffffffffffffn||n<-0x8000000000000000n)throw new Error(`The value of "value" is out of range. It must be >= ${-0x8000000000000000n} and <= ${0x7fffffffffffffffn}. Received ${n}`);return r=r.toUpperCase(),r==="LE"?(e[t]=Number(n&0xffn),e[t+1]=Number(n>>8n&0xffn),e[t+2]=Number(n>>16n&0xffn),e[t+3]=Number(n>>24n&0xffn),e[t+4]=Number(n>>32n&0xffn),e[t+5]=Number(n>>40n&0xffn),e[t+6]=Number(n>>48n&0xffn),e[t+7]=Number(n>>56n&0xffn)):(e[t]=Number(n>>56n&0xffn),e[t+1]=Number(n>>48n&0xffn),e[t+2]=Number(n>>40n&0xffn),e[t+3]=Number(n>>32n&0xffn),e[t+4]=Number(n>>24n&0xffn),e[t+5]=Number(n>>16n&0xffn),e[t+6]=Number(n>>8n&0xffn),e[t+7]=Number(n&0xffn)),t+8}function tb(e,t,n){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){const r=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0);return e[t+3]<=127?r:r-4294967296}else{const r=(e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];return e[t]<=127?r:r-4294967296}}function jy(e,t,n){if(t+8>e.length)throw new Error("Offset is outside the bounds of Uint8Array");n=n.toUpperCase();let r=0n;if(n==="LE")return r=(r<<8n)+BigInt(e[t+7]),r=(r<<8n)+BigInt(e[t+6]),r=(r<<8n)+BigInt(e[t+5]),r=(r<<8n)+BigInt(e[t+4]),r=(r<<8n)+BigInt(e[t+3]),r=(r<<8n)+BigInt(e[t+2]),r=(r<<8n)+BigInt(e[t+1]),r=(r<<8n)+BigInt(e[t]),e[t+7]<=127?r:r-0x10000000000000000n;{let i=0n;return i=(i<<8n)+BigInt(e[t]),i=(i<<8n)+BigInt(e[t+1]),i=(i<<8n)+BigInt(e[t+2]),i=(i<<8n)+BigInt(e[t+3]),i=(i<<8n)+BigInt(e[t+4]),i=(i<<8n)+BigInt(e[t+5]),i=(i<<8n)+BigInt(e[t+6]),i=(i<<8n)+BigInt(e[t+7]),e[t]<=127?i:i-0x10000000000000000n}}function Ky(e){return e<Ge.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}function nb(e,t,n){const r=Ky(t);return r===1?bn(e,n,t):r===2?(bn(e,n,Ge.OP_PUSHDATA1),bn(e,n+1,t)):r===3?(bn(e,n,Ge.OP_PUSHDATA2),J1(e,n+1,t,"LE")):(bn(e,n,Ge.OP_PUSHDATA4),rc(e,n+1,t,"LE")),r}function rb(e,t){const n=vr(e,t);let r,i;if(n<Ge.OP_PUSHDATA1)r=n,i=1;else if(n===Ge.OP_PUSHDATA1){if(t+2>e.length)return null;r=vr(e,t+1),i=2}else if(n===Ge.OP_PUSHDATA2){if(t+3>e.length)return null;r=eb(e,t+1,"LE"),i=3}else{if(t+5>e.length)return null;if(n!==Ge.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=qs(e,t+1,"LE"),i=5}return{opcode:n,number:r,size:i}}function ib(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function sb(e){let t=Math.abs(e);const n=ib(t),r=new Uint8Array(n),i=e<0;for(let s=0;s<n;++s)bn(r,s,t&255),t>>=8;return r[n-1]&128?bn(r,n-1,i?128:0):i&&(r[n-1]|=128),r}var Uu;function ob(e){return{lang:e?.lang??Uu?.lang,message:e?.message,abortEarly:e?.abortEarly??Uu?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Uu?.abortPipeEarly}}var cb;function ab(e){return cb?.get(e)}var ub;function fb(e){return ub?.get(e)}var lb;function hb(e,t){return lb?.get(e)?.get(t)}function vo(e){const t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function Gt(e,t,n,r,i){const s=i&&"input"in i?i.input:n.value,o=i?.expected??e.expects??null,c=i?.received??vo(s),a={kind:e.kind,type:e.type,input:s,expected:o,received:c,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${c}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},u=e.kind==="schema",f=i?.message??e.message??hb(e.reference,a.lang)??(u?fb(a.lang):null)??r.message??ab(a.lang);f&&(a.message=typeof f=="function"?f(a):f),u&&(n.typed=!1),n.issues?n.issues.push(a):n.issues=[a]}function db(e,t){const n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}var pb=class extends Error{issues;constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function Gy(e,t){return{kind:"validation",type:"every_item",reference:Gy,async:!1,expects:null,requirement:e,message:t,_run(n,r){return n.typed&&!n.value.every(this.requirement)&&Gt(this,"item",n,r),n}}}function Tl(e){return{kind:"validation",type:"integer",reference:Tl,async:!1,expects:null,requirement:Number.isInteger,message:e,_run(t,n){return t.typed&&!this.requirement(t.value)&&Gt(this,"integer",t,n),t}}}function Wy(e,t){return{kind:"validation",type:"length",reference:Wy,async:!1,expects:`${e}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value.length!==this.requirement&&Gt(this,"length",n,r,{received:`${n.value.length}`}),n}}}function $a(e,t){return{kind:"validation",type:"max_value",reference:$a,async:!1,expects:`<=${e instanceof Date?e.toJSON():vo(e)}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value>this.requirement&&Gt(this,"value",n,r,{received:n.value instanceof Date?n.value.toJSON():vo(n.value)}),n}}}function Da(e,t){return{kind:"validation",type:"min_value",reference:Da,async:!1,expects:`>=${e instanceof Date?e.toJSON():vo(e)}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value<this.requirement&&Gt(this,"value",n,r,{received:n.value instanceof Date?n.value.toJSON():vo(n.value)}),n}}}function Xy(e,t){return{kind:"validation",type:"regex",reference:Xy,async:!1,expects:`${e}`,requirement:e,message:t,_run(n,r){return n.typed&&!this.requirement.test(n.value)&&Gt(this,"format",n,r),n}}}function xl(e,t,n){return typeof e.default=="function"?e.default(t,n):e.default}function ja(e,t){return!e._run({typed:!1,value:t},{abortEarly:!0}).issues}function zy(){return{kind:"schema",type:"any",reference:zy,expects:"any",async:!1,_run(e){return e.typed=!0,e}}}function dn(e,t){return{kind:"schema",type:"array",reference:dn,expects:"Array",async:!1,item:e,message:t,_run(n,r){const i=n.value;if(Array.isArray(i)){n.typed=!0,n.value=[];for(let s=0;s<i.length;s++){const o=i[s],c=this.item._run({typed:!1,value:o},r);if(c.issues){const a={type:"array",origin:"value",input:i,key:s,value:o};for(const u of c.issues)u.path?u.path.unshift(a):u.path=[a],n.issues?.push(u);if(n.issues||(n.issues=c.issues),r.abortEarly){n.typed=!1;break}}c.typed||(n.typed=!1),n.value.push(c.value)}}else Gt(this,"type",n,r);return n}}}function Yy(e){return{kind:"schema",type:"bigint",reference:Yy,expects:"bigint",async:!1,message:e,_run(t,n){return typeof t.value=="bigint"?t.typed=!0:Gt(this,"type",t,n),t}}}function Kn(e,t){return{kind:"schema",type:"custom",reference:Kn,expects:"unknown",async:!1,check:e,message:t,_run(n,r){return this.check(n.value)?n.typed=!0:Gt(this,"type",n,r),n}}}function Ka(e,t){return{kind:"schema",type:"instance",reference:Ka,expects:e.name,async:!1,class:e,message:t,_run(n,r){return n.value instanceof this.class?n.typed=!0:Gt(this,"type",n,r),n}}}function Mf(e,...t){const n={kind:"schema",type:"nullable",reference:Mf,expects:`(${e.expects} | null)`,async:!1,wrapped:e,_run(r,i){return r.value===null&&("default"in this&&(r.value=xl(this,r,i)),r.value===null)?(r.typed=!0,r):this.wrapped._run(r,i)}};return 0 in t&&(n.default=t[0]),n}function Zy(e,...t){const n={kind:"schema",type:"nullish",reference:Zy,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,_run(r,i){return(r.value===null||r.value===void 0)&&("default"in this&&(r.value=xl(this,r,i)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped._run(r,i)}};return 0 in t&&(n.default=t[0]),n}function ln(e){return{kind:"schema",type:"number",reference:ln,expects:"number",async:!1,message:e,_run(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:Gt(this,"type",t,n),t}}}function Et(e,t){return{kind:"schema",type:"object",reference:Et,expects:"Object",async:!1,entries:e,message:t,_run(n,r){const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const s in this.entries){const o=i[s],c=this.entries[s]._run({typed:!1,value:o},r);if(c.issues){const a={type:"object",origin:"value",input:i,key:s,value:o};for(const u of c.issues)u.path?u.path.unshift(a):u.path=[a],n.issues?.push(u);if(n.issues||(n.issues=c.issues),r.abortEarly){n.typed=!1;break}}c.typed||(n.typed=!1),(c.value!==void 0||s in i)&&(n.value[s]=c.value)}}else Gt(this,"type",n,r);return n}}}function la(e,...t){const n={kind:"schema",type:"optional",reference:la,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,_run(r,i){return r.value===void 0&&("default"in this&&(r.value=xl(this,r,i)),r.value===void 0)?(r.typed=!0,r):this.wrapped._run(r,i)}};return 0 in t&&(n.default=t[0]),n}function zi(e){return{kind:"schema",type:"string",reference:zi,expects:"string",async:!1,message:e,_run(t,n){return typeof t.value=="string"?t.typed=!0:Gt(this,"type",t,n),t}}}function Qn(e,t){return{kind:"schema",type:"tuple",reference:Qn,expects:"Array",async:!1,items:e,message:t,_run(n,r){const i=n.value;if(Array.isArray(i)){n.typed=!0,n.value=[];for(let s=0;s<this.items.length;s++){const o=i[s],c=this.items[s]._run({typed:!1,value:o},r);if(c.issues){const a={type:"array",origin:"value",input:i,key:s,value:o};for(const u of c.issues)u.path?u.path.unshift(a):u.path=[a],n.issues?.push(u);if(n.issues||(n.issues=c.issues),r.abortEarly){n.typed=!1;break}}c.typed||(n.typed=!1),n.value.push(c.value)}}else Gt(this,"type",n,r);return n}}}function id(e){let t;if(e)for(const n of e)t?t.push(...n.issues):t=n.issues;return t}function Al(e,t){return{kind:"schema",type:"union",reference:Al,expects:db(e.map(n=>n.expects),"|"),async:!1,options:e,message:t,_run(n,r){let i,s,o;for(const c of this.options){const a=c._run({typed:!1,value:n.value},r);if(a.typed)if(a.issues)s?s.push(a):s=[a];else{i=a;break}else o?o.push(a):o=[a]}if(i)return i;if(s){if(s.length===1)return s[0];Gt(this,"type",n,r,{issues:id(s)}),n.typed=!0}else{if(o?.length===1)return o[0];Gt(this,"type",n,r,{issues:id(o)})}return n}}}function ct(e,t,n){const r=e._run({typed:!1,value:t},ob(n));if(r.issues)throw new pb(r.issues);return r.value}function fi(e,t){const n={};for(const r in e.entries)n[r]=la(e.entries[r]);return{...e,entries:n}}function Vs(...e){return{...e[0],pipe:e,_run(t,n){for(const r of e)if(r.kind!=="metadata"){if(t.issues&&(r.kind==="schema"||r.kind==="transformation")){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=r._run(t,n))}return t}}}const sd=new Uint8Array(32),od=kr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),At=e=>Vs(Ka(Uint8Array),Wy(e));function Io(e,t){return e.length!==t.length?!1:e.every((n,r)=>de(n,t[r])===0)}function Dn(e){if(!(e instanceof Uint8Array)||e.length<33)return!1;const t=e[0],n=e.slice(1,33);if(de(sd,n)===0||de(n,od)>=0)return!1;if((t===2||t===3)&&e.length===33)return!0;const r=e.slice(33);return de(sd,r)===0||de(r,od)>=0?!1:t===4&&e.length===65}const Xc=254;function vl(e){return!e||!("output"in e)||!(e.output instanceof Uint8Array)?!1:e.version!==void 0?(e.version&Xc)===e.version:!0}function Jy(e){return Array.isArray(e)?e.length!==2?!1:e.every(t=>Jy(t)):vl(e)}const yb=At(32),gb=At(20),cd=At(32),De=Ka(Uint8Array);Vs(zi(),Xy(/^([0-9a-f]{2})+$/i));const mb=Vs(ln(),Tl(),Da(0),$a(255)),yr=Vs(ln(),Tl(),Da(0),$a(4294967295)),Cu=Vs(Yy(),Da(0n),$a(0x7fffffffffffffffn)),ad=e=>Et(Object.entries(e).reduce((t,n)=>({...t,[n[0]]:Zy(n[1])}),{})),ud=new Uint8Array(1);function fd(e){let t=0;for(;e[t]===0;)++t;return t===e.length?ud:(e=e.slice(t),e[0]&128?at([ud,e]):e)}function ld(e){e[0]===0&&(e=e.slice(1));const t=new Uint8Array(32),n=Math.max(0,32-e.length);return t.set(e,n),t}function wb(e){const t=vr(e,e.length-1);if(!Ol(t))throw new Error("Invalid hashType "+t);const n=K1(e.subarray(0,-1)),r=ld(n.r),i=ld(n.s);return{signature:at([r,i]),hashType:t}}function bb(e,t){if(ct(Et({signature:At(64),hashType:mb}),{signature:e,hashType:t}),!Ol(t))throw new Error("Invalid hashType "+t);const n=new Uint8Array(1);bn(n,0,t);const r=fd(e.slice(0,32)),i=fd(e.slice(32,64));return at([G1(r,i),n])}const Eb=Object.freeze(Object.defineProperty({__proto__:null,decode:wb,encode:bb},Symbol.toStringTag,{value:"Module"})),Qy=Ge.OP_RESERVED,eg=dn(Al([Ka(Uint8Array),ln()]));function _b(e){return ja(ln(),e)&&(e===Ge.OP_0||e>=Ge.OP_1&&e<=Ge.OP_16||e===Ge.OP_1NEGATE)}function tg(e){return ja(De,e)||_b(e)}function Il(e){return ja(Vs(zy(),Gy(tg)),e)}function ng(e){return e.length-e.filter(tg).length}function ha(e){if(e.length===0)return Ge.OP_0;if(e.length===1){if(e[0]>=1&&e[0]<=16)return Qy+e[0];if(e[0]===129)return Ge.OP_1NEGATE}}function rg(e){return e instanceof Uint8Array}function Sb(e){return ja(eg,e)}function da(e){return e instanceof Uint8Array}function tn(e){if(rg(e))return e;ct(eg,e);const t=e.reduce((i,s)=>da(s)?s.length===1&&ha(s)!==void 0?i+1:i+Ky(s.length)+s.length:i+1,0),n=new Uint8Array(t);let r=0;if(e.forEach(i=>{if(da(i)){const s=ha(i);if(s!==void 0){bn(n,r,s),r+=1;return}r+=nb(n,i.length,r),n.set(i,r),r+=i.length}else bn(n,r,i),r+=1}),r!==n.length)throw new Error("Could not decode chunks");return n}function lt(e){if(Sb(e))return e;ct(De,e);const t=[];let n=0;for(;n<e.length;){const r=e[n];if(r>Ge.OP_0&&r<=Ge.OP_PUSHDATA4){const i=rb(e,n);if(i===null||(n+=i.size,n+i.number>e.length))return null;const s=e.slice(n,n+i.number);n+=i.number;const o=ha(s);o!==void 0?t.push(o):t.push(s)}else t.push(r),n+=1}return t}function Tb(e){if(rg(e)&&(e=lt(e)),!e)throw new Error("Could not convert invalid chunks to ASM");return e.map(t=>{if(da(t)){const n=ha(t);if(n===void 0)return xe(t);t=n}return My[t]}).join(" ")}function xb(e){return e=lt(e),ct(Kn(Il),e),e.map(t=>da(t)?t:t===Ge.OP_0?new Uint8Array(0):sb(t-Qy))}function Ab(e){return Dn(e)}function Ol(e){const t=e&-129;return t>0&&t<4}function Ir(e){return!(e instanceof Uint8Array)||!Ol(e[e.length-1])?!1:j1(e.slice(0,-1))}const So=Eb;function Te(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const r=n.call(this);return this[t]=r,r},set(r){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:r,writable:!0})}})}function In(e){let t;return()=>(t!==void 0||(t=e()),t)}const hs=Ge,Tc=hs.OP_RESERVED;function Ga(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 n(a){return Ir(a)||(t.allowIncomplete&&a===hs.OP_0)!==void 0}ct(fi(Et({network:Et({}),m:ln(),n:ln(),output:De,pubkeys:dn(Kn(Dn),"Received invalid pubkey"),signatures:dn(Kn(n),"Expected signature to be of type isAcceptableSignature"),input:De})),e);const i={network:e.network||Pn};let s=[],o=!1;function c(a){o||(o=!0,s=lt(a),i.m=s[0]-Tc,i.n=s[s.length-2]-Tc,i.pubkeys=s.slice(1,-2))}if(Te(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return tn([].concat(Tc+e.m,e.pubkeys,Tc+i.n,hs.OP_CHECKMULTISIG))}),Te(i,"m",()=>{if(i.output)return c(i.output),i.m}),Te(i,"n",()=>{if(i.pubkeys)return i.pubkeys.length}),Te(i,"pubkeys",()=>{if(e.output)return c(e.output),i.pubkeys}),Te(i,"signatures",()=>{if(e.input)return lt(e.input).slice(1)}),Te(i,"input",()=>{if(e.signatures)return tn([hs.OP_0].concat(e.signatures))}),Te(i,"witness",()=>{if(i.input)return[]}),Te(i,"name",()=>{if(!(!i.m||!i.n))return`p2ms(${i.m} of ${i.n})`}),t.validate){if(e.output){if(c(e.output),ct(ln(),s[0],{message:"Output is invalid"}),ct(ln(),s[s.length-2],{message:"Output is invalid"}),s[s.length-1]!==hs.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(a=>Dn(a)))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&&!Io(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]!==hs.OP_0)throw new TypeError("Input is invalid");if(i.signatures.length===0||!i.signatures.every(n))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!Io(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)}const hd=Ge;function ig(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||{}),ct(fi(Et({network:Et({}),output:De,pubkey:Kn(Dn,"invalid pubkey"),signature:Kn(Ir,"Expected signature to be of type isCanonicalScriptSignature"),input:De})),e);const n=In(()=>lt(e.input)),i={name:"p2pk",network:e.network||Pn};if(Te(i,"output",()=>{if(e.pubkey)return tn([e.pubkey,hd.OP_CHECKSIG])}),Te(i,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),Te(i,"signature",()=>{if(e.input)return n()[0]}),Te(i,"input",()=>{if(e.signature)return tn([e.signature])}),Te(i,"witness",()=>{if(i.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==hd.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!Dn(i.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&de(e.pubkey,i.pubkey)!==0)throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&de(e.input,i.input)!==0)throw new TypeError("Signature mismatch");if(e.input){if(n().length!==1)throw new TypeError("Input is invalid");if(!Ir(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}const ns=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ic(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function vb(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function On(e,...t){if(!ic(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 dd(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 Ib(e,t){On(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Li(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Hu(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function zn(e,t){return e<<32-t|e>>>t}function xc(e,t){return e<<t|e>>>32-t>>>0}const sg=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ob=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function rt(e){if(On(e),sg)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Ob[e[n]];return t}const sr={_0:48,_9:57,A:65,F:70,a:97,f:102};function pd(e){if(e>=sr._0&&e<=sr._9)return e-sr._0;if(e>=sr.A&&e<=sr.F)return e-(sr.A-10);if(e>=sr.a&&e<=sr.f)return e-(sr.a-10)}function sc(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(sg)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=pd(e.charCodeAt(s)),c=pd(e.charCodeAt(s+1));if(o===void 0||c===void 0){const a=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+s)}r[i]=o*16+c}return r}function dt(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function og(e){return typeof e=="string"&&(e=dt(e)),On(e),e}function $e(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];On(i),t+=i.length}const n=new Uint8Array(t);for(let r=0,i=0;r<e.length;r++){const s=e[r];n.set(s,i),i+=s.length}return n}class Bb{}function Wa(e){const t=r=>e().update(og(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function cg(e=32){if(ns&&typeof ns.getRandomValues=="function")return ns.getRandomValues(new Uint8Array(e));if(ns&&typeof ns.randomBytes=="function")return Uint8Array.from(ns.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Nb(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),c=Number(n&s),a=r?4:0,u=r?0:4;e.setUint32(t+a,o,r),e.setUint32(t+u,c,r)}function kb(e,t,n){return e&t^~e&n}function Pb(e,t,n){return e&t^e&n^t&n}class Bl extends Bb{constructor(t,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Hu(this.buffer)}update(t){dd(this),t=og(t),On(t);const{view:n,buffer:r,blockLen:i}=this,s=t.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const a=Hu(t);for(;i<=s-o;o+=i)this.process(a,o);continue}r.set(t.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){dd(this),Ib(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Li(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let l=o;l<i;l++)n[l]=0;Nb(r,i-8,BigInt(this.length*8),s),this.process(r,0);const c=Hu(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=a/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)c.setUint32(4*l,f[l],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:c}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=c,i%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}}const Rr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ur=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),Vt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Rb=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),ag=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Ub=ag.map(e=>(9*e+5)%16),ug=(()=>{const n=[[ag],[Ub]];for(let r=0;r<4;r++)for(let i of n)i.push(i[r].map(s=>Rb[s]));return n})(),fg=ug[0],lg=ug[1],hg=[[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=>Uint8Array.from(e)),Cb=fg.map((e,t)=>e.map(n=>hg[t][n])),Hb=lg.map((e,t)=>e.map(n=>hg[t][n])),Fb=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Mb=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function yd(e,t,n,r){return e===0?t^n^r:e===1?t&n|~t&r:e===2?(t|~n)^r:e===3?t&r|n&~r:t^(n|~r)}const Ac=new Uint32Array(16);class qb extends Bl{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:n,h2:r,h3:i,h4:s}=this;return[t,n,r,i,s]}set(t,n,r,i,s){this.h0=t|0,this.h1=n|0,this.h2=r|0,this.h3=i|0,this.h4=s|0}process(t,n){for(let y=0;y<16;y++,n+=4)Ac[y]=t.getUint32(n,!0);let r=this.h0|0,i=r,s=this.h1|0,o=s,c=this.h2|0,a=c,u=this.h3|0,f=u,l=this.h4|0,d=l;for(let y=0;y<5;y++){const g=4-y,m=Fb[y],E=Mb[y],_=fg[y],S=lg[y],w=Cb[y],T=Hb[y];for(let O=0;O<16;O++){const A=xc(r+yd(y,s,c,u)+Ac[_[O]]+m,w[O])+l|0;r=l,l=u,u=xc(c,10)|0,c=s,s=A}for(let O=0;O<16;O++){const A=xc(i+yd(g,o,a,f)+Ac[S[O]]+E,T[O])+d|0;i=d,d=f,f=xc(a,10)|0,a=o,o=A}}this.set(this.h1+c+f|0,this.h2+u+d|0,this.h3+l+i|0,this.h4+r+o|0,this.h0+s+a|0)}roundClean(){Li(Ac)}destroy(){this.destroyed=!0,Li(this.buffer),this.set(0,0,0,0,0)}}const Vb=Wa(()=>new qb),Lb=Vb,vc=BigInt(2**32-1),gd=BigInt(32);function $b(e,t=!1){return t?{h:Number(e&vc),l:Number(e>>gd&vc)}:{h:Number(e>>gd&vc)|0,l:Number(e&vc)|0}}function Db(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:c}=$b(e[s],t);[r[s],i[s]]=[o,c]}return[r,i]}const md=(e,t,n)=>e>>>n,wd=(e,t,n)=>e<<32-n|t>>>n,rs=(e,t,n)=>e>>>n|t<<32-n,is=(e,t,n)=>e<<32-n|t>>>n,Ic=(e,t,n)=>e<<64-n|t>>>n-32,Oc=(e,t,n)=>e>>>n-32|t<<64-n;function or(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}const jb=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Kb=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Gb=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Wb=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Xb=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),zb=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,Yb=Uint32Array.from([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]),Cr=new Uint32Array(64);class dg extends Bl{constructor(t=32){super(64,t,8,!1),this.A=Rr[0]|0,this.B=Rr[1]|0,this.C=Rr[2]|0,this.D=Rr[3]|0,this.E=Rr[4]|0,this.F=Rr[5]|0,this.G=Rr[6]|0,this.H=Rr[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:c,H:a}=this;return[t,n,r,i,s,o,c,a]}set(t,n,r,i,s,o,c,a){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=a|0}process(t,n){for(let l=0;l<16;l++,n+=4)Cr[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const d=Cr[l-15],y=Cr[l-2],g=zn(d,7)^zn(d,18)^d>>>3,m=zn(y,17)^zn(y,19)^y>>>10;Cr[l]=m+Cr[l-7]+g+Cr[l-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:a,G:u,H:f}=this;for(let l=0;l<64;l++){const d=zn(c,6)^zn(c,11)^zn(c,25),y=f+d+kb(c,a,u)+Yb[l]+Cr[l]|0,m=(zn(r,2)^zn(r,13)^zn(r,22))+Pb(r,i,s)|0;f=u,u=a,a=c,c=o+y|0,o=s,s=i,i=r,r=y+m|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,i,s,o,c,a,u,f)}roundClean(){Li(Cr)}destroy(){this.set(0,0,0,0,0,0,0,0),Li(this.buffer)}}class Zb extends dg{constructor(){super(28),this.A=Ur[0]|0,this.B=Ur[1]|0,this.C=Ur[2]|0,this.D=Ur[3]|0,this.E=Ur[4]|0,this.F=Ur[5]|0,this.G=Ur[6]|0,this.H=Ur[7]|0}}const pg=Db(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Jb=pg[0],Qb=pg[1],Hr=new Uint32Array(80),Fr=new Uint32Array(80);class e2 extends Bl{constructor(t=64){super(128,t,16,!1),this.Ah=Vt[0]|0,this.Al=Vt[1]|0,this.Bh=Vt[2]|0,this.Bl=Vt[3]|0,this.Ch=Vt[4]|0,this.Cl=Vt[5]|0,this.Dh=Vt[6]|0,this.Dl=Vt[7]|0,this.Eh=Vt[8]|0,this.El=Vt[9]|0,this.Fh=Vt[10]|0,this.Fl=Vt[11]|0,this.Gh=Vt[12]|0,this.Gl=Vt[13]|0,this.Hh=Vt[14]|0,this.Hl=Vt[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:c,Dl:a,Eh:u,El:f,Fh:l,Fl:d,Gh:y,Gl:g,Hh:m,Hl:E}=this;return[t,n,r,i,s,o,c,a,u,f,l,d,y,g,m,E]}set(t,n,r,i,s,o,c,a,u,f,l,d,y,g,m,E){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=c|0,this.Dl=a|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=y|0,this.Gl=g|0,this.Hh=m|0,this.Hl=E|0}process(t,n){for(let w=0;w<16;w++,n+=4)Hr[w]=t.getUint32(n),Fr[w]=t.getUint32(n+=4);for(let w=16;w<80;w++){const T=Hr[w-15]|0,O=Fr[w-15]|0,A=rs(T,O,1)^rs(T,O,8)^md(T,O,7),R=is(T,O,1)^is(T,O,8)^wd(T,O,7),M=Hr[w-2]|0,v=Fr[w-2]|0,U=rs(M,v,19)^Ic(M,v,61)^md(M,v,6),V=is(M,v,19)^Oc(M,v,61)^wd(M,v,6),K=Gb(R,V,Fr[w-7],Fr[w-16]),H=Wb(K,A,U,Hr[w-7],Hr[w-16]);Hr[w]=H|0,Fr[w]=K|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:c,Cl:a,Dh:u,Dl:f,Eh:l,El:d,Fh:y,Fl:g,Gh:m,Gl:E,Hh:_,Hl:S}=this;for(let w=0;w<80;w++){const T=rs(l,d,14)^rs(l,d,18)^Ic(l,d,41),O=is(l,d,14)^is(l,d,18)^Oc(l,d,41),A=l&y^~l&m,R=d&g^~d&E,M=Xb(S,O,R,Qb[w],Fr[w]),v=zb(M,_,T,A,Jb[w],Hr[w]),U=M|0,V=rs(r,i,28)^Ic(r,i,34)^Ic(r,i,39),K=is(r,i,28)^Oc(r,i,34)^Oc(r,i,39),H=r&s^r&c^s&c,$=i&o^i&a^o&a;_=m|0,S=E|0,m=y|0,E=g|0,y=l|0,g=d|0,{h:l,l:d}=or(u|0,f|0,v|0,U|0),u=c|0,f=a|0,c=s|0,a=o|0,s=r|0,o=i|0;const P=jb(U,K,$);r=Kb(P,v,V,H),i=P|0}({h:r,l:i}=or(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=or(this.Bh|0,this.Bl|0,s|0,o|0),{h:c,l:a}=or(this.Ch|0,this.Cl|0,c|0,a|0),{h:u,l:f}=or(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=or(this.Eh|0,this.El|0,l|0,d|0),{h:y,l:g}=or(this.Fh|0,this.Fl|0,y|0,g|0),{h:m,l:E}=or(this.Gh|0,this.Gl|0,m|0,E|0),{h:_,l:S}=or(this.Hh|0,this.Hl|0,_|0,S|0),this.set(r,i,s,o,c,a,u,f,l,d,y,g,m,E,_,S)}roundClean(){Li(Hr,Fr)}destroy(){Li(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const En=Wa(()=>new dg),t2=Wa(()=>new Zb),n2=Wa(()=>new e2),Qt=En;function Ar(e){return Lb(Qt(e))}function wi(e){return Qt(Qt(e))}const r2={"BIP0340/challenge":Uint8Array.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":Uint8Array.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":Uint8Array.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:Uint8Array.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:Uint8Array.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:Uint8Array.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:Uint8Array.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":Uint8Array.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":Uint8Array.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 Xa(e,t){return Qt(at([r2[e],t]))}function i2(e){if(e.length>=255)throw new TypeError("Alphabet too long");const t=new Uint8Array(256);for(let u=0;u<t.length;u++)t[u]=255;for(let u=0;u<e.length;u++){const f=e.charAt(u),l=f.charCodeAt(0);if(t[l]!==255)throw new TypeError(f+" is ambiguous");t[l]=u}const n=e.length,r=e.charAt(0),i=Math.log(n)/Math.log(256),s=Math.log(256)/Math.log(n);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let f=0,l=0,d=0;const y=u.length;for(;d!==y&&u[d]===0;)d++,f++;const g=(y-d)*s+1>>>0,m=new Uint8Array(g);for(;d!==y;){let S=u[d],w=0;for(let T=g-1;(S!==0||w<l)&&T!==-1;T--,w++)S+=256*m[T]>>>0,m[T]=S%n>>>0,S=S/n>>>0;if(S!==0)throw new Error("Non-zero carry");l=w,d++}let E=g-l;for(;E!==g&&m[E]===0;)E++;let _=r.repeat(f);for(;E<g;++E)_+=e.charAt(m[E]);return _}function c(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let f=0,l=0,d=0;for(;u[f]===r;)l++,f++;const y=(u.length-f)*i+1>>>0,g=new Uint8Array(y);for(;f<u.length;){const S=u.charCodeAt(f);if(S>255)return;let w=t[S];if(w===255)return;let T=0;for(let O=y-1;(w!==0||T<d)&&O!==-1;O--,T++)w+=n*g[O]>>>0,g[O]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");d=T,f++}let m=y-d;for(;m!==y&&g[m]===0;)m++;const E=new Uint8Array(l+(y-m));let _=l;for(;m!==y;)E[_++]=g[m++];return E}function a(u){const f=c(u);if(f)return f;throw new Error("Non-base"+n+" character")}return{encode:o,decodeUnsafe:c,decode:a}}var s2="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Fu=i2(s2);function o2(e){function t(s){var o=Uint8Array.from(s),c=e(o),a=o.length+4,u=new Uint8Array(a);return u.set(o,0),u.set(c.subarray(0,4),o.length),Fu.encode(u)}function n(s){var o=s.slice(0,-4),c=s.slice(-4),a=e(o);if(!(c[0]^a[0]|c[1]^a[1]|c[2]^a[2]|c[3]^a[3]))return o}function r(s){var o=Fu.decodeUnsafe(s);if(o!=null)return n(o)}function i(s){var o=Fu.decode(s),c=n(o);if(c==null)throw new Error("Invalid checksum");return c}return{encode:t,decode:i,decodeUnsafe:r}}function c2(e){return Qt(Qt(e))}const Oo=o2(c2),Mr=Ge;function oc(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||{}),ct(fi(Et({network:Et({}),address:zi(),hash:gb,output:At(25),pubkey:Kn(Dn),signature:Kn(Ir),input:De})),e);const n=In(()=>{const o=Oo.decode(e.address),c=vr(o,0),a=o.slice(1);return{version:c,hash:a}}),r=In(()=>lt(e.input)),i=e.network||Pn,s={name:"p2pkh",network:i};if(Te(s,"address",()=>{if(!s.hash)return;const o=new Uint8Array(21);return bn(o,0,i.pubKeyHash),o.set(s.hash,1),Oo.encode(o)}),Te(s,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return n().hash;if(e.pubkey||s.pubkey)return Ar(e.pubkey||s.pubkey)}),Te(s,"output",()=>{if(s.hash)return tn([Mr.OP_DUP,Mr.OP_HASH160,s.hash,Mr.OP_EQUALVERIFY,Mr.OP_CHECKSIG])}),Te(s,"pubkey",()=>{if(e.input)return r()[1]}),Te(s,"signature",()=>{if(e.input)return r()[0]}),Te(s,"input",()=>{if(e.pubkey&&e.signature)return tn([e.signature,e.pubkey])}),Te(s,"witness",()=>{if(s.input)return[]}),t.validate){let o=Uint8Array.from([]);if(e.address){if(n().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(n().hash.length!==20)throw new TypeError("Invalid address");o=n().hash}if(e.hash){if(o.length>0&&de(o,e.hash)!==0)throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==25||e.output[0]!==Mr.OP_DUP||e.output[1]!==Mr.OP_HASH160||e.output[2]!==20||e.output[23]!==Mr.OP_EQUALVERIFY||e.output[24]!==Mr.OP_CHECKSIG)throw new TypeError("Output is invalid");const c=e.output.slice(3,23);if(o.length>0&&de(o,c)!==0)throw new TypeError("Hash mismatch");o=c}if(e.pubkey){const c=Ar(e.pubkey);if(o.length>0&&de(o,c)!==0)throw new TypeError("Hash mismatch");o=c}if(e.input){const c=r();if(c.length!==2)throw new TypeError("Input is invalid");if(!Ir(c[0]))throw new TypeError("Input has invalid signature");if(!Dn(c[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&de(e.signature,c[0])!==0)throw new TypeError("Signature mismatch");if(e.pubkey&&de(e.pubkey,c[1])!==0)throw new TypeError("Pubkey mismatch");const a=Ar(c[1]);if(o.length>0&&de(o,a)!==0)throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}const Js=Ge;function cc(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||{}),ct(fi(Et({network:Et({}),address:zi(),hash:At(20),output:At(23),redeem:fi(Et({network:Et({}),output:De,input:De,witness:dn(De)})),input:De,witness:dn(De)})),e);let n=e.network;n||(n=e.redeem&&e.redeem.network||Pn);const r={network:n},i=In(()=>{const c=Oo.decode(e.address),a=vr(c,0),u=c.slice(1);return{version:a,hash:u}}),s=In(()=>lt(e.input)),o=In(()=>{const c=s(),a=c[c.length-1];return{network:n,output:a===Js.OP_FALSE?Uint8Array.from([]):a,input:tn(c.slice(0,-1)),witness:e.witness||[]}});if(Te(r,"address",()=>{if(!r.hash)return;const c=new Uint8Array(21);return bn(c,0,r.network.scriptHash),c.set(r.hash,1),Oo.encode(c)}),Te(r,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return i().hash;if(r.redeem&&r.redeem.output)return Ar(r.redeem.output)}),Te(r,"output",()=>{if(r.hash)return tn([Js.OP_HASH160,r.hash,Js.OP_EQUAL])}),Te(r,"redeem",()=>{if(e.input)return o()}),Te(r,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return tn([].concat(lt(e.redeem.input),e.redeem.output))}),Te(r,"witness",()=>{if(r.redeem&&r.redeem.witness)return r.redeem.witness;if(r.input)return[]}),Te(r,"name",()=>{const c=["p2sh"];return r.redeem!==void 0&&r.redeem.name!==void 0&&c.push(r.redeem.name),c.join("-")}),t.validate){let c=Uint8Array.from([]);if(e.address){if(i().version!==n.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(i().hash.length!==20)throw new TypeError("Invalid address");c=i().hash}if(e.hash){if(c.length>0&&de(c,e.hash)!==0)throw new TypeError("Hash mismatch");c=e.hash}if(e.output){if(e.output.length!==23||e.output[0]!==Js.OP_HASH160||e.output[1]!==20||e.output[22]!==Js.OP_EQUAL)throw new TypeError("Output is invalid");const u=e.output.slice(2,22);if(c.length>0&&de(c,u)!==0)throw new TypeError("Hash mismatch");c=u}const a=u=>{if(u.output){const f=lt(u.output);if(!f||f.length<1)throw new TypeError("Redeem.output too short");if(u.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(ng(f)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const l=Ar(u.output);if(c.length>0&&de(c,l)!==0)throw new TypeError("Hash mismatch");c=l}if(u.input){const f=u.input.length>0,l=u.witness&&u.witness.length>0;if(!f&&!l)throw new TypeError("Empty input");if(f&&l)throw new TypeError("Input and witness provided");if(f){const d=lt(u.input);if(!Il(d))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const u=s();if(!u||u.length<1)throw new TypeError("Input too short");if(!(o().output instanceof Uint8Array))throw new TypeError("Input is invalid");a(o())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==n)throw new TypeError("Network mismatch");if(e.input){const u=o();if(e.redeem.output&&de(e.redeem.output,u.output)!==0)throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&de(e.redeem.input,u.input)!==0)throw new TypeError("Redeem.input mismatch")}a(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!Io(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(r,e)}var bi={},bd;function ac(){if(bd)return bi;bd=1,Object.defineProperty(bi,"__esModule",{value:!0}),bi.bech32m=bi.bech32=void 0;const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",t={};for(let u=0;u<e.length;u++){const f=e.charAt(u);t[f]=u}function n(u){const f=u>>25;return(u&33554431)<<5^-(f>>0&1)&996825010^-(f>>1&1)&642813549^-(f>>2&1)&513874426^-(f>>3&1)&1027748829^-(f>>4&1)&705979059}function r(u){let f=1;for(let l=0;l<u.length;++l){const d=u.charCodeAt(l);if(d<33||d>126)return"Invalid prefix ("+u+")";f=n(f)^d>>5}f=n(f);for(let l=0;l<u.length;++l){const d=u.charCodeAt(l);f=n(f)^d&31}return f}function i(u,f,l,d){let y=0,g=0;const m=(1<<l)-1,E=[];for(let _=0;_<u.length;++_)for(y=y<<f|u[_],g+=f;g>=l;)g-=l,E.push(y>>g&m);if(d)g>0&&E.push(y<<l-g&m);else{if(g>=f)return"Excess padding";if(y<<l-g&m)return"Non-zero padding"}return E}function s(u){return i(u,8,5,!0)}function o(u){const f=i(u,5,8,!1);if(Array.isArray(f))return f}function c(u){const f=i(u,5,8,!1);if(Array.isArray(f))return f;throw new Error(f)}function a(u){let f;u==="bech32"?f=1:f=734539939;function l(m,E,_){if(_=_||90,m.length+7+E.length>_)throw new TypeError("Exceeds length limit");m=m.toLowerCase();let S=r(m);if(typeof S=="string")throw new Error(S);let w=m+"1";for(let T=0;T<E.length;++T){const O=E[T];if(O>>5!==0)throw new Error("Non 5-bit word");S=n(S)^O,w+=e.charAt(O)}for(let T=0;T<6;++T)S=n(S);S^=f;for(let T=0;T<6;++T){const O=S>>(5-T)*5&31;w+=e.charAt(O)}return w}function d(m,E){if(E=E||90,m.length<8)return m+" too short";if(m.length>E)return"Exceeds length limit";const _=m.toLowerCase(),S=m.toUpperCase();if(m!==_&&m!==S)return"Mixed-case string "+m;m=_;const w=m.lastIndexOf("1");if(w===-1)return"No separator character for "+m;if(w===0)return"Missing prefix for "+m;const T=m.slice(0,w),O=m.slice(w+1);if(O.length<6)return"Data too short";let A=r(T);if(typeof A=="string")return A;const R=[];for(let M=0;M<O.length;++M){const v=O.charAt(M),U=t[v];if(U===void 0)return"Unknown character "+v;A=n(A)^U,!(M+6>=O.length)&&R.push(U)}return A!==f?"Invalid checksum for "+m:{prefix:T,words:R}}function y(m,E){const _=d(m,E);if(typeof _=="object")return _}function g(m,E){const _=d(m,E);if(typeof _=="object")return _;throw new Error(_)}return{decodeUnsafe:y,decode:g,encode:l,toWords:s,fromWordsUnsafe:o,fromWords:c}}return bi.bech32=a("bech32"),bi.bech32m=a("bech32m"),bi}var Kt=ac();const Ed=Ge,a2=new Uint8Array(0);function za(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||{}),ct(fi(Et({address:zi(),hash:At(20),input:At(0),network:Et({}),output:At(22),pubkey:Kn(Dn,"Not a valid pubkey"),signature:Kn(Ir),witness:dn(De)})),e);const n=In(()=>{const s=Kt.bech32.decode(e.address),o=s.words.shift(),c=Kt.bech32.fromWords(s.words);return{version:o,prefix:s.prefix,data:Uint8Array.from(c)}}),r=e.network||Pn,i={name:"p2wpkh",network:r};if(Te(i,"address",()=>{if(!i.hash)return;const s=Kt.bech32.toWords(i.hash);return s.unshift(0),Kt.bech32.encode(r.bech32,s)}),Te(i,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return n().data;if(e.pubkey||i.pubkey)return Ar(e.pubkey||i.pubkey)}),Te(i,"output",()=>{if(i.hash)return tn([Ed.OP_0,i.hash])}),Te(i,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),Te(i,"signature",()=>{if(e.witness)return e.witness[0]}),Te(i,"input",()=>{if(i.witness)return a2}),Te(i,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let s=Uint8Array.from([]);if(e.address){if(r&&r.bech32!==n().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(n().version!==0)throw new TypeError("Invalid address version");if(n().data.length!==20)throw new TypeError("Invalid address data");s=n().data}if(e.hash){if(s.length>0&&de(s,e.hash)!==0)throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==Ed.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(s.length>0&&de(s,e.output.slice(2))!==0)throw new TypeError("Hash mismatch");s=e.output.slice(2)}if(e.pubkey){const o=Ar(e.pubkey);if(s.length>0&&de(s,o)!==0)throw new TypeError("Hash mismatch");if(s=o,!Dn(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(!Ir(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!Dn(e.witness[1])||e.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(e.signature&&de(e.signature,e.witness[0])!==0)throw new TypeError("Signature mismatch");if(e.pubkey&&de(e.pubkey,e.witness[1])!==0)throw new TypeError("Pubkey mismatch");const o=Ar(e.witness[1]);if(s.length>0&&de(s,o)!==0)throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}const _d=Ge,Mu=new Uint8Array(0);function Bc(e){return!!(e instanceof Uint8Array&&e.length===65&&e[0]===4&&Dn(e))}function uc(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||{}),ct(ad({network:Et({}),address:zi(),hash:yb,output:At(34),redeem:ad({input:De,network:Et({}),output:De,witness:dn(De)}),input:At(0),witness:dn(De)}),e);const n=In(()=>{const o=Kt.bech32.decode(e.address),c=o.words.shift(),a=Kt.bech32.fromWords(o.words);return{version:c,prefix:o.prefix,data:Uint8Array.from(a)}}),r=In(()=>lt(e.redeem.input));let i=e.network;i||(i=e.redeem&&e.redeem.network||Pn);const s={network:i};if(Te(s,"address",()=>{if(!s.hash)return;const o=Kt.bech32.toWords(s.hash);return o.unshift(0),Kt.bech32.encode(i.bech32,o)}),Te(s,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return n().data;if(s.redeem&&s.redeem.output)return Qt(s.redeem.output)}),Te(s,"output",()=>{if(s.hash)return tn([_d.OP_0,s.hash])}),Te(s,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:Mu,witness:e.witness.slice(0,-1)}}),Te(s,"input",()=>{if(s.witness)return Mu}),Te(s,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const o=xb(r());return s.redeem=Object.assign({witness:o},e.redeem),s.redeem.input=Mu,[].concat(o,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),Te(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=Uint8Array.from([]);if(e.address){if(n().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(n().version!==0)throw new TypeError("Invalid address version");if(n().data.length!==32)throw new TypeError("Invalid address data");o=n().data}if(e.hash){if(o.length>0&&de(o,e.hash)!==0)throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==34||e.output[0]!==_d.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const c=e.output.slice(2);if(o.length>0&&de(o,c)!==0)throw new TypeError("Hash mismatch");o=c}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 c=lt(e.redeem.output);if(!c||c.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(ng(c)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const a=Qt(e.redeem.output);if(o.length>0&&de(o,a)!==0)throw new TypeError("Hash mismatch");o=a}if(e.redeem.input&&!Il(r()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!Io(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&r().some(Bc)||e.redeem.output&&(lt(e.redeem.output)||[]).some(Bc))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const c=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&de(e.redeem.output,c)!==0)throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(Bc)||(lt(c)||[]).some(Bc))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(s,e)}const To={};function u2(e){e?e!==To.eccLib&&(f2(e),To.eccLib=e):To.eccLib=e}function qf(){if(!To.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return To.eccLib}const cr=e=>kr(e);function f2(e){Tn(typeof e.isXOnlyPoint=="function"),Tn(e.isXOnlyPoint(cr("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Tn(e.isXOnlyPoint(cr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Tn(e.isXOnlyPoint(cr("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Tn(e.isXOnlyPoint(cr("0000000000000000000000000000000000000000000000000000000000000001"))),Tn(!e.isXOnlyPoint(cr("0000000000000000000000000000000000000000000000000000000000000000"))),Tn(!e.isXOnlyPoint(cr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Tn(typeof e.xOnlyPointAddTweak=="function"),l2.forEach(t=>{const n=e.xOnlyPointAddTweak(cr(t.pubkey),cr(t.tweak));t.result===null?Tn(n===null):(Tn(n!==null),Tn(n.parity===t.parity),Tn(de(n.xOnlyPubkey,cr(t.result))===0))})}function Tn(e){if(!e)throw new Error("ecc library invalid")}const l2=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}],yg="0123456789abcdefABCDEF";yg.split("").map(e=>e.codePointAt(0));Array(256).fill(!0).map((e,t)=>{const n=String.fromCodePoint(t),r=yg.indexOf(n);return r<0?void 0:r<16?r:r-6});new TextEncoder;new TextDecoder;function h2(e,t,n,r){if(t+2>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>65535)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= 65535. Received ${n}`);r==="LE"?(e[t]=n&255,e[t+1]=n>>8&255):(e[t]=n>>8&255,e[t+1]=n&255)}function d2(e,t,n,r){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>4294967295)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${4294967295}. Received ${n}`);r==="LE"?(e[t]=n&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255):(e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255)}function p2(e,t,n,r){if(t+8>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>0xffffffffffffffffn)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${n}`);r==="LE"?(e[t]=Number(n&0xffn),e[t+1]=Number(n>>8n&0xffn),e[t+2]=Number(n>>16n&0xffn),e[t+3]=Number(n>>24n&0xffn),e[t+4]=Number(n>>32n&0xffn),e[t+5]=Number(n>>40n&0xffn),e[t+6]=Number(n>>48n&0xffn),e[t+7]=Number(n>>56n&0xffn)):(e[t]=Number(n>>56n&0xffn),e[t+1]=Number(n>>48n&0xffn),e[t+2]=Number(n>>40n&0xffn),e[t+3]=Number(n>>32n&0xffn),e[t+4]=Number(n>>24n&0xffn),e[t+5]=Number(n>>16n&0xffn),e[t+6]=Number(n>>8n&0xffn),e[t+7]=Number(n&0xffn))}function y2(e,t,n){if(t+2>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){let r=0;return r=(r<<8)+e[t+1],r=(r<<8)+e[t],r}else{let r=0;return r=(r<<8)+e[t],r=(r<<8)+e[t+1],r}}function g2(e,t,n){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){let r=0;return r=(r<<8)+e[t+3]>>>0,r=(r<<8)+e[t+2]>>>0,r=(r<<8)+e[t+1]>>>0,r=(r<<8)+e[t]>>>0,r}else{let r=0;return r=(r<<8)+e[t]>>>0,r=(r<<8)+e[t+1]>>>0,r=(r<<8)+e[t+2]>>>0,r=(r<<8)+e[t+3]>>>0,r}}function m2(e,t,n){if(t+8>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){let r=0n;return r=(r<<8n)+BigInt(e[t+7]),r=(r<<8n)+BigInt(e[t+6]),r=(r<<8n)+BigInt(e[t+5]),r=(r<<8n)+BigInt(e[t+4]),r=(r<<8n)+BigInt(e[t+3]),r=(r<<8n)+BigInt(e[t+2]),r=(r<<8n)+BigInt(e[t+1]),r=(r<<8n)+BigInt(e[t]),r}else{let r=0n;return r=(r<<8n)+BigInt(e[t]),r=(r<<8n)+BigInt(e[t+1]),r=(r<<8n)+BigInt(e[t+2]),r=(r<<8n)+BigInt(e[t+3]),r=(r<<8n)+BigInt(e[t+4]),r=(r<<8n)+BigInt(e[t+5]),r=(r<<8n)+BigInt(e[t+6]),r=(r<<8n)+BigInt(e[t+7]),r}}const w2=e=>{if(e<0||e>0xffffffffffffffffn)throw new RangeError("value out of range")};function b2(e){if(e<0||e>Number.MAX_SAFE_INTEGER||e%1!==0)throw new RangeError("value out of range")}function gg(e){typeof e=="number"?b2(e):w2(e)}function li(e,t,n){gg(e),n===void 0&&(n=0),t===void 0&&(t=new Uint8Array(Bn(e)));let r=0;return e<253?(t.set([Number(e)],n),r=1):e<=65535?(t.set([253],n),h2(t,n+1,Number(e),"LE"),r=3):e<=4294967295?(t.set([254],n),d2(t,n+1,Number(e),"LE"),r=5):(t.set([255],n),p2(t,n+1,BigInt(e),"LE"),r=9),{buffer:t,bytes:r}}function Ls(e,t){t===void 0&&(t=0);const n=e.at(t);if(n===void 0)throw new Error("buffer too small");if(n<253)return{numberValue:n,bigintValue:BigInt(n),bytes:1};if(n===253){const r=y2(e,t+1,"LE");return{numberValue:r,bigintValue:BigInt(r),bytes:3}}else if(n===254){const r=g2(e,t+1,"LE");return{numberValue:r,bigintValue:BigInt(r),bytes:5}}else{const r=m2(e,t+1,"LE");return{numberValue:r<=Number.MAX_SAFE_INTEGER?Number(r):null,bigintValue:r,bytes:9}}}function Bn(e){return gg(e),e<253?1:e<=65535?3:e<=4294967295?5:9}const E2=9007199254740991;function _2(e,t){if(typeof e!="number"&&typeof e!="bigint")throw new Error("cannot write a non-number as a number");if(e<0&&e<BigInt(0))throw new Error("specified a negative value for writing an unsigned value");if(e>t&&e>BigInt(t))throw new Error("RangeError: value out of range");if(Math.floor(Number(e))!==Number(e))throw new Error("value has a fractional component")}function Nl(e){if(e.length<1)return e;let t=e.length-1,n=0;for(let r=0;r<e.length/2;r++)n=e[r],e[r]=e[t],e[t]=n,t--;return e}function Sd(e){const t=new Uint8Array(e.length);return t.set(e),t}class $t{buffer;offset;static withCapacity(t){return new $t(new Uint8Array(t))}constructor(t,n=0){this.buffer=t,this.offset=n,ct(Qn([De,yr]),[t,n])}writeUInt8(t){this.offset=bn(this.buffer,this.offset,t)}writeInt32(t){this.offset=$y(this.buffer,this.offset,t,"LE")}writeInt64(t){this.offset=Dy(this.buffer,this.offset,BigInt(t),"LE")}writeUInt32(t){this.offset=rc(this.buffer,this.offset,t,"LE")}writeUInt64(t){this.offset=Q1(this.buffer,this.offset,BigInt(t),"LE")}writeVarInt(t){const{bytes:n}=li(t,this.buffer,this.offset);this.offset+=n}writeSlice(t){if(this.buffer.length<this.offset+t.length)throw new Error("Cannot write slice out of bounds");this.buffer.set(t,this.offset),this.offset+=t.length}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}writeVector(t){this.writeVarInt(t.length),t.forEach(n=>this.writeVarSlice(n))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}class S2{buffer;offset;constructor(t,n=0){this.buffer=t,this.offset=n,ct(Qn([De,yr]),[t,n])}readUInt8(){const t=vr(this.buffer,this.offset);return this.offset++,t}readInt32(){const t=tb(this.buffer,this.offset,"LE");return this.offset+=4,t}readUInt32(){const t=qs(this.buffer,this.offset,"LE");return this.offset+=4,t}readInt64(){const t=jy(this.buffer,this.offset,"LE");return this.offset+=8,t}readVarInt(){const{bigintValue:t,bytes:n}=Ls(this.buffer,this.offset);return this.offset+=n,t}readSlice(t){_2(t,E2);const n=Number(t);if(this.buffer.length<this.offset+n)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+n);return this.offset+=n,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const t=this.readVarInt(),n=[];for(let r=0;r<t;r++)n.push(this.readVarSlice());return n}}const mg=192,T2=128,x2=e=>"left"in e&&"right"in e;function Vf(e,t){if(e.length<33)throw new TypeError(`The control-block length is too small. Got ${e.length}, expected min 33.`);const n=(e.length-33)/32;let r=t;for(let i=0;i<n;i++){const s=e.slice(33+32*i,65+32*i);de(r,s)<0?r=$f(r,s):r=$f(s,r)}return r}function Lf(e){if(vl(e))return{hash:Er(e)};const t=[Lf(e[0]),Lf(e[1])];t.sort((i,s)=>de(i.hash,s.hash));const[n,r]=t;return{hash:$f(n.hash,r.hash),left:n,right:r}}function pa(e,t){if(x2(e)){const n=pa(e.left,t);if(n!==void 0)return[...n,e.right.hash];const r=pa(e.right,t);if(r!==void 0)return[...r,e.left.hash]}else if(de(e.hash,t)===0)return[]}function Er(e){const t=e.version||mg;return Xa("TapLeaf",at([Uint8Array.from([t]),v2(e.output)]))}function A2(e,t){return Xa("TapTweak",at(t?[e,t]:[e]))}function Nc(e,t){if(!(e instanceof Uint8Array)||e.length!==32||t&&t.length!==32)return null;const n=A2(e,t),r=qf().xOnlyPointAddTweak(e,n);return!r||r.xOnlyPubkey===null?null:{parity:r.parity,x:Uint8Array.from(r.xOnlyPubkey)}}function $f(e,t){return Xa("TapBranch",at([e,t]))}function v2(e){const t=Bn(e.length),n=new Uint8Array(t);return li(e.length,n),at([n,e])}const Td=Ge,xd=1,I2=80;function fc(e,t){if(!e.address&&!e.output&&!e.pubkey&&!e.internalPubkey&&!(e.witness&&e.witness.length>1))throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),ct(fi(Et({address:zi(),input:At(0),network:Et({}),output:At(34),internalPubkey:At(32),hash:At(32),pubkey:At(32),signature:Al([At(64),At(65)]),witness:dn(De),scriptTree:Kn(Jy,"Taptree is not of type isTaptree"),redeem:fi(Et({output:De,redeemVersion:ln(),witness:dn(De)})),redeemVersion:ln()})),e);const n=In(()=>kl(e.address)),r=In(()=>{if(!(!e.witness||!e.witness.length))return e.witness.length>=2&&e.witness[e.witness.length-1][0]===I2?e.witness.slice(0,-1):e.witness.slice()}),i=In(()=>{if(e.scriptTree)return Lf(e.scriptTree);if(e.hash)return{hash:e.hash}}),s=e.network||Pn,o={name:"p2tr",network:s};if(Te(o,"address",()=>{if(!o.pubkey)return;const c=Kt.bech32m.toWords(o.pubkey);return c.unshift(xd),Kt.bech32m.encode(s.bech32,c)}),Te(o,"hash",()=>{const c=i();if(c)return c.hash;const a=r();if(a&&a.length>1){const u=a[a.length-1],f=u[0]&Xc,l=a[a.length-2],d=Er({output:l,version:f});return Vf(u,d)}return null}),Te(o,"output",()=>{if(o.pubkey)return tn([Td.OP_1,o.pubkey])}),Te(o,"redeemVersion",()=>e.redeemVersion?e.redeemVersion:e.redeem&&e.redeem.redeemVersion!==void 0&&e.redeem.redeemVersion!==null?e.redeem.redeemVersion:mg),Te(o,"redeem",()=>{const c=r();if(!(!c||c.length<2))return{output:c[c.length-2],witness:c.slice(0,-2),redeemVersion:c[c.length-1][0]&Xc}}),Te(o,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.output)return e.output.slice(2);if(e.address)return n().data;if(o.internalPubkey){const c=Nc(o.internalPubkey,o.hash);if(c)return c.x}}),Te(o,"internalPubkey",()=>{if(e.internalPubkey)return e.internalPubkey;const c=r();if(c&&c.length>1)return c[c.length-1].slice(1,33)}),Te(o,"signature",()=>{if(e.signature)return e.signature;const c=r();if(!(!c||c.length!==1))return c[0]}),Te(o,"witness",()=>{if(e.witness)return e.witness;const c=i();if(c&&e.redeem&&e.redeem.output&&e.internalPubkey){const a=Er({output:e.redeem.output,version:o.redeemVersion}),u=pa(c,a);if(!u)return;const f=Nc(e.internalPubkey,c.hash);if(!f)return;const l=at([Uint8Array.from([o.redeemVersion|f.parity]),e.internalPubkey].concat(u));return[e.redeem.output,l]}if(e.signature)return[e.signature]}),t.validate){let c=Uint8Array.from([]);if(e.address){if(s&&s.bech32!==n().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(n().version!==xd)throw new TypeError("Invalid address version");if(n().data.length!==32)throw new TypeError("Invalid address data");c=n().data}if(e.pubkey){if(c.length>0&&de(c,e.pubkey)!==0)throw new TypeError("Pubkey mismatch");c=e.pubkey}if(e.output){if(e.output.length!==34||e.output[0]!==Td.OP_1||e.output[1]!==32)throw new TypeError("Output is invalid");if(c.length>0&&de(c,e.output.slice(2))!==0)throw new TypeError("Pubkey mismatch");c=e.output.slice(2)}if(e.internalPubkey){const f=Nc(e.internalPubkey,o.hash);if(c.length>0&&de(c,f.x)!==0)throw new TypeError("Pubkey mismatch");c=f.x}if(c&&c.length&&!qf().isXOnlyPoint(c))throw new TypeError("Invalid pubkey for p2tr");const a=i();if(e.hash&&a&&de(e.hash,a.hash)!==0)throw new TypeError("Hash mismatch");if(e.redeem&&e.redeem.output&&a){const f=Er({output:e.redeem.output,version:o.redeemVersion});if(!pa(a,f))throw new TypeError("Redeem script not in tree")}const u=r();if(e.redeem&&o.redeem){if(e.redeem.redeemVersion&&e.redeem.redeemVersion!==o.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(e.redeem.output){if(lt(e.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(o.redeem.output&&de(e.redeem.output,o.redeem.output)!==0)throw new TypeError("Redeem.output and witness mismatch")}if(e.redeem.witness&&o.redeem.witness&&!Io(e.redeem.witness,o.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(u&&u.length)if(u.length===1){if(e.signature&&de(e.signature,u[0])!==0)throw new TypeError("Signature mismatch")}else{const f=u[u.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 l=(f.length-33)/32;if(l>128)throw new TypeError(`The script path is too long. Got ${l}, expected max 128.`);const d=f.slice(1,33);if(e.internalPubkey&&de(e.internalPubkey,d)!==0)throw new TypeError("Internal pubkey mismatch");if(!qf().isXOnlyPoint(d))throw new TypeError("Invalid internalPubkey for p2tr witness");const y=f[0]&Xc,g=u[u.length-2],m=Er({output:g,version:y}),E=Vf(f,m),_=Nc(d,E);if(!_)throw new TypeError("Invalid outputKey for p2tr witness");if(c.length&&de(c,_.x)!==0)throw new TypeError("Pubkey mismatch for p2tr witness");if(_.parity!==(f[0]&1))throw new Error("Incorrect parity")}}return Object.assign(o,e)}const wg=40,bg=2,Eg=16,_g=2,Sg=80,Tg="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 O2(e,t){const n=e.slice(2);if(n.length<bg||n.length>wg)throw new TypeError("Invalid program length for segwit address");const r=e[0]-Sg;if(r<_g||r>Eg)throw new TypeError("Invalid version for segwit address");if(e[1]!==n.length)throw new TypeError("Invalid script for segwit address");return console.warn(Tg),B2(n,r,t.bech32)}function xg(e){const t=Oo.decode(e);if(t.length<21)throw new TypeError(e+" is too short");if(t.length>21)throw new TypeError(e+" is too long");const n=vr(t,0),r=t.slice(1);return{version:n,hash:r}}function kl(e){let t,n;try{t=Kt.bech32.decode(e)}catch{}if(t){if(n=t.words[0],n!==0)throw new TypeError(e+" uses wrong encoding")}else if(t=Kt.bech32m.decode(e),n=t.words[0],n===0)throw new TypeError(e+" uses wrong encoding");const r=Kt.bech32.fromWords(t.words.slice(1));return{version:n,prefix:t.prefix,data:Uint8Array.from(r)}}function B2(e,t,n){const r=Kt.bech32.toWords(e);return r.unshift(t),t===0?Kt.bech32.encode(n,r):Kt.bech32m.encode(n,r)}function N2(e,t){t=t||Pn;try{return oc({output:e,network:t}).address}catch{}try{return cc({output:e,network:t}).address}catch{}try{return za({output:e,network:t}).address}catch{}try{return uc({output:e,network:t}).address}catch{}try{return fc({output:e,network:t}).address}catch{}try{return O2(e,t)}catch{}throw new Error(Tb(e)+" has no matching Address")}function Ag(e,t){t=t||Pn;let n,r;try{n=xg(e)}catch{}if(n){if(n.version===t.pubKeyHash)return oc({hash:n.hash}).output;if(n.version===t.scriptHash)return cc({hash:n.hash}).output}else{try{r=kl(e)}catch{}if(r){if(r.prefix!==t.bech32)throw new Error(e+" has an invalid prefix");if(r.version===0){if(r.data.length===20)return za({hash:r.data}).output;if(r.data.length===32)return uc({hash:r.data}).output}else if(r.version===1){if(r.data.length===32)return fc({pubkey:r.data}).output}else if(r.version>=_g&&r.version<=Eg&&r.data.length>=bg&&r.data.length<=wg)return console.warn(Tg),tn([r.version+Sg,r.data])}}throw new Error(e+" has no matching Script")}function Jn(e){const t=e.length;return Bn(t)+t}function k2(e){const t=e.length;return Bn(t)+e.reduce((n,r)=>n+Jn(r),0)}const ei=new Uint8Array(0),Ad=[],qu=kr("0000000000000000000000000000000000000000000000000000000000000000"),vd=kr("0000000000000000000000000000000000000000000000000000000000000001"),P2=kr("ffffffffffffffff"),R2={script:ei,valueBuffer:P2};function U2(e){return e.value!==void 0}let gt=class Ye{static DEFAULT_SEQUENCE=4294967295;static SIGHASH_DEFAULT=0;static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_ANYONECANPAY=128;static SIGHASH_OUTPUT_MASK=3;static SIGHASH_INPUT_MASK=128;static ADVANCED_TRANSACTION_MARKER=0;static ADVANCED_TRANSACTION_FLAG=1;static fromBuffer(t,n){const r=new S2(t),i=new Ye;i.version=r.readInt32();const s=r.readUInt8(),o=r.readUInt8();let c=!1;s===Ye.ADVANCED_TRANSACTION_MARKER&&o===Ye.ADVANCED_TRANSACTION_FLAG?c=!0:r.offset-=2;const a=r.readVarInt();for(let f=0;f<a;++f)i.ins.push({hash:r.readSlice(32),index:r.readUInt32(),script:r.readVarSlice(),sequence:r.readUInt32(),witness:Ad});const u=r.readVarInt();for(let f=0;f<u;++f)i.outs.push({value:r.readInt64(),script:r.readVarSlice()});if(c){for(let f=0;f<a;++f)i.ins[f].witness=r.readVector();if(!i.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(i.locktime=r.readUInt32(),n)return i;if(r.offset!==t.length)throw new Error("Transaction has unexpected data");return i}static fromHex(t){return Ye.fromBuffer(kr(t),!1)}static isCoinbaseHash(t){ct(cd,t);for(let n=0;n<32;++n)if(t[n]!==0)return!1;return!0}version=1;locktime=0;ins=[];outs=[];isCoinbase(){return this.ins.length===1&&Ye.isCoinbaseHash(this.ins[0].hash)}addInput(t,n,r,i){return ct(Qn([cd,yr,Mf(la(yr)),Mf(la(De))]),[t,n,r,i]),r==null&&(r=Ye.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:n,script:i||ei,sequence:r,witness:Ad})-1}addOutput(t,n){return ct(Qn([De,Cu]),[t,n]),this.outs.push({script:t,value:n})-1}hasWitnesses(){return this.ins.some(t=>t.witness.length!==0)}weight(){const t=this.byteLength(!1),n=this.byteLength(!0);return t*3+n}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const n=t&&this.hasWitnesses();return(n?10:8)+Bn(this.ins.length)+Bn(this.outs.length)+this.ins.reduce((r,i)=>r+40+Jn(i.script),0)+this.outs.reduce((r,i)=>r+8+Jn(i.script),0)+(n?this.ins.reduce((r,i)=>r+k2(i.witness),0):0)}clone(){const t=new Ye;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map(n=>({hash:n.hash,index:n.index,script:n.script,sequence:n.sequence,witness:n.witness})),t.outs=this.outs.map(n=>({script:n.script,value:n.value})),t}hashForSignature(t,n,r){if(ct(Qn([yr,De,ln()]),[t,n,r]),t>=this.ins.length)return vd;const i=tn(lt(n).filter(c=>c!==Ge.OP_CODESEPARATOR)),s=this.clone();if((r&31)===Ye.SIGHASH_NONE)s.outs=[],s.ins.forEach((c,a)=>{a!==t&&(c.sequence=0)});else if((r&31)===Ye.SIGHASH_SINGLE){if(t>=this.outs.length)return vd;s.outs.length=t+1;for(let c=0;c<t;c++)s.outs[c]=R2;s.ins.forEach((c,a)=>{a!==t&&(c.sequence=0)})}r&Ye.SIGHASH_ANYONECANPAY?(s.ins=[s.ins[t]],s.ins[0].script=i):(s.ins.forEach(c=>{c.script=ei}),s.ins[t].script=i);const o=new Uint8Array(s.byteLength(!1)+4);return $y(o,o.length-4,r,"LE"),s.__toBuffer(o,0,!1),wi(o)}hashForWitnessV1(t,n,r,i,s,o){if(ct(Qn([yr,dn(De),dn(Cu),yr]),[t,n,r,i]),r.length!==this.ins.length||n.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const c=i===Ye.SIGHASH_DEFAULT?Ye.SIGHASH_ALL:i&Ye.SIGHASH_OUTPUT_MASK,u=(i&Ye.SIGHASH_INPUT_MASK)===Ye.SIGHASH_ANYONECANPAY,f=c===Ye.SIGHASH_NONE,l=c===Ye.SIGHASH_SINGLE;let d=ei,y=ei,g=ei,m=ei,E=ei;if(!u){let T=$t.withCapacity(36*this.ins.length);this.ins.forEach(O=>{T.writeSlice(O.hash),T.writeUInt32(O.index)}),d=Qt(T.end()),T=$t.withCapacity(8*this.ins.length),r.forEach(O=>T.writeInt64(O)),y=Qt(T.end()),T=$t.withCapacity(n.map(Jn).reduce((O,A)=>O+A)),n.forEach(O=>T.writeVarSlice(O)),g=Qt(T.end()),T=$t.withCapacity(4*this.ins.length),this.ins.forEach(O=>T.writeUInt32(O.sequence)),m=Qt(T.end())}if(f||l){if(l&&t<this.outs.length){const T=this.outs[t],O=$t.withCapacity(8+Jn(T.script));O.writeInt64(T.value),O.writeVarSlice(T.script),E=Qt(O.end())}}else{if(!this.outs.length)throw new Error("Add outputs to the transaction before signing.");const T=this.outs.map(A=>8+Jn(A.script)).reduce((A,R)=>A+R),O=$t.withCapacity(T);this.outs.forEach(A=>{O.writeInt64(A.value),O.writeVarSlice(A.script)}),E=Qt(O.end())}const _=(s?2:0)+(o?1:0),S=174-(u?49:0)-(f?32:0)+(o?32:0)+(s?37:0),w=$t.withCapacity(S);if(w.writeUInt8(i),w.writeInt32(this.version),w.writeUInt32(this.locktime),w.writeSlice(d),w.writeSlice(y),w.writeSlice(g),w.writeSlice(m),f||l||w.writeSlice(E),w.writeUInt8(_),u){const T=this.ins[t];w.writeSlice(T.hash),w.writeUInt32(T.index),w.writeInt64(r[t]),w.writeVarSlice(n[t]),w.writeUInt32(T.sequence)}else w.writeUInt32(t);if(o){const T=$t.withCapacity(Jn(o));T.writeVarSlice(o),w.writeSlice(Qt(T.end()))}return l&&w.writeSlice(E),s&&(w.writeSlice(s),w.writeUInt8(0),w.writeUInt32(4294967295)),Xa("TapSighash",at([Uint8Array.from([0]),w.end()]))}hashForWitnessV0(t,n,r,i){ct(Qn([yr,De,Cu,yr]),[t,n,r,i]);let s=Uint8Array.from([]),o,c=qu,a=qu,u=qu;if(i&Ye.SIGHASH_ANYONECANPAY||(s=new Uint8Array(36*this.ins.length),o=new $t(s,0),this.ins.forEach(l=>{o.writeSlice(l.hash),o.writeUInt32(l.index)}),a=wi(s)),!(i&Ye.SIGHASH_ANYONECANPAY)&&(i&31)!==Ye.SIGHASH_SINGLE&&(i&31)!==Ye.SIGHASH_NONE&&(s=new Uint8Array(4*this.ins.length),o=new $t(s,0),this.ins.forEach(l=>{o.writeUInt32(l.sequence)}),u=wi(s)),(i&31)!==Ye.SIGHASH_SINGLE&&(i&31)!==Ye.SIGHASH_NONE){const l=this.outs.reduce((d,y)=>d+8+Jn(y.script),0);s=new Uint8Array(l),o=new $t(s,0),this.outs.forEach(d=>{o.writeInt64(d.value),o.writeVarSlice(d.script)}),c=wi(s)}else if((i&31)===Ye.SIGHASH_SINGLE&&t<this.outs.length){const l=this.outs[t];s=new Uint8Array(8+Jn(l.script)),o=new $t(s,0),o.writeInt64(l.value),o.writeVarSlice(l.script),c=wi(s)}s=new Uint8Array(156+Jn(n)),o=new $t(s,0);const f=this.ins[t];return o.writeInt32(this.version),o.writeSlice(a),o.writeSlice(u),o.writeSlice(f.hash),o.writeUInt32(f.index),o.writeVarSlice(n),o.writeInt64(r),o.writeUInt32(f.sequence),o.writeSlice(c),o.writeUInt32(this.locktime),o.writeUInt32(i),wi(s)}getHash(t){return t&&this.isCoinbase()?new Uint8Array(32):wi(this.__toBuffer(void 0,void 0,t))}getId(){return xe(Nl(this.getHash(!1)))}toBuffer(t,n){return this.__toBuffer(t,n,!0)}toHex(){return xe(this.toBuffer(void 0,void 0))}setInputScript(t,n){ct(Qn([ln(),De]),[t,n]),this.ins[t].script=n}setWitness(t,n){ct(Qn([ln(),dn(De)]),[t,n]),this.ins[t].witness=n}__toBuffer(t,n,r=!1){t||(t=new Uint8Array(this.byteLength(r)));const i=new $t(t,n||0);i.writeInt32(this.version);const s=r&&this.hasWitnesses();return s&&(i.writeUInt8(Ye.ADVANCED_TRANSACTION_MARKER),i.writeUInt8(Ye.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=>{U2(o)?i.writeInt64(o.value):i.writeSlice(o.valueBuffer),i.writeVarSlice(o.script)}),s&&this.ins.forEach(o=>{i.writeVector(o.witness)}),i.writeUInt32(this.locktime),n!==void 0?t.slice(n,i.offset):t}};var nr;(function(e){e[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB"})(nr||(nr={}));var me;(function(e){e[e.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",e[e.WITNESS_UTXO=1]="WITNESS_UTXO",e[e.PARTIAL_SIG=2]="PARTIAL_SIG",e[e.SIGHASH_TYPE=3]="SIGHASH_TYPE",e[e.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",e[e.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",e[e.BIP32_DERIVATION=6]="BIP32_DERIVATION",e[e.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",e[e.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",e[e.POR_COMMITMENT=9]="POR_COMMITMENT",e[e.TAP_KEY_SIG=19]="TAP_KEY_SIG",e[e.TAP_SCRIPT_SIG=20]="TAP_SCRIPT_SIG",e[e.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",e[e.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",e[e.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",e[e.TAP_MERKLE_ROOT=24]="TAP_MERKLE_ROOT"})(me||(me={}));var pt;(function(e){e[e.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",e[e.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",e[e.BIP32_DERIVATION=2]="BIP32_DERIVATION",e[e.TAP_INTERNAL_KEY=5]="TAP_INTERNAL_KEY",e[e.TAP_TREE=6]="TAP_TREE",e[e.TAP_BIP32_DERIVATION=7]="TAP_BIP32_DERIVATION"})(pt||(pt={}));const C2=e=>[...Array(e).keys()];function H2(e){if(e.key[0]!==nr.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+xe(e.key));if(e.key.length!==79||![2,3].includes(e.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+xe(e.key));if(e.value.length/4%1!==0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const t=e.key.slice(1),n={masterFingerprint:e.value.slice(0,4),extendedPubkey:t,path:"m"};for(const r of C2(e.value.length/4-1)){const i=qs(e.value,r*4+4,"LE"),s=!!(i&2147483648),o=i&2147483647;n.path+="/"+o.toString(10)+(s?"'":"")}return n}function F2(e){const t=new Uint8Array([nr.GLOBAL_XPUB]),n=at([t,e.extendedPubkey]),r=e.path.split("/"),i=new Uint8Array(r.length*4);i.set(e.masterFingerprint,0);let s=4;return r.slice(1).forEach(o=>{const c=o.slice(-1)==="'";let a=2147483647&parseInt(c?o.slice(0,-1):o,10);c&&(a+=2147483648),rc(i,s,a,"LE"),s+=4}),{key:n,value:i}}const M2="{ masterFingerprint: Uint8Array; extendedPubkey: Uint8Array; path: string; }";function q2(e){const t=e.extendedPubkey,n=e.masterFingerprint,r=e.path;return t instanceof Uint8Array&&t.length===78&&[2,3].indexOf(t[45])>-1&&n instanceof Uint8Array&&n.length===4&&typeof r=="string"&&!!r.match(/^m(\/\d+'?)*$/)}function V2(e,t,n){const r=xe(t.extendedPubkey);return n.has(r)?!1:(n.add(r),e.filter(i=>de(i.extendedPubkey,t.extendedPubkey)).length===0)}const L2=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:V2,check:q2,decode:H2,encode:F2,expected:M2},Symbol.toStringTag,{value:"Module"}));function $2(e){return{key:new Uint8Array([nr.UNSIGNED_TX]),value:e.toBuffer()}}const D2=Object.freeze(Object.defineProperty({__proto__:null,encode:$2},Symbol.toStringTag,{value:"Module"}));function j2(e){if(e.key[0]!==me.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+xe(e.key));return e.value}function K2(e){return{key:new Uint8Array([me.FINAL_SCRIPTSIG]),value:e}}const G2="Uint8Array";function W2(e){return e instanceof Uint8Array}function X2(e,t){return!!e&&!!t&&e.finalScriptSig===void 0}const z2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:X2,check:W2,decode:j2,encode:K2,expected:G2},Symbol.toStringTag,{value:"Module"}));function Y2(e){if(e.key[0]!==me.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+xe(e.key));return e.value}function Z2(e){return{key:new Uint8Array([me.FINAL_SCRIPTWITNESS]),value:e}}const J2="Uint8Array";function Q2(e){return e instanceof Uint8Array}function eE(e,t){return!!e&&!!t&&e.finalScriptWitness===void 0}const tE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:eE,check:Q2,decode:Y2,encode:Z2,expected:J2},Symbol.toStringTag,{value:"Module"}));function nE(e){if(e.key[0]!==me.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+xe(e.key));return e.value}function rE(e){return{key:new Uint8Array([me.NON_WITNESS_UTXO]),value:e}}const iE="Uint8Array";function sE(e){return e instanceof Uint8Array}function oE(e,t){return!!e&&!!t&&e.nonWitnessUtxo===void 0}const cE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:oE,check:sE,decode:nE,encode:rE,expected:iE},Symbol.toStringTag,{value:"Module"}));function aE(e){if(e.key[0]!==me.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+xe(e.key));if(!(e.key.length===34||e.key.length===66)||![2,3,4].includes(e.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+xe(e.key));return{pubkey:e.key.slice(1),signature:e.value}}function uE(e){const t=new Uint8Array([me.PARTIAL_SIG]);return{key:at([t,e.pubkey]),value:e.signature}}const fE="{ pubkey: Uint8Array; signature: Uint8Array; }";function lE(e){return e.pubkey instanceof Uint8Array&&e.signature instanceof Uint8Array&&[33,65].includes(e.pubkey.length)&&[2,3,4].includes(e.pubkey[0])&&hE(e.signature)}function hE(e){if(!(e instanceof Uint8Array)||e.length<9||e[0]!==48||e.length!==e[1]+3||e[2]!==2)return!1;const t=e[3];if(t>33||t<1||e[3+t+1]!==2)return!1;const n=e[3+t+2];return!(n>33||n<1||e.length!==3+t+2+n+2)}function dE(e,t,n){const r=xe(t.pubkey);return n.has(r)?!1:(n.add(r),e.filter(i=>de(i.pubkey,t.pubkey)===0).length===0)}const pE=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:dE,check:lE,decode:aE,encode:uE,expected:fE},Symbol.toStringTag,{value:"Module"}));function yE(e){if(e.key[0]!==me.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+xe(e.key));return W1(e.value)}function gE(e){return{key:new Uint8Array([me.POR_COMMITMENT]),value:X1(e)}}const mE="string";function wE(e){return typeof e=="string"}function bE(e,t){return!!e&&!!t&&e.porCommitment===void 0}const EE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:bE,check:wE,decode:yE,encode:gE,expected:mE},Symbol.toStringTag,{value:"Module"}));function _E(e){if(e.key[0]!==me.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+xe(e.key));return Number(qs(e.value,0,"LE"))}function SE(e){const t=Uint8Array.from([me.SIGHASH_TYPE]),n=new Uint8Array(4);return rc(n,0,e,"LE"),{key:t,value:n}}const TE="number";function xE(e){return typeof e=="number"}function AE(e,t){return!!e&&!!t&&e.sighashType===void 0}const vE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:AE,check:xE,decode:_E,encode:SE,expected:TE},Symbol.toStringTag,{value:"Module"}));function IE(e){if(e.key[0]!==me.TAP_KEY_SIG||e.key.length!==1)throw new Error("Decode Error: could not decode tapKeySig with key 0x"+xe(e.key));if(!vg(e.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return e.value}function OE(e){return{key:Uint8Array.from([me.TAP_KEY_SIG]),value:e}}const BE="Uint8Array";function vg(e){return e instanceof Uint8Array&&(e.length===64||e.length===65)}function NE(e,t){return!!e&&!!t&&e.tapKeySig===void 0}const kE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:NE,check:vg,decode:IE,encode:OE,expected:BE},Symbol.toStringTag,{value:"Module"}));function PE(e){if(e.key[0]!==me.TAP_LEAF_SCRIPT)throw new Error("Decode Error: could not decode tapLeafScript with key 0x"+xe(e.key));if((e.key.length-2)%32!==0)throw new Error("Decode Error: tapLeafScript has invalid control block in key 0x"+xe(e.key));const t=e.value[e.value.length-1];if((e.key[1]&254)!==t)throw new Error("Decode Error: tapLeafScript bad leaf version in key 0x"+xe(e.key));const n=e.value.slice(0,-1);return{controlBlock:e.key.slice(1),script:n,leafVersion:t}}function RE(e){const t=Uint8Array.from([me.TAP_LEAF_SCRIPT]),n=Uint8Array.from([e.leafVersion]);return{key:at([t,e.controlBlock]),value:at([e.script,n])}}const UE="{ controlBlock: Uint8Array; leafVersion: number, script: Uint8Array; }";function CE(e){return e.controlBlock instanceof Uint8Array&&(e.controlBlock.length-1)%32===0&&(e.controlBlock[0]&254)===e.leafVersion&&e.script instanceof Uint8Array}function HE(e,t,n){const r=xe(t.controlBlock);return n.has(r)?!1:(n.add(r),e.filter(i=>de(i.controlBlock,t.controlBlock)===0).length===0)}const FE=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:HE,check:CE,decode:PE,encode:RE,expected:UE},Symbol.toStringTag,{value:"Module"}));function ME(e){if(e.key[0]!==me.TAP_MERKLE_ROOT||e.key.length!==1)throw new Error("Decode Error: could not decode tapMerkleRoot with key 0x"+xe(e.key));if(!Ig(e.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return e.value}function qE(e){return{key:Uint8Array.from([me.TAP_MERKLE_ROOT]),value:e}}const VE="Uint8Array";function Ig(e){return e instanceof Uint8Array&&e.length===32}function LE(e,t){return!!e&&!!t&&e.tapMerkleRoot===void 0}const $E=Object.freeze(Object.defineProperty({__proto__:null,canAdd:LE,check:Ig,decode:ME,encode:qE,expected:VE},Symbol.toStringTag,{value:"Module"}));function DE(e){if(e.key[0]!==me.TAP_SCRIPT_SIG)throw new Error("Decode Error: could not decode tapScriptSig with key 0x"+xe(e.key));if(e.key.length!==65)throw new Error("Decode Error: tapScriptSig has invalid key 0x"+xe(e.key));if(e.value.length!==64&&e.value.length!==65)throw new Error("Decode Error: tapScriptSig has invalid signature in key 0x"+xe(e.key));const t=e.key.slice(1,33),n=e.key.slice(33);return{pubkey:t,leafHash:n,signature:e.value}}function jE(e){const t=Uint8Array.from([me.TAP_SCRIPT_SIG]);return{key:at([t,e.pubkey,e.leafHash]),value:e.signature}}const KE="{ pubkey: Uint8Array; leafHash: Uint8Array; signature: Uint8Array; }";function GE(e){return e.pubkey instanceof Uint8Array&&e.leafHash instanceof Uint8Array&&e.signature instanceof Uint8Array&&e.pubkey.length===32&&e.leafHash.length===32&&(e.signature.length===64||e.signature.length===65)}function WE(e,t,n){const r=xe(t.pubkey)+xe(t.leafHash);return n.has(r)?!1:(n.add(r),e.filter(i=>de(i.pubkey,t.pubkey)===0&&de(i.leafHash,t.leafHash)===0).length===0)}const XE=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:WE,check:GE,decode:DE,encode:jE,expected:KE},Symbol.toStringTag,{value:"Module"}));function zE(e){if(e.key[0]!==me.WITNESS_UTXO)throw new Error("Decode Error: could not decode witnessUtxo with key 0x"+xe(e.key));const t=jy(e.value,0,"LE");let n=8;const{numberValue:r,bytes:i}=Ls(e.value,n);n+=i;const s=e.value.slice(n);if(s.length!==r)throw new Error("Decode Error: WITNESS_UTXO script is not proper length");return{script:s,value:t}}function YE(e){const{script:t,value:n}=e,r=Bn(t.length),i=new Uint8Array(8+r+t.length);return Dy(i,0,BigInt(n),"LE"),li(t.length,i,8),i.set(t,8+r),{key:Uint8Array.from([me.WITNESS_UTXO]),value:i}}const ZE="{ script: Uint8Array; value: bigint; }";function JE(e){return e.script instanceof Uint8Array&&typeof e.value=="bigint"}function QE(e,t){return!!e&&!!t&&e.witnessUtxo===void 0}const e_=Object.freeze(Object.defineProperty({__proto__:null,canAdd:QE,check:JE,decode:zE,encode:YE,expected:ZE},Symbol.toStringTag,{value:"Module"}));function t_(e){if(e.key[0]!==pt.TAP_TREE||e.key.length!==1)throw new Error("Decode Error: could not decode tapTree with key 0x"+xe(e.key));let t=0;const n=[];for(;t<e.value.length;){const r=e.value[t++],i=e.value[t++],{numberValue:s,bytes:o}=Ls(e.value,t);t+=o,n.push({depth:r,leafVersion:i,script:e.value.slice(t,t+s)}),t+=s}return{leaves:n}}function n_(e){const t=Uint8Array.from([pt.TAP_TREE]),n=[].concat(...e.leaves.map(r=>[Uint8Array.of(r.depth,r.leafVersion),li(BigInt(r.script.length)).buffer,r.script]));return{key:t,value:at(n)}}const r_="{ leaves: [{ depth: number; leafVersion: number, script: Uint8Array; }] }";function i_(e){return Array.isArray(e.leaves)&&e.leaves.every(t=>t.depth>=0&&t.depth<=128&&(t.leafVersion&254)===t.leafVersion&&t.script instanceof Uint8Array)}function s_(e,t){return!!e&&!!t&&e.tapTree===void 0}const o_=Object.freeze(Object.defineProperty({__proto__:null,canAdd:s_,check:i_,decode:t_,encode:n_,expected:r_},Symbol.toStringTag,{value:"Module"})),c_=e=>[...Array(e).keys()],a_=e=>e.length===33&&[2,3].includes(e[0])||e.length===65&&e[0]===4;function Pl(e,t=a_){function n(c){if(c.key[0]!==e)throw new Error("Decode Error: could not decode bip32Derivation with key 0x"+xe(c.key));const a=c.key.slice(1);if(!t(a))throw new Error("Decode Error: bip32Derivation has invalid pubkey in key 0x"+xe(c.key));if(c.value.length/4%1!==0)throw new Error("Decode Error: Input BIP32_DERIVATION value length should be multiple of 4");const u={masterFingerprint:c.value.slice(0,4),pubkey:a,path:"m"};for(const f of c_(c.value.length/4-1)){const l=qs(c.value,f*4+4,"LE"),d=!!(l&2147483648),y=l&2147483647;u.path+="/"+y.toString(10)+(d?"'":"")}return u}function r(c){const a=Uint8Array.from([e]),u=at([a,c.pubkey]),f=c.path.split("/"),l=new Uint8Array(f.length*4);l.set(c.masterFingerprint,0);let d=4;return f.slice(1).forEach(y=>{const g=y.slice(-1)==="'";let m=2147483647&parseInt(g?y.slice(0,-1):y,10);g&&(m+=2147483648),rc(l,d,m,"LE"),d+=4}),{key:u,value:l}}const i="{ masterFingerprint: Uint8Array; pubkey: Uint8Array; path: string; }";function s(c){return c.pubkey instanceof Uint8Array&&c.masterFingerprint instanceof Uint8Array&&typeof c.path=="string"&&t(c.pubkey)&&c.masterFingerprint.length===4}function o(c,a,u){const f=xe(a.pubkey);return u.has(f)?!1:(u.add(f),c.filter(l=>de(l.pubkey,a.pubkey)===0).length===0)}return{decode:n,encode:r,check:s,expected:i,canAddToArray:o}}function Rl(e){return t;function t(n){let r;if(e.includes(n.key[0])&&(r=n.key.slice(1),!(r.length===33||r.length===65)||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+xe(n.key));return r}}function Og(e){function t(o){if(o.key[0]!==e)throw new Error("Decode Error: could not decode redeemScript with key 0x"+xe(o.key));return o.value}function n(o){return{key:Uint8Array.from([e]),value:o}}const r="Uint8Array";function i(o){return o instanceof Uint8Array}function s(o,c){return!!o&&!!c&&o.redeemScript===void 0}return{decode:t,encode:n,check:i,expected:r,canAdd:s}}const u_=e=>e.length===32;function Bg(e){const t=Pl(e,u_);function n(o){const{numberValue:c,bytes:a}=Ls(o.value),u=t.decode({key:o.key,value:o.value.slice(a+Number(c)*32)}),f=new Array(Number(c));for(let l=0,d=a;l<c;l++,d+=32)f[l]=o.value.slice(d,d+32);return{...u,leafHashes:f}}function r(o){const c=t.encode(o),a=Bn(o.leafHashes.length),u=new Uint8Array(a);li(o.leafHashes.length,u);const f=at([u,...o.leafHashes,c.value]);return{...c,value:f}}const i="{ masterFingerprint: Uint8Array; pubkey: Uint8Array; path: string; leafHashes: Uint8Array[]; }";function s(o){return Array.isArray(o.leafHashes)&&o.leafHashes.every(c=>c instanceof Uint8Array&&c.length===32)&&t.check(o)}return{decode:n,encode:r,check:s,expected:i,canAddToArray:t.canAddToArray}}function Ng(e){function t(o){if(o.key[0]!==e||o.key.length!==1)throw new Error("Decode Error: could not decode tapInternalKey with key 0x"+xe(o.key));if(o.value.length!==32)throw new Error("Decode Error: tapInternalKey not a 32-byte x-only pubkey");return o.value}function n(o){return{key:Uint8Array.from([e]),value:o}}const r="Uint8Array";function i(o){return o instanceof Uint8Array&&o.length===32}function s(o,c){return!!o&&!!c&&o.tapInternalKey===void 0}return{decode:t,encode:n,check:i,expected:r,canAdd:s}}function kg(e){function t(o){if(o.key[0]!==e)throw new Error("Decode Error: could not decode witnessScript with key 0x"+xe(o.key));return o.value}function n(o){return{key:Uint8Array.from([e]),value:o}}const r="Uint8Array";function i(o){return o instanceof Uint8Array}function s(o,c){return!!o&&!!c&&o.witnessScript===void 0}return{decode:t,encode:n,check:i,expected:r,canAdd:s}}const Ul={unsignedTx:D2,globalXpub:L2,checkPubkey:Rl([])},_t={nonWitnessUtxo:cE,partialSig:pE,sighashType:vE,finalScriptSig:z2,finalScriptWitness:tE,porCommitment:EE,witnessUtxo:e_,bip32Derivation:Pl(me.BIP32_DERIVATION),redeemScript:Og(me.REDEEM_SCRIPT),witnessScript:kg(me.WITNESS_SCRIPT),checkPubkey:Rl([me.PARTIAL_SIG,me.BIP32_DERIVATION]),tapKeySig:kE,tapScriptSig:XE,tapLeafScript:FE,tapBip32Derivation:Bg(me.TAP_BIP32_DERIVATION),tapInternalKey:Ng(me.TAP_INTERNAL_KEY),tapMerkleRoot:$E},gr={bip32Derivation:Pl(pt.BIP32_DERIVATION),redeemScript:Og(pt.REDEEM_SCRIPT),witnessScript:kg(pt.WITNESS_SCRIPT),checkPubkey:Rl([pt.BIP32_DERIVATION]),tapBip32Derivation:Bg(pt.TAP_BIP32_DERIVATION),tapTree:o_,tapInternalKey:Ng(pt.TAP_INTERNAL_KEY)},f_=Object.freeze(Object.defineProperty({__proto__:null,globals:Ul,inputs:_t,outputs:gr},Symbol.toStringTag,{value:"Module"})),ya=e=>[...Array(e).keys()];function Id(e){const t=e.map(l_);return t.push(Uint8Array.from([0])),at(t)}function l_(e){const t=e.key.length,n=e.value.length,r=Bn(t),i=Bn(n),s=new Uint8Array(r+t+i+n);return li(t,s,0),s.set(e.key,r),li(n,s,r+t),s.set(e.value,r+t+i),s}function h_(e,t){let n=0;function r(){const{numberValue:E,bytes:_}=Ls(e,n);n+=_;const S=e.slice(n,n+Number(E));return n+=Number(E),S}function i(){const E=qs(e,n,"BE");return n+=4,E}function s(){const E=vr(e,n);return n+=1,E}function o(){const E=r(),_=r();return{key:E,value:_}}function c(){if(n>=e.length)throw new Error("Format Error: Unexpected End of PSBT");const E=vr(e,n)===0;return E&&n++,E}if(i()!==1886610036)throw new Error("Format Error: Invalid Magic Number");if(s()!==255)throw new Error("Format Error: Magic Number must be followed by 0xff separator");const a=[],u={};for(;!c();){const E=o(),_=xe(E.key);if(u[_])throw new Error("Format Error: Keys must be unique for global keymap: key "+_);u[_]=1,a.push(E)}const f=a.filter(E=>E.key[0]===nr.UNSIGNED_TX);if(f.length!==1)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const l=t(f[0].value),{inputCount:d,outputCount:y}=l.getInputOutputCounts(),g=[],m=[];for(const E of ya(d)){const _={},S=[];for(;!c();){const w=o(),T=xe(w.key);if(_[T])throw new Error("Format Error: Keys must be unique for each input: input index "+E+" key "+T);_[T]=1,S.push(w)}g.push(S)}for(const E of ya(y)){const _={},S=[];for(;!c();){const w=o(),T=xe(w.key);if(_[T])throw new Error("Format Error: Keys must be unique for each output: output index "+E+" key "+T);_[T]=1,S.push(w)}m.push(S)}return Pg(l,{globalMapKeyVals:a,inputKeyVals:g,outputKeyVals:m})}function Lt(e,t,n){if(de(t,Uint8Array.from([n])))throw new Error(`Format Error: Invalid ${e} key: ${xe(t)}`)}function Pg(e,{globalMapKeyVals:t,inputKeyVals:n,outputKeyVals:r}){const i={unsignedTx:e};let s=0;for(const f of t)switch(f.key[0]){case nr.UNSIGNED_TX:if(Lt("global",f.key,nr.UNSIGNED_TX),s>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");s++;break;case nr.GLOBAL_XPUB:i.globalXpub===void 0&&(i.globalXpub=[]),i.globalXpub.push(Ul.globalXpub.decode(f));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(f)}const o=n.length,c=r.length,a=[],u=[];for(const f of ya(o)){const l={};for(const d of n[f])switch(_t.checkPubkey(d),d.key[0]){case me.NON_WITNESS_UTXO:if(Lt("input",d.key,me.NON_WITNESS_UTXO),l.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");l.nonWitnessUtxo=_t.nonWitnessUtxo.decode(d);break;case me.WITNESS_UTXO:if(Lt("input",d.key,me.WITNESS_UTXO),l.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");l.witnessUtxo=_t.witnessUtxo.decode(d);break;case me.PARTIAL_SIG:l.partialSig===void 0&&(l.partialSig=[]),l.partialSig.push(_t.partialSig.decode(d));break;case me.SIGHASH_TYPE:if(Lt("input",d.key,me.SIGHASH_TYPE),l.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");l.sighashType=_t.sighashType.decode(d);break;case me.REDEEM_SCRIPT:if(Lt("input",d.key,me.REDEEM_SCRIPT),l.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");l.redeemScript=_t.redeemScript.decode(d);break;case me.WITNESS_SCRIPT:if(Lt("input",d.key,me.WITNESS_SCRIPT),l.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");l.witnessScript=_t.witnessScript.decode(d);break;case me.BIP32_DERIVATION:l.bip32Derivation===void 0&&(l.bip32Derivation=[]),l.bip32Derivation.push(_t.bip32Derivation.decode(d));break;case me.FINAL_SCRIPTSIG:Lt("input",d.key,me.FINAL_SCRIPTSIG),l.finalScriptSig=_t.finalScriptSig.decode(d);break;case me.FINAL_SCRIPTWITNESS:Lt("input",d.key,me.FINAL_SCRIPTWITNESS),l.finalScriptWitness=_t.finalScriptWitness.decode(d);break;case me.POR_COMMITMENT:Lt("input",d.key,me.POR_COMMITMENT),l.porCommitment=_t.porCommitment.decode(d);break;case me.TAP_KEY_SIG:Lt("input",d.key,me.TAP_KEY_SIG),l.tapKeySig=_t.tapKeySig.decode(d);break;case me.TAP_SCRIPT_SIG:l.tapScriptSig===void 0&&(l.tapScriptSig=[]),l.tapScriptSig.push(_t.tapScriptSig.decode(d));break;case me.TAP_LEAF_SCRIPT:l.tapLeafScript===void 0&&(l.tapLeafScript=[]),l.tapLeafScript.push(_t.tapLeafScript.decode(d));break;case me.TAP_BIP32_DERIVATION:l.tapBip32Derivation===void 0&&(l.tapBip32Derivation=[]),l.tapBip32Derivation.push(_t.tapBip32Derivation.decode(d));break;case me.TAP_INTERNAL_KEY:Lt("input",d.key,me.TAP_INTERNAL_KEY),l.tapInternalKey=_t.tapInternalKey.decode(d);break;case me.TAP_MERKLE_ROOT:Lt("input",d.key,me.TAP_MERKLE_ROOT),l.tapMerkleRoot=_t.tapMerkleRoot.decode(d);break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(d)}a.push(l)}for(const f of ya(c)){const l={};for(const d of r[f])switch(gr.checkPubkey(d),d.key[0]){case pt.REDEEM_SCRIPT:if(Lt("output",d.key,pt.REDEEM_SCRIPT),l.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");l.redeemScript=gr.redeemScript.decode(d);break;case pt.WITNESS_SCRIPT:if(Lt("output",d.key,pt.WITNESS_SCRIPT),l.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");l.witnessScript=gr.witnessScript.decode(d);break;case pt.BIP32_DERIVATION:l.bip32Derivation===void 0&&(l.bip32Derivation=[]),l.bip32Derivation.push(gr.bip32Derivation.decode(d));break;case pt.TAP_INTERNAL_KEY:Lt("output",d.key,pt.TAP_INTERNAL_KEY),l.tapInternalKey=gr.tapInternalKey.decode(d);break;case pt.TAP_TREE:Lt("output",d.key,pt.TAP_TREE),l.tapTree=gr.tapTree.decode(d);break;case pt.TAP_BIP32_DERIVATION:l.tapBip32Derivation===void 0&&(l.tapBip32Derivation=[]),l.tapBip32Derivation.push(gr.tapBip32Derivation.decode(d));break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(d)}u.push(l)}return{globalMap:i,inputs:a,outputs:u}}function d_({globalMap:e,inputs:t,outputs:n}){const{globalKeyVals:r,inputKeyVals:i,outputKeyVals:s}=Df({globalMap:e,inputs:t,outputs:n}),o=Id(r),c=l=>l.length===0?[Uint8Array.from([0])]:l.map(Id),a=c(i),u=c(s),f=new Uint8Array(5);return f.set([112,115,98,116,255],0),at([f,o].concat(a,u))}const p_=(e,t)=>de(e.key,t.key);function Vu(e,t){const n=new Set,r=Object.entries(e).reduce((s,[o,c])=>{if(o==="unknownKeyVals")return s;const a=t[o];if(a===void 0)return s;const u=(Array.isArray(c)?c:[c]).map(a.encode);return u.map(l=>xe(l.key)).forEach(l=>{if(n.has(l))throw new Error("Serialize Error: Duplicate key: "+l);n.add(l)}),s.concat(u)},[]),i=e.unknownKeyVals?e.unknownKeyVals.filter(s=>!n.has(xe(s.key))):[];return r.concat(i).sort(p_)}function Df({globalMap:e,inputs:t,outputs:n}){return{globalKeyVals:Vu(e,Ul),inputKeyVals:t.map(r=>Vu(r,_t)),outputKeyVals:n.map(r=>Vu(r,gr))}}function y_(e){const t=e[0],n=Df(t),r=e.slice(1);if(r.length===0)throw new Error("Combine: Nothing to combine");const i=Od(t);if(i===void 0)throw new Error("Combine: Self missing transaction");const s=ss(n.globalKeyVals),o=n.inputKeyVals.map(ss),c=n.outputKeyVals.map(ss);for(const a of r){const u=Od(a);if(u===void 0||de(u.toBuffer(),i.toBuffer())!==0)throw new Error("Combine: One of the Psbts does not have the same transaction.");const f=Df(a);ss(f.globalKeyVals).forEach(Lu(s,n.globalKeyVals,f.globalKeyVals)),f.inputKeyVals.map(ss).forEach((g,m)=>g.forEach(Lu(o[m],n.inputKeyVals[m],f.inputKeyVals[m]))),f.outputKeyVals.map(ss).forEach((g,m)=>g.forEach(Lu(c[m],n.outputKeyVals[m],f.outputKeyVals[m])))}return Pg(i,{globalMapKeyVals:n.globalKeyVals,inputKeyVals:n.inputKeyVals,outputKeyVals:n.outputKeyVals})}function Lu(e,t,n){return r=>{if(e.has(r))return;const i=n.filter(s=>xe(s.key)===r)[0];t.push(i),e.add(r)}}function Od(e){return e.globalMap.unsignedTx}function ss(e){const t=new Set;return e.forEach(n=>{const r=xe(n.key);if(t.has(r))throw new Error("Combine: KeyValue Map keys should be unique");t.add(r)}),t}function Rt(e,t){const n=e[t];if(n===void 0)throw new Error(`No input #${t}`);return n}function Bo(e,t){const n=e[t];if(n===void 0)throw new Error(`No output #${t}`);return n}function $u(e,t,n){if(e.key[0]<n)throw new Error("Use the method for your specific key instead of addUnknownKeyVal*");if(t&&t.filter(r=>de(r.key,e.key)===0).length!==0)throw new Error(`Duplicate Key: ${xe(e.key)}`)}function Du(e){let t=0;return Object.keys(e).forEach(n=>{Number(isNaN(Number(n)))&&t++}),t}function g_(e,t){let n=!1;if(t.nonWitnessUtxo||t.witnessUtxo){const r=!!t.redeemScript,i=!!t.witnessScript,s=!r||!!t.finalScriptSig,o=!i||!!t.finalScriptWitness,c=!!t.finalScriptSig||!!t.finalScriptWitness;n=s&&o&&c}if(n===!1)throw new Error(`Input #${e} has too much or too little data to clean`)}function Bd(e,t,n,r){throw new Error(`Data for ${e} key ${t} is incorrect: Expected ${n} and got ${JSON.stringify(r)}`)}function Cl(e){return(t,n)=>{for(const r of Object.keys(t)){const i=t[r],{canAdd:s,canAddToArray:o,check:c,expected:a}=f_[e+"s"][r]||{},u=!!o;if(c)if(u){if(!Array.isArray(i)||n[r]&&!Array.isArray(n[r]))throw new Error(`Key type ${r} must be an array`);i.every(c)||Bd(e,r,a,i);const f=n[r]||[],l=new Set;if(!i.every(d=>o(f,d,l)))throw new Error("Can not add duplicate data to array");n[r]=f.concat(i)}else{if(c(i)||Bd(e,r,a,i),!s(n,i))throw new Error(`Can not add duplicate data to ${e}`);n[r]=i}}}}const m_=Cl("global"),Rg=Cl("input"),Ug=Cl("output");function w_(e,t){const n=e.length-1,r=Rt(e,n);Rg(t,r)}function b_(e,t){const n=e.length-1,r=Bo(e,n);Ug(t,r)}let Nd=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,n){const r=Ly(t);return this.fromBuffer(r,n)}static fromHex(t,n){const r=kr(t);return this.fromBuffer(r,n)}static fromBuffer(t,n){const r=h_(t,n),i=new this(r.globalMap.unsignedTx);return Object.assign(i,r),i}toBase64(){const t=this.toBuffer();return Z1(t)}toHex(){const t=this.toBuffer();return xe(t)}toBuffer(){return d_(this)}updateGlobal(t){return m_(t,this.globalMap),this}updateInput(t,n){const r=Rt(this.inputs,t);return Rg(n,r),this}updateOutput(t,n){const r=Bo(this.outputs,t);return Ug(n,r),this}addUnknownKeyValToGlobal(t){return $u(t,this.globalMap.unknownKeyVals,Du(nr)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,n){const r=Rt(this.inputs,t);return $u(n,r.unknownKeyVals,Du(me)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(n),this}addUnknownKeyValToOutput(t,n){const r=Bo(this.outputs,t);return $u(n,r.unknownKeyVals,Du(pt)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(n),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const n=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(n))throw new Error("unknownKeyVals must be an Array");return n.forEach(i=>this.addUnknownKeyValToInput(r,i)),w_(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const n=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(n))throw new Error("unknownKeyVals must be an Array");return n.forEach(i=>this.addUnknownKeyValToOutput(r,i)),b_(this.outputs,t),this}clearFinalizedInput(t){const n=Rt(this.inputs,t);g_(t,n);for(const r of Object.keys(n))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(r)||delete n[r];return this}combine(...t){const n=y_([this].concat(t));return Object.assign(this,n),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}};function Yi(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}const E_=Yi(Ga),__=Yi(ig),S_=Yi(oc),Ya=Yi(za),kd=Yi(uc),Cg=Yi(cc),Hg=Yi(fc);function ga(e){let t=new Uint8Array(0);function n(o){t=at([t,o])}function r(o){const c=t.length,a=Bn(o);t=at([t,new Uint8Array(a)]),li(o,t,c)}function i(o){r(o.length),n(o)}function s(o){r(o.length),o.forEach(i)}return s(e),t}function Fg(e,t){const n=Ar(e),r=e.slice(1,33),i=lt(t);if(i===null)throw new Error("Unknown script error");return i.findIndex(s=>typeof s=="number"?!1:de(e,s)===0||de(n,s)===0||de(r,s)===0)}function Za(e,t){return Fg(e,t)!==-1}function T_(e,t){return x_(e).some(r=>Mg(r,So.decode,t))}function Mg(e,t,n){const{hashType:r}=t(e),i=[];switch(r&gt.SIGHASH_ANYONECANPAY&&i.push("addInput"),r&31){case gt.SIGHASH_ALL:break;case gt.SIGHASH_SINGLE:case gt.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence");break}return i.indexOf(n)===-1}function x_(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=A_(e)}else t=e.partialSig;return t.map(n=>n.signature)}function A_(e){const t=e.finalScriptSig?lt(e.finalScriptSig)||[]:[],n=e.finalScriptWitness?lt(e.finalScriptWitness)||[]:[];return t.concat(n).filter(r=>r instanceof Uint8Array&&Ir(r)).map(r=>({signature:r}))}const zc=e=>e.length===32?e:e.slice(1,33);function Pd(e,t,n){const r=q_(t,e,n);try{const s=F_(t,r).concat(r.script).concat(r.controlBlock);return{finalScriptWitness:ga(s)}}catch(i){throw new Error(`Can not finalize taproot input #${e}: ${i}`)}}function kc(e,t){const n=t?Uint8Array.from([t]):Uint8Array.from([]);return at([e,n])}function Mn(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&Hg(e.witnessUtxo.script))}function ju(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t)}function Rd(e,t,n){U_(e,t,n),H_(e,t,n)}function Ud(e,t,n){C_(e,t,n),v_(e,t)}function v_(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const n=t.tapInternalKey||e.tapInternalKey,r=t.tapTree||e.tapTree;if(n){const{script:i}=e,s=I_(n,r);if(i&&de(s,i)!==0)throw new Error("Error adding output. Script or address mismatch.")}}function I_(e,t){const n=t&&O_(t.leaves),{output:r}=fc({internalPubkey:e,scriptTree:n});return r}function O_(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:R_(e)}function B_(e,t){return k_(e).some(r=>Mg(r,N_,t))}function N_(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||gt.SIGHASH_DEFAULT}}function k_(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(n=>n.signature)),!t.length){const n=P_(e.finalScriptWitness);n&&t.push(n)}return t}function P_(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function R_(e){let t;for(const n of e)if(t=jf(n,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function jf(e,t,n=0){if(n>T2)throw new Error("Max taptree depth exceeded.");if(e.depth===n)return t?void 0:{output:e.script,version:e.leafVersion};if(vl(t))return;const r=jf(e,t&&t[0],n+1);if(r)return[r,t&&t[1]];const i=jf(e,t&&t[1],n+1);if(i)return[t&&t[0],i]}function U_(e,t,n){const r=Mn(e)&&bs(t),i=bs(e)&&Mn(t),s=e===t&&Mn(t)&&bs(t);if(r||i||s)throw new Error(`Invalid arguments for Psbt.${n}. Cannot use both taproot and non-taproot fields.`)}function C_(e,t,n){const r=ju(e)&&bs(t),i=bs(e)&&ju(t),s=e===t&&ju(t)&&bs(t);if(r||i||s)throw new Error(`Invalid arguments for Psbt.${n}. Cannot use both taproot and non-taproot fields.`)}function H_(e,t,n){if(t.tapMerkleRoot){const r=(t.tapLeafScript||[]).every(s=>Ku(s,t.tapMerkleRoot)),i=(e.tapLeafScript||[]).every(s=>Ku(s,t.tapMerkleRoot));if(!r||!i)throw new Error(`Invalid arguments for Psbt.${n}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(i=>Ku(i,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${n}. Tapleaf not part of taptree.`)}function Ku(e,t){if(!t)return!0;const n=Er({output:e.script,version:e.leafVersion}),r=Vf(e.controlBlock,n);return de(r,t)===0}function F_(e,t){const n=Er({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(r=>de(r.leafHash,n)===0).map(r=>M_(t.script,r)).sort((r,i)=>i.positionInScript-r.positionInScript).map(r=>r.signature)}function M_(e,t){return Object.assign({positionInScript:Fg(t.pubkey,e)},t)}function q_(e,t,n){if(!e.tapScriptSig||!e.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${t}. No tapleaf script signature provided.`);const r=(e.tapLeafScript||[]).sort((i,s)=>i.controlBlock.length-s.controlBlock.length).find(i=>V_(i,e.tapScriptSig,n));if(!r)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return r}function V_(e,t,n){const r=Er({output:e.script,version:e.leafVersion});return(!n||de(r,n)===0)&&t.find(s=>de(s.leafHash,r)===0)!==void 0}function bs(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const L_={network:Pn,maximumFeeRate:5e3};class ma{data;static fromBase64(t,n={}){const r=Ly(t);return this.fromBuffer(r,n)}static fromHex(t,n={}){const r=kr(t);return this.fromBuffer(r,n)}static fromBuffer(t,n={}){const r=Nd.fromBuffer(t,$_),i=new ma(n,r);return W_(i.__CACHE.__TX,i.__CACHE),i}__CACHE;opts;constructor(t={},n=new Nd(new qg)){this.data=n,this.opts=Object.assign({},L_,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},this.data.inputs.length===0&&this.setVersion(2);const r=(i,s,o,c)=>Object.defineProperty(i,s,{enumerable:o,writable:c});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map(t=>({hash:Sd(t.hash),index:t.index,sequence:t.sequence}))}get txOutputs(){return this.__CACHE.__TX.outs.map(t=>{let n;try{n=N2(t.script,this.opts.network)}catch{}return{script:Sd(t.script),value:t.value,address:n}})}combine(...t){return this.data.combine(...t.map(n=>n.data)),this}clone(){const t=ma.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){Pc(t),this.opts.maximumFeeRate=t}setVersion(t){Pc(t),Qs(this.data.inputs,"setVersion");const n=this.__CACHE;return n.__TX.version=t,n.__EXTRACTED_TX=void 0,this}setLocktime(t){Pc(t),Qs(this.data.inputs,"setLocktime");const n=this.__CACHE;return n.__TX.locktime=t,n.__EXTRACTED_TX=void 0,this}setInputSequence(t,n){Pc(n),Qs(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=n,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach(n=>this.addInput(n)),this}addInput(t){if(arguments.length>1||!t||t.hash===void 0||t.index===void 0)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");Rd(t,t,"addInput"),Qs(this.data.inputs,"addInput"),t.witnessScript&&wa(t.witnessScript);const n=this.__CACHE;this.data.addInput(t);const r=n.__TX.ins[n.__TX.ins.length-1];$g(n,r);const i=this.data.inputs.length-1,s=this.data.inputs[i];return s.nonWitnessUtxo&&Gf(this.__CACHE,s,i),n.__FEE=void 0,n.__FEE_RATE=void 0,n.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach(n=>this.addOutput(n)),this}addOutput(t){if(arguments.length>1||!t||t.value===void 0||t.address===void 0&&t.script===void 0)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");Qs(this.data.inputs,"addOutput");const{address:n}=t;if(typeof n=="string"){const{network:i}=this.opts,s=Ag(n,i);t=Object.assign({},t,{script:s})}Ud(t,t,"addOutput");const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(Vg))throw new Error("Not finalized");const n=this.__CACHE;if(t||j_(this,n,this.opts),n.__EXTRACTED_TX)return n.__EXTRACTED_TX;const r=n.__TX.clone();return Xg(this.data.inputs,r,n,!0),r}getFeeRate(){return qd("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return qd("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Rt(this.data.inputs,0),eo(this.data.inputs.length).forEach(t=>this.finalizeInput(t)),this}finalizeInput(t,n){const r=Rt(this.data.inputs,t);return Mn(r)?this._finalizeTaprootInput(t,r,void 0,n):this._finalizeInput(t,r,n)}finalizeTaprootInput(t,n,r=Pd){const i=Rt(this.data.inputs,t);if(Mn(i))return this._finalizeTaprootInput(t,i,n,r);throw new Error(`Cannot finalize input #${t}. Not Taproot.`)}_finalizeInput(t,n,r=X_){const{script:i,isP2SH:s,isP2WSH:o,isSegwit:c}=J_(t,n,this.__CACHE);if(!i)throw new Error(`No script found for input #${t}`);K_(n);const{finalScriptSig:a,finalScriptWitness:u}=r(t,n,i,c,s,o);if(a&&this.data.updateInput(t,{finalScriptSig:a}),u&&this.data.updateInput(t,{finalScriptWitness:u}),!a&&!u)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}_finalizeTaprootInput(t,n,r,i=Pd){if(!n.witnessUtxo)throw new Error(`Cannot finalize input #${t}. Missing withness utxo.`);if(n.tapKeySig){const s=fc({output:n.witnessUtxo.script,signature:n.tapKeySig}),o=ga(s.witness);this.data.updateInput(t,{finalScriptWitness:o})}else{const{finalScriptWitness:s}=i(t,n,r);this.data.updateInput(t,{finalScriptWitness:s})}return this.data.clearFinalizedInput(t),this}getInputType(t){const n=Rt(this.data.inputs,t),r=zg(t,n,this.__CACHE),i=Qa(r,t,"input",n.redeemScript||rS(n.finalScriptSig),n.witnessScript||iS(n.finalScriptWitness)),s=i.type==="raw"?"":i.type+"-",o=Zg(i.meaningfulScript);return s+o}inputHasPubkey(t,n){const r=Rt(this.data.inputs,t);return tS(n,r,t,this.__CACHE)}inputHasHDKey(t,n){const r=Rt(this.data.inputs,t),i=Hd(n);return!!r.bip32Derivation&&r.bip32Derivation.some(i)}outputHasPubkey(t,n){const r=Bo(this.data.outputs,t);return nS(n,r,t,this.__CACHE)}outputHasHDKey(t,n){const r=Bo(this.data.outputs,t),i=Hd(n);return!!r.bip32Derivation&&r.bip32Derivation.some(i)}validateSignaturesOfAllInputs(t){return Rt(this.data.inputs,0),eo(this.data.inputs.length).map(r=>this.validateSignaturesOfInput(r,t)).reduce((r,i)=>i===!0&&r,!0)}validateSignaturesOfInput(t,n,r){const i=this.data.inputs[t];return Mn(i)?this.validateSignaturesOfTaprootInput(t,n,r):this._validateSignaturesOfInput(t,n,r)}_validateSignaturesOfInput(t,n,r){const i=this.data.inputs[t],s=(i||{}).partialSig;if(!i||!s||s.length<1)throw new Error("No signatures to validate");if(typeof n!="function")throw new Error("Need validator function to validate signatures");const o=r?s.filter(l=>de(l.pubkey,r)===0):s;if(o.length<1)throw new Error("No signatures for this pubkey");const c=[];let a,u,f;for(const l of o){const d=So.decode(l.signature),{hash:y,script:g}=f!==d.hashType?jg(t,Object.assign({},i,{sighashType:d.hashType}),this.__CACHE,!0):{hash:a,script:u};f=d.hashType,a=y,u=g,Lg(l.pubkey,g,"verify"),c.push(n(l.pubkey,y,d.signature))}return c.every(l=>l===!0)}validateSignaturesOfTaprootInput(t,n,r){const i=this.data.inputs[t],s=(i||{}).tapKeySig,o=(i||{}).tapScriptSig;if(!i&&!s&&!(o&&!o.length))throw new Error("No signatures to validate");if(typeof n!="function")throw new Error("Need validator function to validate signatures");r=r&&zc(r);const c=r?Kf(t,i,this.data.inputs,r,this.__CACHE):Y_(t,i,this.data.inputs,this.__CACHE);if(!c.length)throw new Error("No signatures for this pubkey");const a=c.find(f=>!f.leafHash);let u=0;if(s&&a){if(!n(a.pubkey,a.hash,Ld(s)))return!1;u++}if(o)for(const f of o){const l=c.find(d=>de(d.pubkey,f.pubkey)===0);if(l){if(!n(f.pubkey,l.hash,Ld(f.signature)))return!1;u++}}return u>0}signAllInputsHD(t,n=[gt.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const i of eo(this.data.inputs.length))try{this.signInputHD(i,t,n),r.push(!0)}catch{r.push(!1)}if(r.every(i=>i===!1))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,n=[gt.SIGHASH_ALL]){return new Promise((r,i)=>{if(!t||!t.publicKey||!t.fingerprint)return i(new Error("Need HDSigner to sign input"));const s=[],o=[];for(const c of eo(this.data.inputs.length))o.push(this.signInputHDAsync(c,t,n).then(()=>{s.push(!0)},()=>{s.push(!1)}));return Promise.all(o).then(()=>{if(s.every(c=>c===!1))return i(new Error("No inputs were signed"));r()})})}signInputHD(t,n,r=[gt.SIGHASH_ALL]){if(!n||!n.publicKey||!n.fingerprint)throw new Error("Need HDSigner to sign input");return $d(t,this.data.inputs,n).forEach(s=>this.signInput(t,s,r)),this}signInputHDAsync(t,n,r=[gt.SIGHASH_ALL]){return new Promise((i,s)=>{if(!n||!n.publicKey||!n.fingerprint)return s(new Error("Need HDSigner to sign input"));const c=$d(t,this.data.inputs,n).map(a=>this.signInputAsync(t,a,r));return Promise.all(c).then(()=>{i()}).catch(s)})}signAllInputs(t,n){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const i of eo(this.data.inputs.length))try{this.signInput(i,t,n),r.push(!0)}catch{r.push(!1)}if(r.every(i=>i===!1))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,n){return new Promise((r,i)=>{if(!t||!t.publicKey)return i(new Error("Need Signer to sign input"));const s=[],o=[];for(const[c]of this.data.inputs.entries())o.push(this.signInputAsync(c,t,n).then(()=>{s.push(!0)},()=>{s.push(!1)}));return Promise.all(o).then(()=>{if(s.every(c=>c===!1))return i(new Error("No inputs were signed"));r()})})}signInput(t,n,r){if(!n||!n.publicKey)throw new Error("Need Signer to sign input");const i=Rt(this.data.inputs,t);return Mn(i)?this._signTaprootInput(t,i,n,void 0,r):this._signInput(t,n,r)}signTaprootInput(t,n,r,i){if(!n||!n.publicKey)throw new Error("Need Signer to sign input");const s=Rt(this.data.inputs,t);if(Mn(s))return this._signTaprootInput(t,s,n,r,i);throw new Error(`Input #${t} is not of type Taproot.`)}_signInput(t,n,r=[gt.SIGHASH_ALL]){const{hash:i,sighashType:s}=Vd(this.data.inputs,t,n.publicKey,this.__CACHE,r),o=[{pubkey:n.publicKey,signature:So.encode(n.sign(i),s)}];return this.data.updateInput(t,{partialSig:o}),this}_signTaprootInput(t,n,r,i,s=[gt.SIGHASH_DEFAULT]){const o=this.checkTaprootHashesForSig(t,n,r,i,s),c=o.filter(u=>!u.leafHash).map(u=>kc(r.signSchnorr(u.hash),n.sighashType))[0],a=o.filter(u=>!!u.leafHash).map(u=>({pubkey:zc(r.publicKey),signature:kc(r.signSchnorr(u.hash),n.sighashType),leafHash:u.leafHash}));return c&&this.data.updateInput(t,{tapKeySig:c}),a.length&&this.data.updateInput(t,{tapScriptSig:a}),this}signInputAsync(t,n,r){return Promise.resolve().then(()=>{if(!n||!n.publicKey)throw new Error("Need Signer to sign input");const i=Rt(this.data.inputs,t);return Mn(i)?this._signTaprootInputAsync(t,i,n,void 0,r):this._signInputAsync(t,n,r)})}signTaprootInputAsync(t,n,r,i){return Promise.resolve().then(()=>{if(!n||!n.publicKey)throw new Error("Need Signer to sign input");const s=Rt(this.data.inputs,t);if(Mn(s))return this._signTaprootInputAsync(t,s,n,r,i);throw new Error(`Input #${t} is not of type Taproot.`)})}_signInputAsync(t,n,r=[gt.SIGHASH_ALL]){const{hash:i,sighashType:s}=Vd(this.data.inputs,t,n.publicKey,this.__CACHE,r);return Promise.resolve(n.sign(i)).then(o=>{const c=[{pubkey:n.publicKey,signature:So.encode(o,s)}];this.data.updateInput(t,{partialSig:c})})}async _signTaprootInputAsync(t,n,r,i,s=[gt.SIGHASH_DEFAULT]){const o=this.checkTaprootHashesForSig(t,n,r,i,s),c=[],a=o.filter(f=>!f.leafHash)[0];if(a){const f=Promise.resolve(r.signSchnorr(a.hash)).then(l=>({tapKeySig:kc(l,n.sighashType)}));c.push(f)}const u=o.filter(f=>!!f.leafHash);if(u.length){const f=u.map(l=>Promise.resolve(r.signSchnorr(l.hash)).then(d=>({tapScriptSig:[{pubkey:zc(r.publicKey),signature:kc(d,n.sighashType),leafHash:l.leafHash}]})));c.push(...f)}return Promise.all(c).then(f=>{f.forEach(l=>this.data.updateInput(t,l))})}checkTaprootHashesForSig(t,n,r,i,s){if(typeof r.signSchnorr!="function")throw new Error(`Need Schnorr Signer to sign taproot input #${t}.`);const o=Kf(t,n,this.data.inputs,r.publicKey,this.__CACHE,i,s);if(!o||!o.length)throw new Error(`Can not sign for input #${t} with the key ${xe(r.publicKey)}`);return o}toBuffer(){return Gu(this.__CACHE),this.data.toBuffer()}toHex(){return Gu(this.__CACHE),this.data.toHex()}toBase64(){return Gu(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,n){return n.witnessScript&&wa(n.witnessScript),Rd(this.data.inputs[t],n,"updateInput"),this.data.updateInput(t,n),n.nonWitnessUtxo&&Gf(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,n){const r=this.data.outputs[t];return Ud(r,n,"updateOutput"),this.data.updateOutput(t,n),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,n){return this.data.addUnknownKeyValToInput(t,n),this}addUnknownKeyValToOutput(t,n){return this.data.addUnknownKeyValToOutput(t,n),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}const $_=e=>new qg(e);class qg{tx;constructor(t=Uint8Array.from([2,0,0,0,0,0,0,0,0,0])){this.tx=gt.fromBuffer(t),G_(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(t.hash===void 0||t.index===void 0||!(t.hash instanceof Uint8Array)&&typeof t.hash!="string"||typeof t.index!="number")throw new Error("Error adding input.");const n=typeof t.hash=="string"?Nl(kr(t.hash)):t.hash;this.tx.addInput(n,t.index,t.sequence)}addOutput(t){if(t.script===void 0||t.value===void 0||!(t.script instanceof Uint8Array)||typeof t.value!="bigint")throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function D_(e,t,n){switch(n){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Cd(1,e.partialSig);case"multisig":const r=Ga({output:t});return Cd(r.m,e.partialSig,r.pubkeys);default:return!1}}function Gu(e){if(e.__UNSAFE_SIGN_NONSEGWIT!==!1)throw new Error("Not BIP174 compliant, can not export")}function Cd(e,t,n){if(!t)return!1;let r;if(n?r=n.map(i=>{const s=sS(i);return t.find(o=>de(o.pubkey,s)===0)}).filter(i=>!!i):r=t,r.length>e)throw new Error("Too many signatures");return r.length===e}function Vg(e){return!!e.finalScriptSig||!!e.finalScriptWitness}function Hd(e){return t=>!(de(e.fingerprint,t.masterFingerprint)||de(e.derivePath(t.path).publicKey,t.pubkey))}function Pc(e){if(typeof e!="number"||e!==Math.floor(e)||e>4294967295||e<0)throw new Error("Invalid 32 bit integer")}function j_(e,t,n){const r=t.__FEE_RATE||e.getFeeRate(),i=t.__EXTRACTED_TX.virtualSize(),s=r*i;if(r>=n.maximumFeeRate)throw new Error(`Warning: You are paying around ${(s/1e8).toFixed(8)} in fees, which is ${r} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}function Qs(e,t){e.forEach(n=>{if(Mn(n)?B_(n,t):T_(n,t))throw new Error("Can not modify transaction, signatures exist.")})}function K_(e){if(!e.sighashType||!e.partialSig)return;const{partialSig:t,sighashType:n}=e;t.forEach(r=>{const{hashType:i}=So.decode(r.signature);if(n!==i)throw new Error("Signature sighash does not match input sighash type")})}function Lg(e,t,n){if(!Za(e,t))throw new Error(`Can not ${n} for this input with the key ${xe(e)}`)}function G_(e){if(!e.ins.every(n=>n.script&&n.script.length===0&&n.witness&&n.witness.length===0))throw new Error("Format Error: Transaction ScriptSigs are not empty")}function W_(e,t){e.ins.forEach(n=>{$g(t,n)})}function $g(e,t){const n=xe(Nl(Uint8Array.from(t.hash)))+":"+t.index;if(e.__TX_IN_CACHE[n])throw new Error("Duplicate input detected.");e.__TX_IN_CACHE[n]=1}function Dg(e,t){return(n,r,i,s)=>{const o=e({redeem:{output:i}}).output;if(de(r,o))throw new Error(`${t} for ${s} #${n} doesn't match the scriptPubKey in the prevout`)}}const Fd=Dg(cc,"Redeem script"),Md=Dg(uc,"Witness script");function qd(e,t,n,r){if(!n.every(Vg))throw new Error(`PSBT must be finalized to calculate ${t}`);if(e==="__FEE_RATE"&&r.__FEE_RATE)return r.__FEE_RATE;if(e==="__FEE"&&r.__FEE)return r.__FEE;let i,s=!0;if(r.__EXTRACTED_TX?(i=r.__EXTRACTED_TX,s=!1):i=r.__TX.clone(),Xg(n,i,r,s),e==="__FEE_RATE")return r.__FEE_RATE;if(e==="__FEE")return r.__FEE}function X_(e,t,n,r,i,s){const o=Zg(n);if(!D_(t,n,o))throw new Error(`Can not finalize input #${e}`);return z_(n,o,t.partialSig,r,i,s)}function z_(e,t,n,r,i,s){let o,c;const a=Z_(e,t,n),u=s?uc({redeem:a}):null,f=i?cc({redeem:u||a}):null;return r?(u?c=ga(u.witness):c=ga(a.witness),f&&(o=f.input)):f?o=f.input:o=a.input,{finalScriptSig:o,finalScriptWitness:c}}function Vd(e,t,n,r,i){const s=Rt(e,t),{hash:o,sighashType:c,script:a}=jg(t,s,r,!1,i);return Lg(n,a,"sign"),{hash:o,sighashType:c}}function jg(e,t,n,r,i){const s=n.__TX,o=t.sighashType||gt.SIGHASH_ALL;Gg(o,i);let c,a;if(t.nonWitnessUtxo){const l=Ja(n,t,e),d=s.ins[e].hash,y=l.getHash();if(de(d,y)!==0)throw new Error(`Non-witness UTXO hash for input #${e} doesn't match the hash specified in the prevout`);const g=s.ins[e].index;a=l.outs[g]}else if(t.witnessUtxo)a=t.witnessUtxo;else throw new Error("Need a Utxo input item for signing");const{meaningfulScript:u,type:f}=Qa(a.script,e,"input",t.redeemScript,t.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)c=s.hashForWitnessV0(e,u,a.value,o);else if(Ya(u)){const l=oc({hash:u.slice(2)}).output;c=s.hashForWitnessV0(e,l,a.value,o)}else{if(t.nonWitnessUtxo===void 0&&n.__UNSAFE_SIGN_NONSEGWIT===!1)throw new Error(`Input #${e} has witnessUtxo but non-segwit script: ${xe(u)}`);!r&&n.__UNSAFE_SIGN_NONSEGWIT!==!1&&console.warn(`Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as Psbt's predecessor (TransactionBuilder - now removed) when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.
9
+ `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};function j1(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 n=e[5+t];return!(n===0||6+t+n!==e.length||e[4]&128||t>1&&e[4]===0&&!(e[5]&128)||e[t+6]&128||n>1&&e[t+6]===0&&!(e[t+7]&128))}function K1(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 n=e[5+t];if(n===0)throw new Error("S length is zero");if(6+t+n!==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(n>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)}}function G1(e,t){const n=e.length,r=t.length;if(n===0)throw new Error("R length is zero");if(r===0)throw new Error("S length is zero");if(n>33)throw new Error("R length is too long");if(r>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(n>1&&e[0]===0&&!(e[1]&128))throw new Error("R value excessively padded");if(r>1&&t[0]===0&&!(t[1]&128))throw new Error("S value excessively padded");const i=new Uint8Array(6+n+r);return i[0]=48,i[1]=i.length-2,i[2]=2,i[3]=e.length,i.set(e,4),i[4+n]=2,i[5+n]=t.length,i.set(t,6+n),i}const Ge={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},My={};for(const e of Object.keys(Ge)){const t=Ge[e];My[t]=e}const aa="0123456789abcdefABCDEF",ua=aa.split("").map(e=>e.codePointAt(0)),fa=Array(256).fill(!0).map((e,t)=>{const n=String.fromCodePoint(t),r=aa.indexOf(n);return r<0?void 0:r<16?r:r-6}),qy=new TextEncoder,Vy=new TextDecoder;function W1(e){return Vy.decode(e)}function X1(e){return qy.encode(e)}function at(e){const t=e.reduce((i,s)=>i+s.length,0),n=new Uint8Array(t);let r=0;for(const i of e)n.set(i,r),r+=i.length;return n}function xe(e){const t=e||new Uint8Array;return t.length>512?Y1(t):z1(t)}function z1(e){let t="";for(let n=0;n<e.length;++n)t+=aa[fa[ua[e[n]>>4]]],t+=aa[fa[ua[e[n]&15]]];return t}function Y1(e){const t=new Uint8Array(e.length*2);for(let n=0;n<e.length;++n)t[n*2]=ua[e[n]>>4],t[n*2+1]=ua[e[n]&15];return Vy.decode(t)}function kr(e){const t=qy.encode(e||""),n=new Uint8Array(Math.floor(t.length/2));let r;for(r=0;r<n.length;r++){const i=fa[t[r*2]],s=fa[t[r*2+1]];if(i===void 0||s===void 0)break;n[r]=i<<4|s}return r===n.length?n:n.slice(0,r)}function Z1(e){return btoa(String.fromCharCode(...e))}function Ly(e){const t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function de(e,t){const n=Math.min(e.length,t.length);for(let r=0;r<n;++r)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return e.length===t.length?0:e.length>t.length?1:-1}function bn(e,t,n){if(t+1>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n>255)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= 255. Received ${n}`);return e[t]=n,t+1}function J1(e,t,n,r){if(t+2>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>65535)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= 65535. Received ${n}`);return r==="LE"?(e[t]=n&255,e[t+1]=n>>8&255):(e[t]=n>>8&255,e[t+1]=n&255),t+2}function rc(e,t,n,r){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>4294967295)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${4294967295}. Received ${n}`);return r==="LE"?(e[t]=n&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255):(e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255),t+4}function Q1(e,t,n,r){if(t+8>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>0xffffffffffffffffn)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${n}`);return r==="LE"?(e[t]=Number(n&0xffn),e[t+1]=Number(n>>8n&0xffn),e[t+2]=Number(n>>16n&0xffn),e[t+3]=Number(n>>24n&0xffn),e[t+4]=Number(n>>32n&0xffn),e[t+5]=Number(n>>40n&0xffn),e[t+6]=Number(n>>48n&0xffn),e[t+7]=Number(n>>56n&0xffn)):(e[t]=Number(n>>56n&0xffn),e[t+1]=Number(n>>48n&0xffn),e[t+2]=Number(n>>40n&0xffn),e[t+3]=Number(n>>32n&0xffn),e[t+4]=Number(n>>24n&0xffn),e[t+5]=Number(n>>16n&0xffn),e[t+6]=Number(n>>8n&0xffn),e[t+7]=Number(n&0xffn)),t+8}function vr(e,t){if(t+1>e.length)throw new Error("Offset is outside the bounds of Uint8Array");return e[t]}function eb(e,t,n){if(t+2>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){let r=0;return r=(r<<8)+e[t+1],r=(r<<8)+e[t],r}else{let r=0;return r=(r<<8)+e[t],r=(r<<8)+e[t+1],r}}function qs(e,t,n){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){let r=0;return r=(r<<8)+e[t+3]>>>0,r=(r<<8)+e[t+2]>>>0,r=(r<<8)+e[t+1]>>>0,r=(r<<8)+e[t]>>>0,r}else{let r=0;return r=(r<<8)+e[t]>>>0,r=(r<<8)+e[t+1]>>>0,r=(r<<8)+e[t+2]>>>0,r=(r<<8)+e[t+3]>>>0,r}}function $y(e,t,n,r){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n>2147483647||n<-2147483648)throw new Error(`The value of "value" is out of range. It must be >= -2147483648 and <= 2147483647. Received ${n}`);return r=r.toUpperCase(),r==="LE"?(e[t]=n&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255):(e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255),t+4}function Dy(e,t,n,r){if(t+8>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n>0x7fffffffffffffffn||n<-0x8000000000000000n)throw new Error(`The value of "value" is out of range. It must be >= ${-0x8000000000000000n} and <= ${0x7fffffffffffffffn}. Received ${n}`);return r=r.toUpperCase(),r==="LE"?(e[t]=Number(n&0xffn),e[t+1]=Number(n>>8n&0xffn),e[t+2]=Number(n>>16n&0xffn),e[t+3]=Number(n>>24n&0xffn),e[t+4]=Number(n>>32n&0xffn),e[t+5]=Number(n>>40n&0xffn),e[t+6]=Number(n>>48n&0xffn),e[t+7]=Number(n>>56n&0xffn)):(e[t]=Number(n>>56n&0xffn),e[t+1]=Number(n>>48n&0xffn),e[t+2]=Number(n>>40n&0xffn),e[t+3]=Number(n>>32n&0xffn),e[t+4]=Number(n>>24n&0xffn),e[t+5]=Number(n>>16n&0xffn),e[t+6]=Number(n>>8n&0xffn),e[t+7]=Number(n&0xffn)),t+8}function tb(e,t,n){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){const r=e[t]+(e[t+1]<<8)+(e[t+2]<<16)+(e[t+3]<<24>>>0);return e[t+3]<=127?r:r-4294967296}else{const r=(e[t]<<24>>>0)+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];return e[t]<=127?r:r-4294967296}}function jy(e,t,n){if(t+8>e.length)throw new Error("Offset is outside the bounds of Uint8Array");n=n.toUpperCase();let r=0n;if(n==="LE")return r=(r<<8n)+BigInt(e[t+7]),r=(r<<8n)+BigInt(e[t+6]),r=(r<<8n)+BigInt(e[t+5]),r=(r<<8n)+BigInt(e[t+4]),r=(r<<8n)+BigInt(e[t+3]),r=(r<<8n)+BigInt(e[t+2]),r=(r<<8n)+BigInt(e[t+1]),r=(r<<8n)+BigInt(e[t]),e[t+7]<=127?r:r-0x10000000000000000n;{let i=0n;return i=(i<<8n)+BigInt(e[t]),i=(i<<8n)+BigInt(e[t+1]),i=(i<<8n)+BigInt(e[t+2]),i=(i<<8n)+BigInt(e[t+3]),i=(i<<8n)+BigInt(e[t+4]),i=(i<<8n)+BigInt(e[t+5]),i=(i<<8n)+BigInt(e[t+6]),i=(i<<8n)+BigInt(e[t+7]),e[t]<=127?i:i-0x10000000000000000n}}function Ky(e){return e<Ge.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}function nb(e,t,n){const r=Ky(t);return r===1?bn(e,n,t):r===2?(bn(e,n,Ge.OP_PUSHDATA1),bn(e,n+1,t)):r===3?(bn(e,n,Ge.OP_PUSHDATA2),J1(e,n+1,t,"LE")):(bn(e,n,Ge.OP_PUSHDATA4),rc(e,n+1,t,"LE")),r}function rb(e,t){const n=vr(e,t);let r,i;if(n<Ge.OP_PUSHDATA1)r=n,i=1;else if(n===Ge.OP_PUSHDATA1){if(t+2>e.length)return null;r=vr(e,t+1),i=2}else if(n===Ge.OP_PUSHDATA2){if(t+3>e.length)return null;r=eb(e,t+1,"LE"),i=3}else{if(t+5>e.length)return null;if(n!==Ge.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=qs(e,t+1,"LE"),i=5}return{opcode:n,number:r,size:i}}function ib(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function sb(e){let t=Math.abs(e);const n=ib(t),r=new Uint8Array(n),i=e<0;for(let s=0;s<n;++s)bn(r,s,t&255),t>>=8;return r[n-1]&128?bn(r,n-1,i?128:0):i&&(r[n-1]|=128),r}var Uu;function ob(e){return{lang:e?.lang??Uu?.lang,message:e?.message,abortEarly:e?.abortEarly??Uu?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Uu?.abortPipeEarly}}var cb;function ab(e){return cb?.get(e)}var ub;function fb(e){return ub?.get(e)}var lb;function hb(e,t){return lb?.get(e)?.get(t)}function vo(e){const t=typeof e;return t==="string"?`"${e}"`:t==="number"||t==="bigint"||t==="boolean"?`${e}`:t==="object"||t==="function"?(e&&Object.getPrototypeOf(e)?.constructor?.name)??"null":t}function Gt(e,t,n,r,i){const s=i&&"input"in i?i.input:n.value,o=i?.expected??e.expects??null,c=i?.received??vo(s),a={kind:e.kind,type:e.type,input:s,expected:o,received:c,message:`Invalid ${t}: ${o?`Expected ${o} but r`:"R"}eceived ${c}`,requirement:e.requirement,path:i?.path,issues:i?.issues,lang:r.lang,abortEarly:r.abortEarly,abortPipeEarly:r.abortPipeEarly},u=e.kind==="schema",f=i?.message??e.message??hb(e.reference,a.lang)??(u?fb(a.lang):null)??r.message??ab(a.lang);f&&(a.message=typeof f=="function"?f(a):f),u&&(n.typed=!1),n.issues?n.issues.push(a):n.issues=[a]}function db(e,t){const n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}var pb=class extends Error{issues;constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function Gy(e,t){return{kind:"validation",type:"every_item",reference:Gy,async:!1,expects:null,requirement:e,message:t,_run(n,r){return n.typed&&!n.value.every(this.requirement)&&Gt(this,"item",n,r),n}}}function Tl(e){return{kind:"validation",type:"integer",reference:Tl,async:!1,expects:null,requirement:Number.isInteger,message:e,_run(t,n){return t.typed&&!this.requirement(t.value)&&Gt(this,"integer",t,n),t}}}function Wy(e,t){return{kind:"validation",type:"length",reference:Wy,async:!1,expects:`${e}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value.length!==this.requirement&&Gt(this,"length",n,r,{received:`${n.value.length}`}),n}}}function $a(e,t){return{kind:"validation",type:"max_value",reference:$a,async:!1,expects:`<=${e instanceof Date?e.toJSON():vo(e)}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value>this.requirement&&Gt(this,"value",n,r,{received:n.value instanceof Date?n.value.toJSON():vo(n.value)}),n}}}function Da(e,t){return{kind:"validation",type:"min_value",reference:Da,async:!1,expects:`>=${e instanceof Date?e.toJSON():vo(e)}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value<this.requirement&&Gt(this,"value",n,r,{received:n.value instanceof Date?n.value.toJSON():vo(n.value)}),n}}}function Xy(e,t){return{kind:"validation",type:"regex",reference:Xy,async:!1,expects:`${e}`,requirement:e,message:t,_run(n,r){return n.typed&&!this.requirement.test(n.value)&&Gt(this,"format",n,r),n}}}function xl(e,t,n){return typeof e.default=="function"?e.default(t,n):e.default}function ja(e,t){return!e._run({typed:!1,value:t},{abortEarly:!0}).issues}function zy(){return{kind:"schema",type:"any",reference:zy,expects:"any",async:!1,_run(e){return e.typed=!0,e}}}function dn(e,t){return{kind:"schema",type:"array",reference:dn,expects:"Array",async:!1,item:e,message:t,_run(n,r){const i=n.value;if(Array.isArray(i)){n.typed=!0,n.value=[];for(let s=0;s<i.length;s++){const o=i[s],c=this.item._run({typed:!1,value:o},r);if(c.issues){const a={type:"array",origin:"value",input:i,key:s,value:o};for(const u of c.issues)u.path?u.path.unshift(a):u.path=[a],n.issues?.push(u);if(n.issues||(n.issues=c.issues),r.abortEarly){n.typed=!1;break}}c.typed||(n.typed=!1),n.value.push(c.value)}}else Gt(this,"type",n,r);return n}}}function Yy(e){return{kind:"schema",type:"bigint",reference:Yy,expects:"bigint",async:!1,message:e,_run(t,n){return typeof t.value=="bigint"?t.typed=!0:Gt(this,"type",t,n),t}}}function Kn(e,t){return{kind:"schema",type:"custom",reference:Kn,expects:"unknown",async:!1,check:e,message:t,_run(n,r){return this.check(n.value)?n.typed=!0:Gt(this,"type",n,r),n}}}function Ka(e,t){return{kind:"schema",type:"instance",reference:Ka,expects:e.name,async:!1,class:e,message:t,_run(n,r){return n.value instanceof this.class?n.typed=!0:Gt(this,"type",n,r),n}}}function Mf(e,...t){const n={kind:"schema",type:"nullable",reference:Mf,expects:`(${e.expects} | null)`,async:!1,wrapped:e,_run(r,i){return r.value===null&&("default"in this&&(r.value=xl(this,r,i)),r.value===null)?(r.typed=!0,r):this.wrapped._run(r,i)}};return 0 in t&&(n.default=t[0]),n}function Zy(e,...t){const n={kind:"schema",type:"nullish",reference:Zy,expects:`(${e.expects} | null | undefined)`,async:!1,wrapped:e,_run(r,i){return(r.value===null||r.value===void 0)&&("default"in this&&(r.value=xl(this,r,i)),r.value===null||r.value===void 0)?(r.typed=!0,r):this.wrapped._run(r,i)}};return 0 in t&&(n.default=t[0]),n}function ln(e){return{kind:"schema",type:"number",reference:ln,expects:"number",async:!1,message:e,_run(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:Gt(this,"type",t,n),t}}}function Et(e,t){return{kind:"schema",type:"object",reference:Et,expects:"Object",async:!1,entries:e,message:t,_run(n,r){const i=n.value;if(i&&typeof i=="object"){n.typed=!0,n.value={};for(const s in this.entries){const o=i[s],c=this.entries[s]._run({typed:!1,value:o},r);if(c.issues){const a={type:"object",origin:"value",input:i,key:s,value:o};for(const u of c.issues)u.path?u.path.unshift(a):u.path=[a],n.issues?.push(u);if(n.issues||(n.issues=c.issues),r.abortEarly){n.typed=!1;break}}c.typed||(n.typed=!1),(c.value!==void 0||s in i)&&(n.value[s]=c.value)}}else Gt(this,"type",n,r);return n}}}function la(e,...t){const n={kind:"schema",type:"optional",reference:la,expects:`(${e.expects} | undefined)`,async:!1,wrapped:e,_run(r,i){return r.value===void 0&&("default"in this&&(r.value=xl(this,r,i)),r.value===void 0)?(r.typed=!0,r):this.wrapped._run(r,i)}};return 0 in t&&(n.default=t[0]),n}function zi(e){return{kind:"schema",type:"string",reference:zi,expects:"string",async:!1,message:e,_run(t,n){return typeof t.value=="string"?t.typed=!0:Gt(this,"type",t,n),t}}}function Qn(e,t){return{kind:"schema",type:"tuple",reference:Qn,expects:"Array",async:!1,items:e,message:t,_run(n,r){const i=n.value;if(Array.isArray(i)){n.typed=!0,n.value=[];for(let s=0;s<this.items.length;s++){const o=i[s],c=this.items[s]._run({typed:!1,value:o},r);if(c.issues){const a={type:"array",origin:"value",input:i,key:s,value:o};for(const u of c.issues)u.path?u.path.unshift(a):u.path=[a],n.issues?.push(u);if(n.issues||(n.issues=c.issues),r.abortEarly){n.typed=!1;break}}c.typed||(n.typed=!1),n.value.push(c.value)}}else Gt(this,"type",n,r);return n}}}function id(e){let t;if(e)for(const n of e)t?t.push(...n.issues):t=n.issues;return t}function Al(e,t){return{kind:"schema",type:"union",reference:Al,expects:db(e.map(n=>n.expects),"|"),async:!1,options:e,message:t,_run(n,r){let i,s,o;for(const c of this.options){const a=c._run({typed:!1,value:n.value},r);if(a.typed)if(a.issues)s?s.push(a):s=[a];else{i=a;break}else o?o.push(a):o=[a]}if(i)return i;if(s){if(s.length===1)return s[0];Gt(this,"type",n,r,{issues:id(s)}),n.typed=!0}else{if(o?.length===1)return o[0];Gt(this,"type",n,r,{issues:id(o)})}return n}}}function ct(e,t,n){const r=e._run({typed:!1,value:t},ob(n));if(r.issues)throw new pb(r.issues);return r.value}function fi(e,t){const n={};for(const r in e.entries)n[r]=la(e.entries[r]);return{...e,entries:n}}function Vs(...e){return{...e[0],pipe:e,_run(t,n){for(const r of e)if(r.kind!=="metadata"){if(t.issues&&(r.kind==="schema"||r.kind==="transformation")){t.typed=!1;break}(!t.issues||!n.abortEarly&&!n.abortPipeEarly)&&(t=r._run(t,n))}return t}}}const sd=new Uint8Array(32),od=kr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),At=e=>Vs(Ka(Uint8Array),Wy(e));function Io(e,t){return e.length!==t.length?!1:e.every((n,r)=>de(n,t[r])===0)}function Dn(e){if(!(e instanceof Uint8Array)||e.length<33)return!1;const t=e[0],n=e.slice(1,33);if(de(sd,n)===0||de(n,od)>=0)return!1;if((t===2||t===3)&&e.length===33)return!0;const r=e.slice(33);return de(sd,r)===0||de(r,od)>=0?!1:t===4&&e.length===65}const Xc=254;function vl(e){return!e||!("output"in e)||!(e.output instanceof Uint8Array)?!1:e.version!==void 0?(e.version&Xc)===e.version:!0}function Jy(e){return Array.isArray(e)?e.length!==2?!1:e.every(t=>Jy(t)):vl(e)}const yb=At(32),gb=At(20),cd=At(32),De=Ka(Uint8Array);Vs(zi(),Xy(/^([0-9a-f]{2})+$/i));const mb=Vs(ln(),Tl(),Da(0),$a(255)),yr=Vs(ln(),Tl(),Da(0),$a(4294967295)),Cu=Vs(Yy(),Da(0n),$a(0x7fffffffffffffffn)),ad=e=>Et(Object.entries(e).reduce((t,n)=>({...t,[n[0]]:Zy(n[1])}),{})),ud=new Uint8Array(1);function fd(e){let t=0;for(;e[t]===0;)++t;return t===e.length?ud:(e=e.slice(t),e[0]&128?at([ud,e]):e)}function ld(e){e[0]===0&&(e=e.slice(1));const t=new Uint8Array(32),n=Math.max(0,32-e.length);return t.set(e,n),t}function wb(e){const t=vr(e,e.length-1);if(!Ol(t))throw new Error("Invalid hashType "+t);const n=K1(e.subarray(0,-1)),r=ld(n.r),i=ld(n.s);return{signature:at([r,i]),hashType:t}}function bb(e,t){if(ct(Et({signature:At(64),hashType:mb}),{signature:e,hashType:t}),!Ol(t))throw new Error("Invalid hashType "+t);const n=new Uint8Array(1);bn(n,0,t);const r=fd(e.slice(0,32)),i=fd(e.slice(32,64));return at([G1(r,i),n])}const Eb=Object.freeze(Object.defineProperty({__proto__:null,decode:wb,encode:bb},Symbol.toStringTag,{value:"Module"})),Qy=Ge.OP_RESERVED,eg=dn(Al([Ka(Uint8Array),ln()]));function _b(e){return ja(ln(),e)&&(e===Ge.OP_0||e>=Ge.OP_1&&e<=Ge.OP_16||e===Ge.OP_1NEGATE)}function tg(e){return ja(De,e)||_b(e)}function Il(e){return ja(Vs(zy(),Gy(tg)),e)}function ng(e){return e.length-e.filter(tg).length}function ha(e){if(e.length===0)return Ge.OP_0;if(e.length===1){if(e[0]>=1&&e[0]<=16)return Qy+e[0];if(e[0]===129)return Ge.OP_1NEGATE}}function rg(e){return e instanceof Uint8Array}function Sb(e){return ja(eg,e)}function da(e){return e instanceof Uint8Array}function nn(e){if(rg(e))return e;ct(eg,e);const t=e.reduce((i,s)=>da(s)?s.length===1&&ha(s)!==void 0?i+1:i+Ky(s.length)+s.length:i+1,0),n=new Uint8Array(t);let r=0;if(e.forEach(i=>{if(da(i)){const s=ha(i);if(s!==void 0){bn(n,r,s),r+=1;return}r+=nb(n,i.length,r),n.set(i,r),r+=i.length}else bn(n,r,i),r+=1}),r!==n.length)throw new Error("Could not decode chunks");return n}function lt(e){if(Sb(e))return e;ct(De,e);const t=[];let n=0;for(;n<e.length;){const r=e[n];if(r>Ge.OP_0&&r<=Ge.OP_PUSHDATA4){const i=rb(e,n);if(i===null||(n+=i.size,n+i.number>e.length))return null;const s=e.slice(n,n+i.number);n+=i.number;const o=ha(s);o!==void 0?t.push(o):t.push(s)}else t.push(r),n+=1}return t}function Tb(e){if(rg(e)&&(e=lt(e)),!e)throw new Error("Could not convert invalid chunks to ASM");return e.map(t=>{if(da(t)){const n=ha(t);if(n===void 0)return xe(t);t=n}return My[t]}).join(" ")}function xb(e){return e=lt(e),ct(Kn(Il),e),e.map(t=>da(t)?t:t===Ge.OP_0?new Uint8Array(0):sb(t-Qy))}function Ab(e){return Dn(e)}function Ol(e){const t=e&-129;return t>0&&t<4}function Ir(e){return!(e instanceof Uint8Array)||!Ol(e[e.length-1])?!1:j1(e.slice(0,-1))}const So=Eb;function Te(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get(){const r=n.call(this);return this[t]=r,r},set(r){Object.defineProperty(this,t,{configurable:!0,enumerable:!0,value:r,writable:!0})}})}function In(e){let t;return()=>(t!==void 0||(t=e()),t)}const hs=Ge,Tc=hs.OP_RESERVED;function Ga(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 n(a){return Ir(a)||(t.allowIncomplete&&a===hs.OP_0)!==void 0}ct(fi(Et({network:Et({}),m:ln(),n:ln(),output:De,pubkeys:dn(Kn(Dn),"Received invalid pubkey"),signatures:dn(Kn(n),"Expected signature to be of type isAcceptableSignature"),input:De})),e);const i={network:e.network||Pn};let s=[],o=!1;function c(a){o||(o=!0,s=lt(a),i.m=s[0]-Tc,i.n=s[s.length-2]-Tc,i.pubkeys=s.slice(1,-2))}if(Te(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return nn([].concat(Tc+e.m,e.pubkeys,Tc+i.n,hs.OP_CHECKMULTISIG))}),Te(i,"m",()=>{if(i.output)return c(i.output),i.m}),Te(i,"n",()=>{if(i.pubkeys)return i.pubkeys.length}),Te(i,"pubkeys",()=>{if(e.output)return c(e.output),i.pubkeys}),Te(i,"signatures",()=>{if(e.input)return lt(e.input).slice(1)}),Te(i,"input",()=>{if(e.signatures)return nn([hs.OP_0].concat(e.signatures))}),Te(i,"witness",()=>{if(i.input)return[]}),Te(i,"name",()=>{if(!(!i.m||!i.n))return`p2ms(${i.m} of ${i.n})`}),t.validate){if(e.output){if(c(e.output),ct(ln(),s[0],{message:"Output is invalid"}),ct(ln(),s[s.length-2],{message:"Output is invalid"}),s[s.length-1]!==hs.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(a=>Dn(a)))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&&!Io(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]!==hs.OP_0)throw new TypeError("Input is invalid");if(i.signatures.length===0||!i.signatures.every(n))throw new TypeError("Input has invalid signature(s)");if(e.signatures&&!Io(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)}const hd=Ge;function ig(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||{}),ct(fi(Et({network:Et({}),output:De,pubkey:Kn(Dn,"invalid pubkey"),signature:Kn(Ir,"Expected signature to be of type isCanonicalScriptSignature"),input:De})),e);const n=In(()=>lt(e.input)),i={name:"p2pk",network:e.network||Pn};if(Te(i,"output",()=>{if(e.pubkey)return nn([e.pubkey,hd.OP_CHECKSIG])}),Te(i,"pubkey",()=>{if(e.output)return e.output.slice(1,-1)}),Te(i,"signature",()=>{if(e.input)return n()[0]}),Te(i,"input",()=>{if(e.signature)return nn([e.signature])}),Te(i,"witness",()=>{if(i.input)return[]}),t.validate){if(e.output){if(e.output[e.output.length-1]!==hd.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!Dn(i.pubkey))throw new TypeError("Output pubkey is invalid");if(e.pubkey&&de(e.pubkey,i.pubkey)!==0)throw new TypeError("Pubkey mismatch")}if(e.signature&&e.input&&de(e.input,i.input)!==0)throw new TypeError("Signature mismatch");if(e.input){if(n().length!==1)throw new TypeError("Input is invalid");if(!Ir(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}const ns=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function ic(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function vb(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function On(e,...t){if(!ic(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 dd(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 Ib(e,t){On(e);const n=t.outputLen;if(e.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Li(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Hu(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function zn(e,t){return e<<32-t|e>>>t}function xc(e,t){return e<<t|e>>>32-t>>>0}const sg=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ob=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function rt(e){if(On(e),sg)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Ob[e[n]];return t}const sr={_0:48,_9:57,A:65,F:70,a:97,f:102};function pd(e){if(e>=sr._0&&e<=sr._9)return e-sr._0;if(e>=sr.A&&e<=sr.F)return e-(sr.A-10);if(e>=sr.a&&e<=sr.f)return e-(sr.a-10)}function sc(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(sg)return Uint8Array.fromHex(e);const t=e.length,n=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=pd(e.charCodeAt(s)),c=pd(e.charCodeAt(s+1));if(o===void 0||c===void 0){const a=e[s]+e[s+1];throw new Error('hex string expected, got non-hex character "'+a+'" at index '+s)}r[i]=o*16+c}return r}function dt(e){if(typeof e!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(e))}function og(e){return typeof e=="string"&&(e=dt(e)),On(e),e}function $e(...e){let t=0;for(let r=0;r<e.length;r++){const i=e[r];On(i),t+=i.length}const n=new Uint8Array(t);for(let r=0,i=0;r<e.length;r++){const s=e[r];n.set(s,i),i+=s.length}return n}class Bb{}function Wa(e){const t=r=>e().update(og(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function cg(e=32){if(ns&&typeof ns.getRandomValues=="function")return ns.getRandomValues(new Uint8Array(e));if(ns&&typeof ns.randomBytes=="function")return Uint8Array.from(ns.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Nb(e,t,n,r){if(typeof e.setBigUint64=="function")return e.setBigUint64(t,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),c=Number(n&s),a=r?4:0,u=r?0:4;e.setUint32(t+a,o,r),e.setUint32(t+u,c,r)}function kb(e,t,n){return e&t^~e&n}function Pb(e,t,n){return e&t^e&n^t&n}class Bl extends Bb{constructor(t,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=t,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(t),this.view=Hu(this.buffer)}update(t){dd(this),t=og(t),On(t);const{view:n,buffer:r,blockLen:i}=this,s=t.length;for(let o=0;o<s;){const c=Math.min(i-this.pos,s-o);if(c===i){const a=Hu(t);for(;i<=s-o;o+=i)this.process(a,o);continue}r.set(t.subarray(o,o+c),this.pos),this.pos+=c,o+=c,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=t.length,this.roundClean(),this}digestInto(t){dd(this),Ib(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Li(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let l=o;l<i;l++)n[l]=0;Nb(r,i-8,BigInt(this.length*8),s),this.process(r,0);const c=Hu(t),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=a/4,f=this.get();if(u>f.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)c.setUint32(4*l,f[l],s)}digest(){const{buffer:t,outputLen:n}=this;this.digestInto(t);const r=t.slice(0,n);return this.destroy(),r}_cloneInto(t){t||(t=new this.constructor),t.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:c}=this;return t.destroyed=o,t.finished=s,t.length=i,t.pos=c,i%n&&t.buffer.set(r),t}clone(){return this._cloneInto()}}const Rr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ur=Uint32Array.from([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428]),Vt=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Rb=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),ag=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Ub=ag.map(e=>(9*e+5)%16),ug=(()=>{const n=[[ag],[Ub]];for(let r=0;r<4;r++)for(let i of n)i.push(i[r].map(s=>Rb[s]));return n})(),fg=ug[0],lg=ug[1],hg=[[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=>Uint8Array.from(e)),Cb=fg.map((e,t)=>e.map(n=>hg[t][n])),Hb=lg.map((e,t)=>e.map(n=>hg[t][n])),Fb=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Mb=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function yd(e,t,n,r){return e===0?t^n^r:e===1?t&n|~t&r:e===2?(t|~n)^r:e===3?t&r|n&~r:t^(n|~r)}const Ac=new Uint32Array(16);class qb extends Bl{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:n,h2:r,h3:i,h4:s}=this;return[t,n,r,i,s]}set(t,n,r,i,s){this.h0=t|0,this.h1=n|0,this.h2=r|0,this.h3=i|0,this.h4=s|0}process(t,n){for(let y=0;y<16;y++,n+=4)Ac[y]=t.getUint32(n,!0);let r=this.h0|0,i=r,s=this.h1|0,o=s,c=this.h2|0,a=c,u=this.h3|0,f=u,l=this.h4|0,d=l;for(let y=0;y<5;y++){const g=4-y,m=Fb[y],E=Mb[y],_=fg[y],S=lg[y],w=Cb[y],T=Hb[y];for(let O=0;O<16;O++){const A=xc(r+yd(y,s,c,u)+Ac[_[O]]+m,w[O])+l|0;r=l,l=u,u=xc(c,10)|0,c=s,s=A}for(let O=0;O<16;O++){const A=xc(i+yd(g,o,a,f)+Ac[S[O]]+E,T[O])+d|0;i=d,d=f,f=xc(a,10)|0,a=o,o=A}}this.set(this.h1+c+f|0,this.h2+u+d|0,this.h3+l+i|0,this.h4+r+o|0,this.h0+s+a|0)}roundClean(){Li(Ac)}destroy(){this.destroyed=!0,Li(this.buffer),this.set(0,0,0,0,0)}}const Vb=Wa(()=>new qb),Lb=Vb,vc=BigInt(2**32-1),gd=BigInt(32);function $b(e,t=!1){return t?{h:Number(e&vc),l:Number(e>>gd&vc)}:{h:Number(e>>gd&vc)|0,l:Number(e&vc)|0}}function Db(e,t=!1){const n=e.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:c}=$b(e[s],t);[r[s],i[s]]=[o,c]}return[r,i]}const md=(e,t,n)=>e>>>n,wd=(e,t,n)=>e<<32-n|t>>>n,rs=(e,t,n)=>e>>>n|t<<32-n,is=(e,t,n)=>e<<32-n|t>>>n,Ic=(e,t,n)=>e<<64-n|t>>>n-32,Oc=(e,t,n)=>e>>>n-32|t<<64-n;function or(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}const jb=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),Kb=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Gb=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Wb=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Xb=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),zb=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,Yb=Uint32Array.from([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]),Cr=new Uint32Array(64);class dg extends Bl{constructor(t=32){super(64,t,8,!1),this.A=Rr[0]|0,this.B=Rr[1]|0,this.C=Rr[2]|0,this.D=Rr[3]|0,this.E=Rr[4]|0,this.F=Rr[5]|0,this.G=Rr[6]|0,this.H=Rr[7]|0}get(){const{A:t,B:n,C:r,D:i,E:s,F:o,G:c,H:a}=this;return[t,n,r,i,s,o,c,a]}set(t,n,r,i,s,o,c,a){this.A=t|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=c|0,this.H=a|0}process(t,n){for(let l=0;l<16;l++,n+=4)Cr[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const d=Cr[l-15],y=Cr[l-2],g=zn(d,7)^zn(d,18)^d>>>3,m=zn(y,17)^zn(y,19)^y>>>10;Cr[l]=m+Cr[l-7]+g+Cr[l-16]|0}let{A:r,B:i,C:s,D:o,E:c,F:a,G:u,H:f}=this;for(let l=0;l<64;l++){const d=zn(c,6)^zn(c,11)^zn(c,25),y=f+d+kb(c,a,u)+Yb[l]+Cr[l]|0,m=(zn(r,2)^zn(r,13)^zn(r,22))+Pb(r,i,s)|0;f=u,u=a,a=c,c=o+y|0,o=s,s=i,i=r,r=y+m|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,c=c+this.E|0,a=a+this.F|0,u=u+this.G|0,f=f+this.H|0,this.set(r,i,s,o,c,a,u,f)}roundClean(){Li(Cr)}destroy(){this.set(0,0,0,0,0,0,0,0),Li(this.buffer)}}class Zb extends dg{constructor(){super(28),this.A=Ur[0]|0,this.B=Ur[1]|0,this.C=Ur[2]|0,this.D=Ur[3]|0,this.E=Ur[4]|0,this.F=Ur[5]|0,this.G=Ur[6]|0,this.H=Ur[7]|0}}const pg=Db(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),Jb=pg[0],Qb=pg[1],Hr=new Uint32Array(80),Fr=new Uint32Array(80);class e2 extends Bl{constructor(t=64){super(128,t,16,!1),this.Ah=Vt[0]|0,this.Al=Vt[1]|0,this.Bh=Vt[2]|0,this.Bl=Vt[3]|0,this.Ch=Vt[4]|0,this.Cl=Vt[5]|0,this.Dh=Vt[6]|0,this.Dl=Vt[7]|0,this.Eh=Vt[8]|0,this.El=Vt[9]|0,this.Fh=Vt[10]|0,this.Fl=Vt[11]|0,this.Gh=Vt[12]|0,this.Gl=Vt[13]|0,this.Hh=Vt[14]|0,this.Hl=Vt[15]|0}get(){const{Ah:t,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:c,Dl:a,Eh:u,El:f,Fh:l,Fl:d,Gh:y,Gl:g,Hh:m,Hl:E}=this;return[t,n,r,i,s,o,c,a,u,f,l,d,y,g,m,E]}set(t,n,r,i,s,o,c,a,u,f,l,d,y,g,m,E){this.Ah=t|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=c|0,this.Dl=a|0,this.Eh=u|0,this.El=f|0,this.Fh=l|0,this.Fl=d|0,this.Gh=y|0,this.Gl=g|0,this.Hh=m|0,this.Hl=E|0}process(t,n){for(let w=0;w<16;w++,n+=4)Hr[w]=t.getUint32(n),Fr[w]=t.getUint32(n+=4);for(let w=16;w<80;w++){const T=Hr[w-15]|0,O=Fr[w-15]|0,A=rs(T,O,1)^rs(T,O,8)^md(T,O,7),R=is(T,O,1)^is(T,O,8)^wd(T,O,7),M=Hr[w-2]|0,v=Fr[w-2]|0,U=rs(M,v,19)^Ic(M,v,61)^md(M,v,6),V=is(M,v,19)^Oc(M,v,61)^wd(M,v,6),K=Gb(R,V,Fr[w-7],Fr[w-16]),H=Wb(K,A,U,Hr[w-7],Hr[w-16]);Hr[w]=H|0,Fr[w]=K|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:c,Cl:a,Dh:u,Dl:f,Eh:l,El:d,Fh:y,Fl:g,Gh:m,Gl:E,Hh:_,Hl:S}=this;for(let w=0;w<80;w++){const T=rs(l,d,14)^rs(l,d,18)^Ic(l,d,41),O=is(l,d,14)^is(l,d,18)^Oc(l,d,41),A=l&y^~l&m,R=d&g^~d&E,M=Xb(S,O,R,Qb[w],Fr[w]),v=zb(M,_,T,A,Jb[w],Hr[w]),U=M|0,V=rs(r,i,28)^Ic(r,i,34)^Ic(r,i,39),K=is(r,i,28)^Oc(r,i,34)^Oc(r,i,39),H=r&s^r&c^s&c,$=i&o^i&a^o&a;_=m|0,S=E|0,m=y|0,E=g|0,y=l|0,g=d|0,{h:l,l:d}=or(u|0,f|0,v|0,U|0),u=c|0,f=a|0,c=s|0,a=o|0,s=r|0,o=i|0;const P=jb(U,K,$);r=Kb(P,v,V,H),i=P|0}({h:r,l:i}=or(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=or(this.Bh|0,this.Bl|0,s|0,o|0),{h:c,l:a}=or(this.Ch|0,this.Cl|0,c|0,a|0),{h:u,l:f}=or(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=or(this.Eh|0,this.El|0,l|0,d|0),{h:y,l:g}=or(this.Fh|0,this.Fl|0,y|0,g|0),{h:m,l:E}=or(this.Gh|0,this.Gl|0,m|0,E|0),{h:_,l:S}=or(this.Hh|0,this.Hl|0,_|0,S|0),this.set(r,i,s,o,c,a,u,f,l,d,y,g,m,E,_,S)}roundClean(){Li(Hr,Fr)}destroy(){Li(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const En=Wa(()=>new dg),t2=Wa(()=>new Zb),n2=Wa(()=>new e2),en=En;function Ar(e){return Lb(en(e))}function wi(e){return en(en(e))}const r2={"BIP0340/challenge":Uint8Array.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":Uint8Array.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":Uint8Array.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:Uint8Array.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:Uint8Array.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:Uint8Array.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:Uint8Array.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":Uint8Array.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":Uint8Array.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 Xa(e,t){return en(at([r2[e],t]))}function i2(e){if(e.length>=255)throw new TypeError("Alphabet too long");const t=new Uint8Array(256);for(let u=0;u<t.length;u++)t[u]=255;for(let u=0;u<e.length;u++){const f=e.charAt(u),l=f.charCodeAt(0);if(t[l]!==255)throw new TypeError(f+" is ambiguous");t[l]=u}const n=e.length,r=e.charAt(0),i=Math.log(n)/Math.log(256),s=Math.log(256)/Math.log(n);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let f=0,l=0,d=0;const y=u.length;for(;d!==y&&u[d]===0;)d++,f++;const g=(y-d)*s+1>>>0,m=new Uint8Array(g);for(;d!==y;){let S=u[d],w=0;for(let T=g-1;(S!==0||w<l)&&T!==-1;T--,w++)S+=256*m[T]>>>0,m[T]=S%n>>>0,S=S/n>>>0;if(S!==0)throw new Error("Non-zero carry");l=w,d++}let E=g-l;for(;E!==g&&m[E]===0;)E++;let _=r.repeat(f);for(;E<g;++E)_+=e.charAt(m[E]);return _}function c(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let f=0,l=0,d=0;for(;u[f]===r;)l++,f++;const y=(u.length-f)*i+1>>>0,g=new Uint8Array(y);for(;f<u.length;){const S=u.charCodeAt(f);if(S>255)return;let w=t[S];if(w===255)return;let T=0;for(let O=y-1;(w!==0||T<d)&&O!==-1;O--,T++)w+=n*g[O]>>>0,g[O]=w%256>>>0,w=w/256>>>0;if(w!==0)throw new Error("Non-zero carry");d=T,f++}let m=y-d;for(;m!==y&&g[m]===0;)m++;const E=new Uint8Array(l+(y-m));let _=l;for(;m!==y;)E[_++]=g[m++];return E}function a(u){const f=c(u);if(f)return f;throw new Error("Non-base"+n+" character")}return{encode:o,decodeUnsafe:c,decode:a}}var s2="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Fu=i2(s2);function o2(e){function t(s){var o=Uint8Array.from(s),c=e(o),a=o.length+4,u=new Uint8Array(a);return u.set(o,0),u.set(c.subarray(0,4),o.length),Fu.encode(u)}function n(s){var o=s.slice(0,-4),c=s.slice(-4),a=e(o);if(!(c[0]^a[0]|c[1]^a[1]|c[2]^a[2]|c[3]^a[3]))return o}function r(s){var o=Fu.decodeUnsafe(s);if(o!=null)return n(o)}function i(s){var o=Fu.decode(s),c=n(o);if(c==null)throw new Error("Invalid checksum");return c}return{encode:t,decode:i,decodeUnsafe:r}}function c2(e){return en(en(e))}const Oo=o2(c2),Mr=Ge;function oc(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||{}),ct(fi(Et({network:Et({}),address:zi(),hash:gb,output:At(25),pubkey:Kn(Dn),signature:Kn(Ir),input:De})),e);const n=In(()=>{const o=Oo.decode(e.address),c=vr(o,0),a=o.slice(1);return{version:c,hash:a}}),r=In(()=>lt(e.input)),i=e.network||Pn,s={name:"p2pkh",network:i};if(Te(s,"address",()=>{if(!s.hash)return;const o=new Uint8Array(21);return bn(o,0,i.pubKeyHash),o.set(s.hash,1),Oo.encode(o)}),Te(s,"hash",()=>{if(e.output)return e.output.slice(3,23);if(e.address)return n().hash;if(e.pubkey||s.pubkey)return Ar(e.pubkey||s.pubkey)}),Te(s,"output",()=>{if(s.hash)return nn([Mr.OP_DUP,Mr.OP_HASH160,s.hash,Mr.OP_EQUALVERIFY,Mr.OP_CHECKSIG])}),Te(s,"pubkey",()=>{if(e.input)return r()[1]}),Te(s,"signature",()=>{if(e.input)return r()[0]}),Te(s,"input",()=>{if(e.pubkey&&e.signature)return nn([e.signature,e.pubkey])}),Te(s,"witness",()=>{if(s.input)return[]}),t.validate){let o=Uint8Array.from([]);if(e.address){if(n().version!==i.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(n().hash.length!==20)throw new TypeError("Invalid address");o=n().hash}if(e.hash){if(o.length>0&&de(o,e.hash)!==0)throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==25||e.output[0]!==Mr.OP_DUP||e.output[1]!==Mr.OP_HASH160||e.output[2]!==20||e.output[23]!==Mr.OP_EQUALVERIFY||e.output[24]!==Mr.OP_CHECKSIG)throw new TypeError("Output is invalid");const c=e.output.slice(3,23);if(o.length>0&&de(o,c)!==0)throw new TypeError("Hash mismatch");o=c}if(e.pubkey){const c=Ar(e.pubkey);if(o.length>0&&de(o,c)!==0)throw new TypeError("Hash mismatch");o=c}if(e.input){const c=r();if(c.length!==2)throw new TypeError("Input is invalid");if(!Ir(c[0]))throw new TypeError("Input has invalid signature");if(!Dn(c[1]))throw new TypeError("Input has invalid pubkey");if(e.signature&&de(e.signature,c[0])!==0)throw new TypeError("Signature mismatch");if(e.pubkey&&de(e.pubkey,c[1])!==0)throw new TypeError("Pubkey mismatch");const a=Ar(c[1]);if(o.length>0&&de(o,a)!==0)throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}const Js=Ge;function cc(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||{}),ct(fi(Et({network:Et({}),address:zi(),hash:At(20),output:At(23),redeem:fi(Et({network:Et({}),output:De,input:De,witness:dn(De)})),input:De,witness:dn(De)})),e);let n=e.network;n||(n=e.redeem&&e.redeem.network||Pn);const r={network:n},i=In(()=>{const c=Oo.decode(e.address),a=vr(c,0),u=c.slice(1);return{version:a,hash:u}}),s=In(()=>lt(e.input)),o=In(()=>{const c=s(),a=c[c.length-1];return{network:n,output:a===Js.OP_FALSE?Uint8Array.from([]):a,input:nn(c.slice(0,-1)),witness:e.witness||[]}});if(Te(r,"address",()=>{if(!r.hash)return;const c=new Uint8Array(21);return bn(c,0,r.network.scriptHash),c.set(r.hash,1),Oo.encode(c)}),Te(r,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return i().hash;if(r.redeem&&r.redeem.output)return Ar(r.redeem.output)}),Te(r,"output",()=>{if(r.hash)return nn([Js.OP_HASH160,r.hash,Js.OP_EQUAL])}),Te(r,"redeem",()=>{if(e.input)return o()}),Te(r,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return nn([].concat(lt(e.redeem.input),e.redeem.output))}),Te(r,"witness",()=>{if(r.redeem&&r.redeem.witness)return r.redeem.witness;if(r.input)return[]}),Te(r,"name",()=>{const c=["p2sh"];return r.redeem!==void 0&&r.redeem.name!==void 0&&c.push(r.redeem.name),c.join("-")}),t.validate){let c=Uint8Array.from([]);if(e.address){if(i().version!==n.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(i().hash.length!==20)throw new TypeError("Invalid address");c=i().hash}if(e.hash){if(c.length>0&&de(c,e.hash)!==0)throw new TypeError("Hash mismatch");c=e.hash}if(e.output){if(e.output.length!==23||e.output[0]!==Js.OP_HASH160||e.output[1]!==20||e.output[22]!==Js.OP_EQUAL)throw new TypeError("Output is invalid");const u=e.output.slice(2,22);if(c.length>0&&de(c,u)!==0)throw new TypeError("Hash mismatch");c=u}const a=u=>{if(u.output){const f=lt(u.output);if(!f||f.length<1)throw new TypeError("Redeem.output too short");if(u.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(ng(f)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const l=Ar(u.output);if(c.length>0&&de(c,l)!==0)throw new TypeError("Hash mismatch");c=l}if(u.input){const f=u.input.length>0,l=u.witness&&u.witness.length>0;if(!f&&!l)throw new TypeError("Empty input");if(f&&l)throw new TypeError("Input and witness provided");if(f){const d=lt(u.input);if(!Il(d))throw new TypeError("Non push-only scriptSig")}}};if(e.input){const u=s();if(!u||u.length<1)throw new TypeError("Input too short");if(!(o().output instanceof Uint8Array))throw new TypeError("Input is invalid");a(o())}if(e.redeem){if(e.redeem.network&&e.redeem.network!==n)throw new TypeError("Network mismatch");if(e.input){const u=o();if(e.redeem.output&&de(e.redeem.output,u.output)!==0)throw new TypeError("Redeem.output mismatch");if(e.redeem.input&&de(e.redeem.input,u.input)!==0)throw new TypeError("Redeem.input mismatch")}a(e.redeem)}if(e.witness&&e.redeem&&e.redeem.witness&&!Io(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(r,e)}var bi={},bd;function ac(){if(bd)return bi;bd=1,Object.defineProperty(bi,"__esModule",{value:!0}),bi.bech32m=bi.bech32=void 0;const e="qpzry9x8gf2tvdw0s3jn54khce6mua7l",t={};for(let u=0;u<e.length;u++){const f=e.charAt(u);t[f]=u}function n(u){const f=u>>25;return(u&33554431)<<5^-(f>>0&1)&996825010^-(f>>1&1)&642813549^-(f>>2&1)&513874426^-(f>>3&1)&1027748829^-(f>>4&1)&705979059}function r(u){let f=1;for(let l=0;l<u.length;++l){const d=u.charCodeAt(l);if(d<33||d>126)return"Invalid prefix ("+u+")";f=n(f)^d>>5}f=n(f);for(let l=0;l<u.length;++l){const d=u.charCodeAt(l);f=n(f)^d&31}return f}function i(u,f,l,d){let y=0,g=0;const m=(1<<l)-1,E=[];for(let _=0;_<u.length;++_)for(y=y<<f|u[_],g+=f;g>=l;)g-=l,E.push(y>>g&m);if(d)g>0&&E.push(y<<l-g&m);else{if(g>=f)return"Excess padding";if(y<<l-g&m)return"Non-zero padding"}return E}function s(u){return i(u,8,5,!0)}function o(u){const f=i(u,5,8,!1);if(Array.isArray(f))return f}function c(u){const f=i(u,5,8,!1);if(Array.isArray(f))return f;throw new Error(f)}function a(u){let f;u==="bech32"?f=1:f=734539939;function l(m,E,_){if(_=_||90,m.length+7+E.length>_)throw new TypeError("Exceeds length limit");m=m.toLowerCase();let S=r(m);if(typeof S=="string")throw new Error(S);let w=m+"1";for(let T=0;T<E.length;++T){const O=E[T];if(O>>5!==0)throw new Error("Non 5-bit word");S=n(S)^O,w+=e.charAt(O)}for(let T=0;T<6;++T)S=n(S);S^=f;for(let T=0;T<6;++T){const O=S>>(5-T)*5&31;w+=e.charAt(O)}return w}function d(m,E){if(E=E||90,m.length<8)return m+" too short";if(m.length>E)return"Exceeds length limit";const _=m.toLowerCase(),S=m.toUpperCase();if(m!==_&&m!==S)return"Mixed-case string "+m;m=_;const w=m.lastIndexOf("1");if(w===-1)return"No separator character for "+m;if(w===0)return"Missing prefix for "+m;const T=m.slice(0,w),O=m.slice(w+1);if(O.length<6)return"Data too short";let A=r(T);if(typeof A=="string")return A;const R=[];for(let M=0;M<O.length;++M){const v=O.charAt(M),U=t[v];if(U===void 0)return"Unknown character "+v;A=n(A)^U,!(M+6>=O.length)&&R.push(U)}return A!==f?"Invalid checksum for "+m:{prefix:T,words:R}}function y(m,E){const _=d(m,E);if(typeof _=="object")return _}function g(m,E){const _=d(m,E);if(typeof _=="object")return _;throw new Error(_)}return{decodeUnsafe:y,decode:g,encode:l,toWords:s,fromWordsUnsafe:o,fromWords:c}}return bi.bech32=a("bech32"),bi.bech32m=a("bech32m"),bi}var Kt=ac();const Ed=Ge,a2=new Uint8Array(0);function za(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||{}),ct(fi(Et({address:zi(),hash:At(20),input:At(0),network:Et({}),output:At(22),pubkey:Kn(Dn,"Not a valid pubkey"),signature:Kn(Ir),witness:dn(De)})),e);const n=In(()=>{const s=Kt.bech32.decode(e.address),o=s.words.shift(),c=Kt.bech32.fromWords(s.words);return{version:o,prefix:s.prefix,data:Uint8Array.from(c)}}),r=e.network||Pn,i={name:"p2wpkh",network:r};if(Te(i,"address",()=>{if(!i.hash)return;const s=Kt.bech32.toWords(i.hash);return s.unshift(0),Kt.bech32.encode(r.bech32,s)}),Te(i,"hash",()=>{if(e.output)return e.output.slice(2,22);if(e.address)return n().data;if(e.pubkey||i.pubkey)return Ar(e.pubkey||i.pubkey)}),Te(i,"output",()=>{if(i.hash)return nn([Ed.OP_0,i.hash])}),Te(i,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.witness)return e.witness[1]}),Te(i,"signature",()=>{if(e.witness)return e.witness[0]}),Te(i,"input",()=>{if(i.witness)return a2}),Te(i,"witness",()=>{if(e.pubkey&&e.signature)return[e.signature,e.pubkey]}),t.validate){let s=Uint8Array.from([]);if(e.address){if(r&&r.bech32!==n().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(n().version!==0)throw new TypeError("Invalid address version");if(n().data.length!==20)throw new TypeError("Invalid address data");s=n().data}if(e.hash){if(s.length>0&&de(s,e.hash)!==0)throw new TypeError("Hash mismatch");s=e.hash}if(e.output){if(e.output.length!==22||e.output[0]!==Ed.OP_0||e.output[1]!==20)throw new TypeError("Output is invalid");if(s.length>0&&de(s,e.output.slice(2))!==0)throw new TypeError("Hash mismatch");s=e.output.slice(2)}if(e.pubkey){const o=Ar(e.pubkey);if(s.length>0&&de(s,o)!==0)throw new TypeError("Hash mismatch");if(s=o,!Dn(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(!Ir(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!Dn(e.witness[1])||e.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(e.signature&&de(e.signature,e.witness[0])!==0)throw new TypeError("Signature mismatch");if(e.pubkey&&de(e.pubkey,e.witness[1])!==0)throw new TypeError("Pubkey mismatch");const o=Ar(e.witness[1]);if(s.length>0&&de(s,o)!==0)throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}const _d=Ge,Mu=new Uint8Array(0);function Bc(e){return!!(e instanceof Uint8Array&&e.length===65&&e[0]===4&&Dn(e))}function uc(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||{}),ct(ad({network:Et({}),address:zi(),hash:yb,output:At(34),redeem:ad({input:De,network:Et({}),output:De,witness:dn(De)}),input:At(0),witness:dn(De)}),e);const n=In(()=>{const o=Kt.bech32.decode(e.address),c=o.words.shift(),a=Kt.bech32.fromWords(o.words);return{version:c,prefix:o.prefix,data:Uint8Array.from(a)}}),r=In(()=>lt(e.redeem.input));let i=e.network;i||(i=e.redeem&&e.redeem.network||Pn);const s={network:i};if(Te(s,"address",()=>{if(!s.hash)return;const o=Kt.bech32.toWords(s.hash);return o.unshift(0),Kt.bech32.encode(i.bech32,o)}),Te(s,"hash",()=>{if(e.output)return e.output.slice(2);if(e.address)return n().data;if(s.redeem&&s.redeem.output)return en(s.redeem.output)}),Te(s,"output",()=>{if(s.hash)return nn([_d.OP_0,s.hash])}),Te(s,"redeem",()=>{if(e.witness)return{output:e.witness[e.witness.length-1],input:Mu,witness:e.witness.slice(0,-1)}}),Te(s,"input",()=>{if(s.witness)return Mu}),Te(s,"witness",()=>{if(e.redeem&&e.redeem.input&&e.redeem.input.length>0&&e.redeem.output&&e.redeem.output.length>0){const o=xb(r());return s.redeem=Object.assign({witness:o},e.redeem),s.redeem.input=Mu,[].concat(o,e.redeem.output)}if(e.redeem&&e.redeem.output&&e.redeem.witness)return[].concat(e.redeem.witness,e.redeem.output)}),Te(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=Uint8Array.from([]);if(e.address){if(n().prefix!==i.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(n().version!==0)throw new TypeError("Invalid address version");if(n().data.length!==32)throw new TypeError("Invalid address data");o=n().data}if(e.hash){if(o.length>0&&de(o,e.hash)!==0)throw new TypeError("Hash mismatch");o=e.hash}if(e.output){if(e.output.length!==34||e.output[0]!==_d.OP_0||e.output[1]!==32)throw new TypeError("Output is invalid");const c=e.output.slice(2);if(o.length>0&&de(o,c)!==0)throw new TypeError("Hash mismatch");o=c}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 c=lt(e.redeem.output);if(!c||c.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(ng(c)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const a=en(e.redeem.output);if(o.length>0&&de(o,a)!==0)throw new TypeError("Hash mismatch");o=a}if(e.redeem.input&&!Il(r()))throw new TypeError("Non push-only scriptSig");if(e.witness&&e.redeem.witness&&!Io(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&r().some(Bc)||e.redeem.output&&(lt(e.redeem.output)||[]).some(Bc))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(e.witness&&e.witness.length>0){const c=e.witness[e.witness.length-1];if(e.redeem&&e.redeem.output&&de(e.redeem.output,c)!==0)throw new TypeError("Witness and redeem.output mismatch");if(e.witness.some(Bc)||(lt(c)||[]).some(Bc))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(s,e)}const To={};function u2(e){e?e!==To.eccLib&&(f2(e),To.eccLib=e):To.eccLib=e}function qf(){if(!To.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return To.eccLib}const cr=e=>kr(e);function f2(e){Tn(typeof e.isXOnlyPoint=="function"),Tn(e.isXOnlyPoint(cr("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Tn(e.isXOnlyPoint(cr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Tn(e.isXOnlyPoint(cr("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Tn(e.isXOnlyPoint(cr("0000000000000000000000000000000000000000000000000000000000000001"))),Tn(!e.isXOnlyPoint(cr("0000000000000000000000000000000000000000000000000000000000000000"))),Tn(!e.isXOnlyPoint(cr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Tn(typeof e.xOnlyPointAddTweak=="function"),l2.forEach(t=>{const n=e.xOnlyPointAddTweak(cr(t.pubkey),cr(t.tweak));t.result===null?Tn(n===null):(Tn(n!==null),Tn(n.parity===t.parity),Tn(de(n.xOnlyPubkey,cr(t.result))===0))})}function Tn(e){if(!e)throw new Error("ecc library invalid")}const l2=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}],yg="0123456789abcdefABCDEF";yg.split("").map(e=>e.codePointAt(0));Array(256).fill(!0).map((e,t)=>{const n=String.fromCodePoint(t),r=yg.indexOf(n);return r<0?void 0:r<16?r:r-6});new TextEncoder;new TextDecoder;function h2(e,t,n,r){if(t+2>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>65535)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= 65535. Received ${n}`);r==="LE"?(e[t]=n&255,e[t+1]=n>>8&255):(e[t]=n>>8&255,e[t+1]=n&255)}function d2(e,t,n,r){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>4294967295)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${4294967295}. Received ${n}`);r==="LE"?(e[t]=n&255,e[t+1]=n>>8&255,e[t+2]=n>>16&255,e[t+3]=n>>24&255):(e[t]=n>>24&255,e[t+1]=n>>16&255,e[t+2]=n>>8&255,e[t+3]=n&255)}function p2(e,t,n,r){if(t+8>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(r=r.toUpperCase(),n>0xffffffffffffffffn)throw new Error(`The value of "value" is out of range. It must be >= 0 and <= ${0xffffffffffffffffn}. Received ${n}`);r==="LE"?(e[t]=Number(n&0xffn),e[t+1]=Number(n>>8n&0xffn),e[t+2]=Number(n>>16n&0xffn),e[t+3]=Number(n>>24n&0xffn),e[t+4]=Number(n>>32n&0xffn),e[t+5]=Number(n>>40n&0xffn),e[t+6]=Number(n>>48n&0xffn),e[t+7]=Number(n>>56n&0xffn)):(e[t]=Number(n>>56n&0xffn),e[t+1]=Number(n>>48n&0xffn),e[t+2]=Number(n>>40n&0xffn),e[t+3]=Number(n>>32n&0xffn),e[t+4]=Number(n>>24n&0xffn),e[t+5]=Number(n>>16n&0xffn),e[t+6]=Number(n>>8n&0xffn),e[t+7]=Number(n&0xffn))}function y2(e,t,n){if(t+2>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){let r=0;return r=(r<<8)+e[t+1],r=(r<<8)+e[t],r}else{let r=0;return r=(r<<8)+e[t],r=(r<<8)+e[t+1],r}}function g2(e,t,n){if(t+4>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){let r=0;return r=(r<<8)+e[t+3]>>>0,r=(r<<8)+e[t+2]>>>0,r=(r<<8)+e[t+1]>>>0,r=(r<<8)+e[t]>>>0,r}else{let r=0;return r=(r<<8)+e[t]>>>0,r=(r<<8)+e[t+1]>>>0,r=(r<<8)+e[t+2]>>>0,r=(r<<8)+e[t+3]>>>0,r}}function m2(e,t,n){if(t+8>e.length)throw new Error("Offset is outside the bounds of Uint8Array");if(n=n.toUpperCase(),n==="LE"){let r=0n;return r=(r<<8n)+BigInt(e[t+7]),r=(r<<8n)+BigInt(e[t+6]),r=(r<<8n)+BigInt(e[t+5]),r=(r<<8n)+BigInt(e[t+4]),r=(r<<8n)+BigInt(e[t+3]),r=(r<<8n)+BigInt(e[t+2]),r=(r<<8n)+BigInt(e[t+1]),r=(r<<8n)+BigInt(e[t]),r}else{let r=0n;return r=(r<<8n)+BigInt(e[t]),r=(r<<8n)+BigInt(e[t+1]),r=(r<<8n)+BigInt(e[t+2]),r=(r<<8n)+BigInt(e[t+3]),r=(r<<8n)+BigInt(e[t+4]),r=(r<<8n)+BigInt(e[t+5]),r=(r<<8n)+BigInt(e[t+6]),r=(r<<8n)+BigInt(e[t+7]),r}}const w2=e=>{if(e<0||e>0xffffffffffffffffn)throw new RangeError("value out of range")};function b2(e){if(e<0||e>Number.MAX_SAFE_INTEGER||e%1!==0)throw new RangeError("value out of range")}function gg(e){typeof e=="number"?b2(e):w2(e)}function li(e,t,n){gg(e),n===void 0&&(n=0),t===void 0&&(t=new Uint8Array(Bn(e)));let r=0;return e<253?(t.set([Number(e)],n),r=1):e<=65535?(t.set([253],n),h2(t,n+1,Number(e),"LE"),r=3):e<=4294967295?(t.set([254],n),d2(t,n+1,Number(e),"LE"),r=5):(t.set([255],n),p2(t,n+1,BigInt(e),"LE"),r=9),{buffer:t,bytes:r}}function Ls(e,t){t===void 0&&(t=0);const n=e.at(t);if(n===void 0)throw new Error("buffer too small");if(n<253)return{numberValue:n,bigintValue:BigInt(n),bytes:1};if(n===253){const r=y2(e,t+1,"LE");return{numberValue:r,bigintValue:BigInt(r),bytes:3}}else if(n===254){const r=g2(e,t+1,"LE");return{numberValue:r,bigintValue:BigInt(r),bytes:5}}else{const r=m2(e,t+1,"LE");return{numberValue:r<=Number.MAX_SAFE_INTEGER?Number(r):null,bigintValue:r,bytes:9}}}function Bn(e){return gg(e),e<253?1:e<=65535?3:e<=4294967295?5:9}const E2=9007199254740991;function _2(e,t){if(typeof e!="number"&&typeof e!="bigint")throw new Error("cannot write a non-number as a number");if(e<0&&e<BigInt(0))throw new Error("specified a negative value for writing an unsigned value");if(e>t&&e>BigInt(t))throw new Error("RangeError: value out of range");if(Math.floor(Number(e))!==Number(e))throw new Error("value has a fractional component")}function Nl(e){if(e.length<1)return e;let t=e.length-1,n=0;for(let r=0;r<e.length/2;r++)n=e[r],e[r]=e[t],e[t]=n,t--;return e}function Sd(e){const t=new Uint8Array(e.length);return t.set(e),t}class $t{buffer;offset;static withCapacity(t){return new $t(new Uint8Array(t))}constructor(t,n=0){this.buffer=t,this.offset=n,ct(Qn([De,yr]),[t,n])}writeUInt8(t){this.offset=bn(this.buffer,this.offset,t)}writeInt32(t){this.offset=$y(this.buffer,this.offset,t,"LE")}writeInt64(t){this.offset=Dy(this.buffer,this.offset,BigInt(t),"LE")}writeUInt32(t){this.offset=rc(this.buffer,this.offset,t,"LE")}writeUInt64(t){this.offset=Q1(this.buffer,this.offset,BigInt(t),"LE")}writeVarInt(t){const{bytes:n}=li(t,this.buffer,this.offset);this.offset+=n}writeSlice(t){if(this.buffer.length<this.offset+t.length)throw new Error("Cannot write slice out of bounds");this.buffer.set(t,this.offset),this.offset+=t.length}writeVarSlice(t){this.writeVarInt(t.length),this.writeSlice(t)}writeVector(t){this.writeVarInt(t.length),t.forEach(n=>this.writeVarSlice(n))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}class S2{buffer;offset;constructor(t,n=0){this.buffer=t,this.offset=n,ct(Qn([De,yr]),[t,n])}readUInt8(){const t=vr(this.buffer,this.offset);return this.offset++,t}readInt32(){const t=tb(this.buffer,this.offset,"LE");return this.offset+=4,t}readUInt32(){const t=qs(this.buffer,this.offset,"LE");return this.offset+=4,t}readInt64(){const t=jy(this.buffer,this.offset,"LE");return this.offset+=8,t}readVarInt(){const{bigintValue:t,bytes:n}=Ls(this.buffer,this.offset);return this.offset+=n,t}readSlice(t){_2(t,E2);const n=Number(t);if(this.buffer.length<this.offset+n)throw new Error("Cannot read slice out of bounds");const r=this.buffer.slice(this.offset,this.offset+n);return this.offset+=n,r}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const t=this.readVarInt(),n=[];for(let r=0;r<t;r++)n.push(this.readVarSlice());return n}}const mg=192,T2=128,x2=e=>"left"in e&&"right"in e;function Vf(e,t){if(e.length<33)throw new TypeError(`The control-block length is too small. Got ${e.length}, expected min 33.`);const n=(e.length-33)/32;let r=t;for(let i=0;i<n;i++){const s=e.slice(33+32*i,65+32*i);de(r,s)<0?r=$f(r,s):r=$f(s,r)}return r}function Lf(e){if(vl(e))return{hash:Er(e)};const t=[Lf(e[0]),Lf(e[1])];t.sort((i,s)=>de(i.hash,s.hash));const[n,r]=t;return{hash:$f(n.hash,r.hash),left:n,right:r}}function pa(e,t){if(x2(e)){const n=pa(e.left,t);if(n!==void 0)return[...n,e.right.hash];const r=pa(e.right,t);if(r!==void 0)return[...r,e.left.hash]}else if(de(e.hash,t)===0)return[]}function Er(e){const t=e.version||mg;return Xa("TapLeaf",at([Uint8Array.from([t]),v2(e.output)]))}function A2(e,t){return Xa("TapTweak",at(t?[e,t]:[e]))}function Nc(e,t){if(!(e instanceof Uint8Array)||e.length!==32||t&&t.length!==32)return null;const n=A2(e,t),r=qf().xOnlyPointAddTweak(e,n);return!r||r.xOnlyPubkey===null?null:{parity:r.parity,x:Uint8Array.from(r.xOnlyPubkey)}}function $f(e,t){return Xa("TapBranch",at([e,t]))}function v2(e){const t=Bn(e.length),n=new Uint8Array(t);return li(e.length,n),at([n,e])}const Td=Ge,xd=1,I2=80;function fc(e,t){if(!e.address&&!e.output&&!e.pubkey&&!e.internalPubkey&&!(e.witness&&e.witness.length>1))throw new TypeError("Not enough data");t=Object.assign({validate:!0},t||{}),ct(fi(Et({address:zi(),input:At(0),network:Et({}),output:At(34),internalPubkey:At(32),hash:At(32),pubkey:At(32),signature:Al([At(64),At(65)]),witness:dn(De),scriptTree:Kn(Jy,"Taptree is not of type isTaptree"),redeem:fi(Et({output:De,redeemVersion:ln(),witness:dn(De)})),redeemVersion:ln()})),e);const n=In(()=>kl(e.address)),r=In(()=>{if(!(!e.witness||!e.witness.length))return e.witness.length>=2&&e.witness[e.witness.length-1][0]===I2?e.witness.slice(0,-1):e.witness.slice()}),i=In(()=>{if(e.scriptTree)return Lf(e.scriptTree);if(e.hash)return{hash:e.hash}}),s=e.network||Pn,o={name:"p2tr",network:s};if(Te(o,"address",()=>{if(!o.pubkey)return;const c=Kt.bech32m.toWords(o.pubkey);return c.unshift(xd),Kt.bech32m.encode(s.bech32,c)}),Te(o,"hash",()=>{const c=i();if(c)return c.hash;const a=r();if(a&&a.length>1){const u=a[a.length-1],f=u[0]&Xc,l=a[a.length-2],d=Er({output:l,version:f});return Vf(u,d)}return null}),Te(o,"output",()=>{if(o.pubkey)return nn([Td.OP_1,o.pubkey])}),Te(o,"redeemVersion",()=>e.redeemVersion?e.redeemVersion:e.redeem&&e.redeem.redeemVersion!==void 0&&e.redeem.redeemVersion!==null?e.redeem.redeemVersion:mg),Te(o,"redeem",()=>{const c=r();if(!(!c||c.length<2))return{output:c[c.length-2],witness:c.slice(0,-2),redeemVersion:c[c.length-1][0]&Xc}}),Te(o,"pubkey",()=>{if(e.pubkey)return e.pubkey;if(e.output)return e.output.slice(2);if(e.address)return n().data;if(o.internalPubkey){const c=Nc(o.internalPubkey,o.hash);if(c)return c.x}}),Te(o,"internalPubkey",()=>{if(e.internalPubkey)return e.internalPubkey;const c=r();if(c&&c.length>1)return c[c.length-1].slice(1,33)}),Te(o,"signature",()=>{if(e.signature)return e.signature;const c=r();if(!(!c||c.length!==1))return c[0]}),Te(o,"witness",()=>{if(e.witness)return e.witness;const c=i();if(c&&e.redeem&&e.redeem.output&&e.internalPubkey){const a=Er({output:e.redeem.output,version:o.redeemVersion}),u=pa(c,a);if(!u)return;const f=Nc(e.internalPubkey,c.hash);if(!f)return;const l=at([Uint8Array.from([o.redeemVersion|f.parity]),e.internalPubkey].concat(u));return[e.redeem.output,l]}if(e.signature)return[e.signature]}),t.validate){let c=Uint8Array.from([]);if(e.address){if(s&&s.bech32!==n().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(n().version!==xd)throw new TypeError("Invalid address version");if(n().data.length!==32)throw new TypeError("Invalid address data");c=n().data}if(e.pubkey){if(c.length>0&&de(c,e.pubkey)!==0)throw new TypeError("Pubkey mismatch");c=e.pubkey}if(e.output){if(e.output.length!==34||e.output[0]!==Td.OP_1||e.output[1]!==32)throw new TypeError("Output is invalid");if(c.length>0&&de(c,e.output.slice(2))!==0)throw new TypeError("Pubkey mismatch");c=e.output.slice(2)}if(e.internalPubkey){const f=Nc(e.internalPubkey,o.hash);if(c.length>0&&de(c,f.x)!==0)throw new TypeError("Pubkey mismatch");c=f.x}if(c&&c.length&&!qf().isXOnlyPoint(c))throw new TypeError("Invalid pubkey for p2tr");const a=i();if(e.hash&&a&&de(e.hash,a.hash)!==0)throw new TypeError("Hash mismatch");if(e.redeem&&e.redeem.output&&a){const f=Er({output:e.redeem.output,version:o.redeemVersion});if(!pa(a,f))throw new TypeError("Redeem script not in tree")}const u=r();if(e.redeem&&o.redeem){if(e.redeem.redeemVersion&&e.redeem.redeemVersion!==o.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(e.redeem.output){if(lt(e.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(o.redeem.output&&de(e.redeem.output,o.redeem.output)!==0)throw new TypeError("Redeem.output and witness mismatch")}if(e.redeem.witness&&o.redeem.witness&&!Io(e.redeem.witness,o.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(u&&u.length)if(u.length===1){if(e.signature&&de(e.signature,u[0])!==0)throw new TypeError("Signature mismatch")}else{const f=u[u.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 l=(f.length-33)/32;if(l>128)throw new TypeError(`The script path is too long. Got ${l}, expected max 128.`);const d=f.slice(1,33);if(e.internalPubkey&&de(e.internalPubkey,d)!==0)throw new TypeError("Internal pubkey mismatch");if(!qf().isXOnlyPoint(d))throw new TypeError("Invalid internalPubkey for p2tr witness");const y=f[0]&Xc,g=u[u.length-2],m=Er({output:g,version:y}),E=Vf(f,m),_=Nc(d,E);if(!_)throw new TypeError("Invalid outputKey for p2tr witness");if(c.length&&de(c,_.x)!==0)throw new TypeError("Pubkey mismatch for p2tr witness");if(_.parity!==(f[0]&1))throw new Error("Incorrect parity")}}return Object.assign(o,e)}const wg=40,bg=2,Eg=16,_g=2,Sg=80,Tg="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 O2(e,t){const n=e.slice(2);if(n.length<bg||n.length>wg)throw new TypeError("Invalid program length for segwit address");const r=e[0]-Sg;if(r<_g||r>Eg)throw new TypeError("Invalid version for segwit address");if(e[1]!==n.length)throw new TypeError("Invalid script for segwit address");return console.warn(Tg),B2(n,r,t.bech32)}function xg(e){const t=Oo.decode(e);if(t.length<21)throw new TypeError(e+" is too short");if(t.length>21)throw new TypeError(e+" is too long");const n=vr(t,0),r=t.slice(1);return{version:n,hash:r}}function kl(e){let t,n;try{t=Kt.bech32.decode(e)}catch{}if(t){if(n=t.words[0],n!==0)throw new TypeError(e+" uses wrong encoding")}else if(t=Kt.bech32m.decode(e),n=t.words[0],n===0)throw new TypeError(e+" uses wrong encoding");const r=Kt.bech32.fromWords(t.words.slice(1));return{version:n,prefix:t.prefix,data:Uint8Array.from(r)}}function B2(e,t,n){const r=Kt.bech32.toWords(e);return r.unshift(t),t===0?Kt.bech32.encode(n,r):Kt.bech32m.encode(n,r)}function N2(e,t){t=t||Pn;try{return oc({output:e,network:t}).address}catch{}try{return cc({output:e,network:t}).address}catch{}try{return za({output:e,network:t}).address}catch{}try{return uc({output:e,network:t}).address}catch{}try{return fc({output:e,network:t}).address}catch{}try{return O2(e,t)}catch{}throw new Error(Tb(e)+" has no matching Address")}function Ag(e,t){t=t||Pn;let n,r;try{n=xg(e)}catch{}if(n){if(n.version===t.pubKeyHash)return oc({hash:n.hash}).output;if(n.version===t.scriptHash)return cc({hash:n.hash}).output}else{try{r=kl(e)}catch{}if(r){if(r.prefix!==t.bech32)throw new Error(e+" has an invalid prefix");if(r.version===0){if(r.data.length===20)return za({hash:r.data}).output;if(r.data.length===32)return uc({hash:r.data}).output}else if(r.version===1){if(r.data.length===32)return fc({pubkey:r.data}).output}else if(r.version>=_g&&r.version<=Eg&&r.data.length>=bg&&r.data.length<=wg)return console.warn(Tg),nn([r.version+Sg,r.data])}}throw new Error(e+" has no matching Script")}function Jn(e){const t=e.length;return Bn(t)+t}function k2(e){const t=e.length;return Bn(t)+e.reduce((n,r)=>n+Jn(r),0)}const ei=new Uint8Array(0),Ad=[],qu=kr("0000000000000000000000000000000000000000000000000000000000000000"),vd=kr("0000000000000000000000000000000000000000000000000000000000000001"),P2=kr("ffffffffffffffff"),R2={script:ei,valueBuffer:P2};function U2(e){return e.value!==void 0}let gt=class Ye{static DEFAULT_SEQUENCE=4294967295;static SIGHASH_DEFAULT=0;static SIGHASH_ALL=1;static SIGHASH_NONE=2;static SIGHASH_SINGLE=3;static SIGHASH_ANYONECANPAY=128;static SIGHASH_OUTPUT_MASK=3;static SIGHASH_INPUT_MASK=128;static ADVANCED_TRANSACTION_MARKER=0;static ADVANCED_TRANSACTION_FLAG=1;static fromBuffer(t,n){const r=new S2(t),i=new Ye;i.version=r.readInt32();const s=r.readUInt8(),o=r.readUInt8();let c=!1;s===Ye.ADVANCED_TRANSACTION_MARKER&&o===Ye.ADVANCED_TRANSACTION_FLAG?c=!0:r.offset-=2;const a=r.readVarInt();for(let f=0;f<a;++f)i.ins.push({hash:r.readSlice(32),index:r.readUInt32(),script:r.readVarSlice(),sequence:r.readUInt32(),witness:Ad});const u=r.readVarInt();for(let f=0;f<u;++f)i.outs.push({value:r.readInt64(),script:r.readVarSlice()});if(c){for(let f=0;f<a;++f)i.ins[f].witness=r.readVector();if(!i.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(i.locktime=r.readUInt32(),n)return i;if(r.offset!==t.length)throw new Error("Transaction has unexpected data");return i}static fromHex(t){return Ye.fromBuffer(kr(t),!1)}static isCoinbaseHash(t){ct(cd,t);for(let n=0;n<32;++n)if(t[n]!==0)return!1;return!0}version=1;locktime=0;ins=[];outs=[];isCoinbase(){return this.ins.length===1&&Ye.isCoinbaseHash(this.ins[0].hash)}addInput(t,n,r,i){return ct(Qn([cd,yr,Mf(la(yr)),Mf(la(De))]),[t,n,r,i]),r==null&&(r=Ye.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:n,script:i||ei,sequence:r,witness:Ad})-1}addOutput(t,n){return ct(Qn([De,Cu]),[t,n]),this.outs.push({script:t,value:n})-1}hasWitnesses(){return this.ins.some(t=>t.witness.length!==0)}weight(){const t=this.byteLength(!1),n=this.byteLength(!0);return t*3+n}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(t=!0){const n=t&&this.hasWitnesses();return(n?10:8)+Bn(this.ins.length)+Bn(this.outs.length)+this.ins.reduce((r,i)=>r+40+Jn(i.script),0)+this.outs.reduce((r,i)=>r+8+Jn(i.script),0)+(n?this.ins.reduce((r,i)=>r+k2(i.witness),0):0)}clone(){const t=new Ye;return t.version=this.version,t.locktime=this.locktime,t.ins=this.ins.map(n=>({hash:n.hash,index:n.index,script:n.script,sequence:n.sequence,witness:n.witness})),t.outs=this.outs.map(n=>({script:n.script,value:n.value})),t}hashForSignature(t,n,r){if(ct(Qn([yr,De,ln()]),[t,n,r]),t>=this.ins.length)return vd;const i=nn(lt(n).filter(c=>c!==Ge.OP_CODESEPARATOR)),s=this.clone();if((r&31)===Ye.SIGHASH_NONE)s.outs=[],s.ins.forEach((c,a)=>{a!==t&&(c.sequence=0)});else if((r&31)===Ye.SIGHASH_SINGLE){if(t>=this.outs.length)return vd;s.outs.length=t+1;for(let c=0;c<t;c++)s.outs[c]=R2;s.ins.forEach((c,a)=>{a!==t&&(c.sequence=0)})}r&Ye.SIGHASH_ANYONECANPAY?(s.ins=[s.ins[t]],s.ins[0].script=i):(s.ins.forEach(c=>{c.script=ei}),s.ins[t].script=i);const o=new Uint8Array(s.byteLength(!1)+4);return $y(o,o.length-4,r,"LE"),s.__toBuffer(o,0,!1),wi(o)}hashForWitnessV1(t,n,r,i,s,o){if(ct(Qn([yr,dn(De),dn(Cu),yr]),[t,n,r,i]),r.length!==this.ins.length||n.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const c=i===Ye.SIGHASH_DEFAULT?Ye.SIGHASH_ALL:i&Ye.SIGHASH_OUTPUT_MASK,u=(i&Ye.SIGHASH_INPUT_MASK)===Ye.SIGHASH_ANYONECANPAY,f=c===Ye.SIGHASH_NONE,l=c===Ye.SIGHASH_SINGLE;let d=ei,y=ei,g=ei,m=ei,E=ei;if(!u){let T=$t.withCapacity(36*this.ins.length);this.ins.forEach(O=>{T.writeSlice(O.hash),T.writeUInt32(O.index)}),d=en(T.end()),T=$t.withCapacity(8*this.ins.length),r.forEach(O=>T.writeInt64(O)),y=en(T.end()),T=$t.withCapacity(n.map(Jn).reduce((O,A)=>O+A)),n.forEach(O=>T.writeVarSlice(O)),g=en(T.end()),T=$t.withCapacity(4*this.ins.length),this.ins.forEach(O=>T.writeUInt32(O.sequence)),m=en(T.end())}if(f||l){if(l&&t<this.outs.length){const T=this.outs[t],O=$t.withCapacity(8+Jn(T.script));O.writeInt64(T.value),O.writeVarSlice(T.script),E=en(O.end())}}else{if(!this.outs.length)throw new Error("Add outputs to the transaction before signing.");const T=this.outs.map(A=>8+Jn(A.script)).reduce((A,R)=>A+R),O=$t.withCapacity(T);this.outs.forEach(A=>{O.writeInt64(A.value),O.writeVarSlice(A.script)}),E=en(O.end())}const _=(s?2:0)+(o?1:0),S=174-(u?49:0)-(f?32:0)+(o?32:0)+(s?37:0),w=$t.withCapacity(S);if(w.writeUInt8(i),w.writeInt32(this.version),w.writeUInt32(this.locktime),w.writeSlice(d),w.writeSlice(y),w.writeSlice(g),w.writeSlice(m),f||l||w.writeSlice(E),w.writeUInt8(_),u){const T=this.ins[t];w.writeSlice(T.hash),w.writeUInt32(T.index),w.writeInt64(r[t]),w.writeVarSlice(n[t]),w.writeUInt32(T.sequence)}else w.writeUInt32(t);if(o){const T=$t.withCapacity(Jn(o));T.writeVarSlice(o),w.writeSlice(en(T.end()))}return l&&w.writeSlice(E),s&&(w.writeSlice(s),w.writeUInt8(0),w.writeUInt32(4294967295)),Xa("TapSighash",at([Uint8Array.from([0]),w.end()]))}hashForWitnessV0(t,n,r,i){ct(Qn([yr,De,Cu,yr]),[t,n,r,i]);let s=Uint8Array.from([]),o,c=qu,a=qu,u=qu;if(i&Ye.SIGHASH_ANYONECANPAY||(s=new Uint8Array(36*this.ins.length),o=new $t(s,0),this.ins.forEach(l=>{o.writeSlice(l.hash),o.writeUInt32(l.index)}),a=wi(s)),!(i&Ye.SIGHASH_ANYONECANPAY)&&(i&31)!==Ye.SIGHASH_SINGLE&&(i&31)!==Ye.SIGHASH_NONE&&(s=new Uint8Array(4*this.ins.length),o=new $t(s,0),this.ins.forEach(l=>{o.writeUInt32(l.sequence)}),u=wi(s)),(i&31)!==Ye.SIGHASH_SINGLE&&(i&31)!==Ye.SIGHASH_NONE){const l=this.outs.reduce((d,y)=>d+8+Jn(y.script),0);s=new Uint8Array(l),o=new $t(s,0),this.outs.forEach(d=>{o.writeInt64(d.value),o.writeVarSlice(d.script)}),c=wi(s)}else if((i&31)===Ye.SIGHASH_SINGLE&&t<this.outs.length){const l=this.outs[t];s=new Uint8Array(8+Jn(l.script)),o=new $t(s,0),o.writeInt64(l.value),o.writeVarSlice(l.script),c=wi(s)}s=new Uint8Array(156+Jn(n)),o=new $t(s,0);const f=this.ins[t];return o.writeInt32(this.version),o.writeSlice(a),o.writeSlice(u),o.writeSlice(f.hash),o.writeUInt32(f.index),o.writeVarSlice(n),o.writeInt64(r),o.writeUInt32(f.sequence),o.writeSlice(c),o.writeUInt32(this.locktime),o.writeUInt32(i),wi(s)}getHash(t){return t&&this.isCoinbase()?new Uint8Array(32):wi(this.__toBuffer(void 0,void 0,t))}getId(){return xe(Nl(this.getHash(!1)))}toBuffer(t,n){return this.__toBuffer(t,n,!0)}toHex(){return xe(this.toBuffer(void 0,void 0))}setInputScript(t,n){ct(Qn([ln(),De]),[t,n]),this.ins[t].script=n}setWitness(t,n){ct(Qn([ln(),dn(De)]),[t,n]),this.ins[t].witness=n}__toBuffer(t,n,r=!1){t||(t=new Uint8Array(this.byteLength(r)));const i=new $t(t,n||0);i.writeInt32(this.version);const s=r&&this.hasWitnesses();return s&&(i.writeUInt8(Ye.ADVANCED_TRANSACTION_MARKER),i.writeUInt8(Ye.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=>{U2(o)?i.writeInt64(o.value):i.writeSlice(o.valueBuffer),i.writeVarSlice(o.script)}),s&&this.ins.forEach(o=>{i.writeVector(o.witness)}),i.writeUInt32(this.locktime),n!==void 0?t.slice(n,i.offset):t}};var nr;(function(e){e[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB"})(nr||(nr={}));var me;(function(e){e[e.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",e[e.WITNESS_UTXO=1]="WITNESS_UTXO",e[e.PARTIAL_SIG=2]="PARTIAL_SIG",e[e.SIGHASH_TYPE=3]="SIGHASH_TYPE",e[e.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",e[e.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",e[e.BIP32_DERIVATION=6]="BIP32_DERIVATION",e[e.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",e[e.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",e[e.POR_COMMITMENT=9]="POR_COMMITMENT",e[e.TAP_KEY_SIG=19]="TAP_KEY_SIG",e[e.TAP_SCRIPT_SIG=20]="TAP_SCRIPT_SIG",e[e.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",e[e.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",e[e.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",e[e.TAP_MERKLE_ROOT=24]="TAP_MERKLE_ROOT"})(me||(me={}));var pt;(function(e){e[e.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",e[e.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",e[e.BIP32_DERIVATION=2]="BIP32_DERIVATION",e[e.TAP_INTERNAL_KEY=5]="TAP_INTERNAL_KEY",e[e.TAP_TREE=6]="TAP_TREE",e[e.TAP_BIP32_DERIVATION=7]="TAP_BIP32_DERIVATION"})(pt||(pt={}));const C2=e=>[...Array(e).keys()];function H2(e){if(e.key[0]!==nr.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+xe(e.key));if(e.key.length!==79||![2,3].includes(e.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+xe(e.key));if(e.value.length/4%1!==0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const t=e.key.slice(1),n={masterFingerprint:e.value.slice(0,4),extendedPubkey:t,path:"m"};for(const r of C2(e.value.length/4-1)){const i=qs(e.value,r*4+4,"LE"),s=!!(i&2147483648),o=i&2147483647;n.path+="/"+o.toString(10)+(s?"'":"")}return n}function F2(e){const t=new Uint8Array([nr.GLOBAL_XPUB]),n=at([t,e.extendedPubkey]),r=e.path.split("/"),i=new Uint8Array(r.length*4);i.set(e.masterFingerprint,0);let s=4;return r.slice(1).forEach(o=>{const c=o.slice(-1)==="'";let a=2147483647&parseInt(c?o.slice(0,-1):o,10);c&&(a+=2147483648),rc(i,s,a,"LE"),s+=4}),{key:n,value:i}}const M2="{ masterFingerprint: Uint8Array; extendedPubkey: Uint8Array; path: string; }";function q2(e){const t=e.extendedPubkey,n=e.masterFingerprint,r=e.path;return t instanceof Uint8Array&&t.length===78&&[2,3].indexOf(t[45])>-1&&n instanceof Uint8Array&&n.length===4&&typeof r=="string"&&!!r.match(/^m(\/\d+'?)*$/)}function V2(e,t,n){const r=xe(t.extendedPubkey);return n.has(r)?!1:(n.add(r),e.filter(i=>de(i.extendedPubkey,t.extendedPubkey)).length===0)}const L2=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:V2,check:q2,decode:H2,encode:F2,expected:M2},Symbol.toStringTag,{value:"Module"}));function $2(e){return{key:new Uint8Array([nr.UNSIGNED_TX]),value:e.toBuffer()}}const D2=Object.freeze(Object.defineProperty({__proto__:null,encode:$2},Symbol.toStringTag,{value:"Module"}));function j2(e){if(e.key[0]!==me.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+xe(e.key));return e.value}function K2(e){return{key:new Uint8Array([me.FINAL_SCRIPTSIG]),value:e}}const G2="Uint8Array";function W2(e){return e instanceof Uint8Array}function X2(e,t){return!!e&&!!t&&e.finalScriptSig===void 0}const z2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:X2,check:W2,decode:j2,encode:K2,expected:G2},Symbol.toStringTag,{value:"Module"}));function Y2(e){if(e.key[0]!==me.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+xe(e.key));return e.value}function Z2(e){return{key:new Uint8Array([me.FINAL_SCRIPTWITNESS]),value:e}}const J2="Uint8Array";function Q2(e){return e instanceof Uint8Array}function eE(e,t){return!!e&&!!t&&e.finalScriptWitness===void 0}const tE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:eE,check:Q2,decode:Y2,encode:Z2,expected:J2},Symbol.toStringTag,{value:"Module"}));function nE(e){if(e.key[0]!==me.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+xe(e.key));return e.value}function rE(e){return{key:new Uint8Array([me.NON_WITNESS_UTXO]),value:e}}const iE="Uint8Array";function sE(e){return e instanceof Uint8Array}function oE(e,t){return!!e&&!!t&&e.nonWitnessUtxo===void 0}const cE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:oE,check:sE,decode:nE,encode:rE,expected:iE},Symbol.toStringTag,{value:"Module"}));function aE(e){if(e.key[0]!==me.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+xe(e.key));if(!(e.key.length===34||e.key.length===66)||![2,3,4].includes(e.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+xe(e.key));return{pubkey:e.key.slice(1),signature:e.value}}function uE(e){const t=new Uint8Array([me.PARTIAL_SIG]);return{key:at([t,e.pubkey]),value:e.signature}}const fE="{ pubkey: Uint8Array; signature: Uint8Array; }";function lE(e){return e.pubkey instanceof Uint8Array&&e.signature instanceof Uint8Array&&[33,65].includes(e.pubkey.length)&&[2,3,4].includes(e.pubkey[0])&&hE(e.signature)}function hE(e){if(!(e instanceof Uint8Array)||e.length<9||e[0]!==48||e.length!==e[1]+3||e[2]!==2)return!1;const t=e[3];if(t>33||t<1||e[3+t+1]!==2)return!1;const n=e[3+t+2];return!(n>33||n<1||e.length!==3+t+2+n+2)}function dE(e,t,n){const r=xe(t.pubkey);return n.has(r)?!1:(n.add(r),e.filter(i=>de(i.pubkey,t.pubkey)===0).length===0)}const pE=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:dE,check:lE,decode:aE,encode:uE,expected:fE},Symbol.toStringTag,{value:"Module"}));function yE(e){if(e.key[0]!==me.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+xe(e.key));return W1(e.value)}function gE(e){return{key:new Uint8Array([me.POR_COMMITMENT]),value:X1(e)}}const mE="string";function wE(e){return typeof e=="string"}function bE(e,t){return!!e&&!!t&&e.porCommitment===void 0}const EE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:bE,check:wE,decode:yE,encode:gE,expected:mE},Symbol.toStringTag,{value:"Module"}));function _E(e){if(e.key[0]!==me.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+xe(e.key));return Number(qs(e.value,0,"LE"))}function SE(e){const t=Uint8Array.from([me.SIGHASH_TYPE]),n=new Uint8Array(4);return rc(n,0,e,"LE"),{key:t,value:n}}const TE="number";function xE(e){return typeof e=="number"}function AE(e,t){return!!e&&!!t&&e.sighashType===void 0}const vE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:AE,check:xE,decode:_E,encode:SE,expected:TE},Symbol.toStringTag,{value:"Module"}));function IE(e){if(e.key[0]!==me.TAP_KEY_SIG||e.key.length!==1)throw new Error("Decode Error: could not decode tapKeySig with key 0x"+xe(e.key));if(!vg(e.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return e.value}function OE(e){return{key:Uint8Array.from([me.TAP_KEY_SIG]),value:e}}const BE="Uint8Array";function vg(e){return e instanceof Uint8Array&&(e.length===64||e.length===65)}function NE(e,t){return!!e&&!!t&&e.tapKeySig===void 0}const kE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:NE,check:vg,decode:IE,encode:OE,expected:BE},Symbol.toStringTag,{value:"Module"}));function PE(e){if(e.key[0]!==me.TAP_LEAF_SCRIPT)throw new Error("Decode Error: could not decode tapLeafScript with key 0x"+xe(e.key));if((e.key.length-2)%32!==0)throw new Error("Decode Error: tapLeafScript has invalid control block in key 0x"+xe(e.key));const t=e.value[e.value.length-1];if((e.key[1]&254)!==t)throw new Error("Decode Error: tapLeafScript bad leaf version in key 0x"+xe(e.key));const n=e.value.slice(0,-1);return{controlBlock:e.key.slice(1),script:n,leafVersion:t}}function RE(e){const t=Uint8Array.from([me.TAP_LEAF_SCRIPT]),n=Uint8Array.from([e.leafVersion]);return{key:at([t,e.controlBlock]),value:at([e.script,n])}}const UE="{ controlBlock: Uint8Array; leafVersion: number, script: Uint8Array; }";function CE(e){return e.controlBlock instanceof Uint8Array&&(e.controlBlock.length-1)%32===0&&(e.controlBlock[0]&254)===e.leafVersion&&e.script instanceof Uint8Array}function HE(e,t,n){const r=xe(t.controlBlock);return n.has(r)?!1:(n.add(r),e.filter(i=>de(i.controlBlock,t.controlBlock)===0).length===0)}const FE=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:HE,check:CE,decode:PE,encode:RE,expected:UE},Symbol.toStringTag,{value:"Module"}));function ME(e){if(e.key[0]!==me.TAP_MERKLE_ROOT||e.key.length!==1)throw new Error("Decode Error: could not decode tapMerkleRoot with key 0x"+xe(e.key));if(!Ig(e.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return e.value}function qE(e){return{key:Uint8Array.from([me.TAP_MERKLE_ROOT]),value:e}}const VE="Uint8Array";function Ig(e){return e instanceof Uint8Array&&e.length===32}function LE(e,t){return!!e&&!!t&&e.tapMerkleRoot===void 0}const $E=Object.freeze(Object.defineProperty({__proto__:null,canAdd:LE,check:Ig,decode:ME,encode:qE,expected:VE},Symbol.toStringTag,{value:"Module"}));function DE(e){if(e.key[0]!==me.TAP_SCRIPT_SIG)throw new Error("Decode Error: could not decode tapScriptSig with key 0x"+xe(e.key));if(e.key.length!==65)throw new Error("Decode Error: tapScriptSig has invalid key 0x"+xe(e.key));if(e.value.length!==64&&e.value.length!==65)throw new Error("Decode Error: tapScriptSig has invalid signature in key 0x"+xe(e.key));const t=e.key.slice(1,33),n=e.key.slice(33);return{pubkey:t,leafHash:n,signature:e.value}}function jE(e){const t=Uint8Array.from([me.TAP_SCRIPT_SIG]);return{key:at([t,e.pubkey,e.leafHash]),value:e.signature}}const KE="{ pubkey: Uint8Array; leafHash: Uint8Array; signature: Uint8Array; }";function GE(e){return e.pubkey instanceof Uint8Array&&e.leafHash instanceof Uint8Array&&e.signature instanceof Uint8Array&&e.pubkey.length===32&&e.leafHash.length===32&&(e.signature.length===64||e.signature.length===65)}function WE(e,t,n){const r=xe(t.pubkey)+xe(t.leafHash);return n.has(r)?!1:(n.add(r),e.filter(i=>de(i.pubkey,t.pubkey)===0&&de(i.leafHash,t.leafHash)===0).length===0)}const XE=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:WE,check:GE,decode:DE,encode:jE,expected:KE},Symbol.toStringTag,{value:"Module"}));function zE(e){if(e.key[0]!==me.WITNESS_UTXO)throw new Error("Decode Error: could not decode witnessUtxo with key 0x"+xe(e.key));const t=jy(e.value,0,"LE");let n=8;const{numberValue:r,bytes:i}=Ls(e.value,n);n+=i;const s=e.value.slice(n);if(s.length!==r)throw new Error("Decode Error: WITNESS_UTXO script is not proper length");return{script:s,value:t}}function YE(e){const{script:t,value:n}=e,r=Bn(t.length),i=new Uint8Array(8+r+t.length);return Dy(i,0,BigInt(n),"LE"),li(t.length,i,8),i.set(t,8+r),{key:Uint8Array.from([me.WITNESS_UTXO]),value:i}}const ZE="{ script: Uint8Array; value: bigint; }";function JE(e){return e.script instanceof Uint8Array&&typeof e.value=="bigint"}function QE(e,t){return!!e&&!!t&&e.witnessUtxo===void 0}const e_=Object.freeze(Object.defineProperty({__proto__:null,canAdd:QE,check:JE,decode:zE,encode:YE,expected:ZE},Symbol.toStringTag,{value:"Module"}));function t_(e){if(e.key[0]!==pt.TAP_TREE||e.key.length!==1)throw new Error("Decode Error: could not decode tapTree with key 0x"+xe(e.key));let t=0;const n=[];for(;t<e.value.length;){const r=e.value[t++],i=e.value[t++],{numberValue:s,bytes:o}=Ls(e.value,t);t+=o,n.push({depth:r,leafVersion:i,script:e.value.slice(t,t+s)}),t+=s}return{leaves:n}}function n_(e){const t=Uint8Array.from([pt.TAP_TREE]),n=[].concat(...e.leaves.map(r=>[Uint8Array.of(r.depth,r.leafVersion),li(BigInt(r.script.length)).buffer,r.script]));return{key:t,value:at(n)}}const r_="{ leaves: [{ depth: number; leafVersion: number, script: Uint8Array; }] }";function i_(e){return Array.isArray(e.leaves)&&e.leaves.every(t=>t.depth>=0&&t.depth<=128&&(t.leafVersion&254)===t.leafVersion&&t.script instanceof Uint8Array)}function s_(e,t){return!!e&&!!t&&e.tapTree===void 0}const o_=Object.freeze(Object.defineProperty({__proto__:null,canAdd:s_,check:i_,decode:t_,encode:n_,expected:r_},Symbol.toStringTag,{value:"Module"})),c_=e=>[...Array(e).keys()],a_=e=>e.length===33&&[2,3].includes(e[0])||e.length===65&&e[0]===4;function Pl(e,t=a_){function n(c){if(c.key[0]!==e)throw new Error("Decode Error: could not decode bip32Derivation with key 0x"+xe(c.key));const a=c.key.slice(1);if(!t(a))throw new Error("Decode Error: bip32Derivation has invalid pubkey in key 0x"+xe(c.key));if(c.value.length/4%1!==0)throw new Error("Decode Error: Input BIP32_DERIVATION value length should be multiple of 4");const u={masterFingerprint:c.value.slice(0,4),pubkey:a,path:"m"};for(const f of c_(c.value.length/4-1)){const l=qs(c.value,f*4+4,"LE"),d=!!(l&2147483648),y=l&2147483647;u.path+="/"+y.toString(10)+(d?"'":"")}return u}function r(c){const a=Uint8Array.from([e]),u=at([a,c.pubkey]),f=c.path.split("/"),l=new Uint8Array(f.length*4);l.set(c.masterFingerprint,0);let d=4;return f.slice(1).forEach(y=>{const g=y.slice(-1)==="'";let m=2147483647&parseInt(g?y.slice(0,-1):y,10);g&&(m+=2147483648),rc(l,d,m,"LE"),d+=4}),{key:u,value:l}}const i="{ masterFingerprint: Uint8Array; pubkey: Uint8Array; path: string; }";function s(c){return c.pubkey instanceof Uint8Array&&c.masterFingerprint instanceof Uint8Array&&typeof c.path=="string"&&t(c.pubkey)&&c.masterFingerprint.length===4}function o(c,a,u){const f=xe(a.pubkey);return u.has(f)?!1:(u.add(f),c.filter(l=>de(l.pubkey,a.pubkey)===0).length===0)}return{decode:n,encode:r,check:s,expected:i,canAddToArray:o}}function Rl(e){return t;function t(n){let r;if(e.includes(n.key[0])&&(r=n.key.slice(1),!(r.length===33||r.length===65)||![2,3,4].includes(r[0])))throw new Error("Format Error: invalid pubkey in key 0x"+xe(n.key));return r}}function Og(e){function t(o){if(o.key[0]!==e)throw new Error("Decode Error: could not decode redeemScript with key 0x"+xe(o.key));return o.value}function n(o){return{key:Uint8Array.from([e]),value:o}}const r="Uint8Array";function i(o){return o instanceof Uint8Array}function s(o,c){return!!o&&!!c&&o.redeemScript===void 0}return{decode:t,encode:n,check:i,expected:r,canAdd:s}}const u_=e=>e.length===32;function Bg(e){const t=Pl(e,u_);function n(o){const{numberValue:c,bytes:a}=Ls(o.value),u=t.decode({key:o.key,value:o.value.slice(a+Number(c)*32)}),f=new Array(Number(c));for(let l=0,d=a;l<c;l++,d+=32)f[l]=o.value.slice(d,d+32);return{...u,leafHashes:f}}function r(o){const c=t.encode(o),a=Bn(o.leafHashes.length),u=new Uint8Array(a);li(o.leafHashes.length,u);const f=at([u,...o.leafHashes,c.value]);return{...c,value:f}}const i="{ masterFingerprint: Uint8Array; pubkey: Uint8Array; path: string; leafHashes: Uint8Array[]; }";function s(o){return Array.isArray(o.leafHashes)&&o.leafHashes.every(c=>c instanceof Uint8Array&&c.length===32)&&t.check(o)}return{decode:n,encode:r,check:s,expected:i,canAddToArray:t.canAddToArray}}function Ng(e){function t(o){if(o.key[0]!==e||o.key.length!==1)throw new Error("Decode Error: could not decode tapInternalKey with key 0x"+xe(o.key));if(o.value.length!==32)throw new Error("Decode Error: tapInternalKey not a 32-byte x-only pubkey");return o.value}function n(o){return{key:Uint8Array.from([e]),value:o}}const r="Uint8Array";function i(o){return o instanceof Uint8Array&&o.length===32}function s(o,c){return!!o&&!!c&&o.tapInternalKey===void 0}return{decode:t,encode:n,check:i,expected:r,canAdd:s}}function kg(e){function t(o){if(o.key[0]!==e)throw new Error("Decode Error: could not decode witnessScript with key 0x"+xe(o.key));return o.value}function n(o){return{key:Uint8Array.from([e]),value:o}}const r="Uint8Array";function i(o){return o instanceof Uint8Array}function s(o,c){return!!o&&!!c&&o.witnessScript===void 0}return{decode:t,encode:n,check:i,expected:r,canAdd:s}}const Ul={unsignedTx:D2,globalXpub:L2,checkPubkey:Rl([])},_t={nonWitnessUtxo:cE,partialSig:pE,sighashType:vE,finalScriptSig:z2,finalScriptWitness:tE,porCommitment:EE,witnessUtxo:e_,bip32Derivation:Pl(me.BIP32_DERIVATION),redeemScript:Og(me.REDEEM_SCRIPT),witnessScript:kg(me.WITNESS_SCRIPT),checkPubkey:Rl([me.PARTIAL_SIG,me.BIP32_DERIVATION]),tapKeySig:kE,tapScriptSig:XE,tapLeafScript:FE,tapBip32Derivation:Bg(me.TAP_BIP32_DERIVATION),tapInternalKey:Ng(me.TAP_INTERNAL_KEY),tapMerkleRoot:$E},gr={bip32Derivation:Pl(pt.BIP32_DERIVATION),redeemScript:Og(pt.REDEEM_SCRIPT),witnessScript:kg(pt.WITNESS_SCRIPT),checkPubkey:Rl([pt.BIP32_DERIVATION]),tapBip32Derivation:Bg(pt.TAP_BIP32_DERIVATION),tapTree:o_,tapInternalKey:Ng(pt.TAP_INTERNAL_KEY)},f_=Object.freeze(Object.defineProperty({__proto__:null,globals:Ul,inputs:_t,outputs:gr},Symbol.toStringTag,{value:"Module"})),ya=e=>[...Array(e).keys()];function Id(e){const t=e.map(l_);return t.push(Uint8Array.from([0])),at(t)}function l_(e){const t=e.key.length,n=e.value.length,r=Bn(t),i=Bn(n),s=new Uint8Array(r+t+i+n);return li(t,s,0),s.set(e.key,r),li(n,s,r+t),s.set(e.value,r+t+i),s}function h_(e,t){let n=0;function r(){const{numberValue:E,bytes:_}=Ls(e,n);n+=_;const S=e.slice(n,n+Number(E));return n+=Number(E),S}function i(){const E=qs(e,n,"BE");return n+=4,E}function s(){const E=vr(e,n);return n+=1,E}function o(){const E=r(),_=r();return{key:E,value:_}}function c(){if(n>=e.length)throw new Error("Format Error: Unexpected End of PSBT");const E=vr(e,n)===0;return E&&n++,E}if(i()!==1886610036)throw new Error("Format Error: Invalid Magic Number");if(s()!==255)throw new Error("Format Error: Magic Number must be followed by 0xff separator");const a=[],u={};for(;!c();){const E=o(),_=xe(E.key);if(u[_])throw new Error("Format Error: Keys must be unique for global keymap: key "+_);u[_]=1,a.push(E)}const f=a.filter(E=>E.key[0]===nr.UNSIGNED_TX);if(f.length!==1)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const l=t(f[0].value),{inputCount:d,outputCount:y}=l.getInputOutputCounts(),g=[],m=[];for(const E of ya(d)){const _={},S=[];for(;!c();){const w=o(),T=xe(w.key);if(_[T])throw new Error("Format Error: Keys must be unique for each input: input index "+E+" key "+T);_[T]=1,S.push(w)}g.push(S)}for(const E of ya(y)){const _={},S=[];for(;!c();){const w=o(),T=xe(w.key);if(_[T])throw new Error("Format Error: Keys must be unique for each output: output index "+E+" key "+T);_[T]=1,S.push(w)}m.push(S)}return Pg(l,{globalMapKeyVals:a,inputKeyVals:g,outputKeyVals:m})}function Lt(e,t,n){if(de(t,Uint8Array.from([n])))throw new Error(`Format Error: Invalid ${e} key: ${xe(t)}`)}function Pg(e,{globalMapKeyVals:t,inputKeyVals:n,outputKeyVals:r}){const i={unsignedTx:e};let s=0;for(const f of t)switch(f.key[0]){case nr.UNSIGNED_TX:if(Lt("global",f.key,nr.UNSIGNED_TX),s>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");s++;break;case nr.GLOBAL_XPUB:i.globalXpub===void 0&&(i.globalXpub=[]),i.globalXpub.push(Ul.globalXpub.decode(f));break;default:i.unknownKeyVals||(i.unknownKeyVals=[]),i.unknownKeyVals.push(f)}const o=n.length,c=r.length,a=[],u=[];for(const f of ya(o)){const l={};for(const d of n[f])switch(_t.checkPubkey(d),d.key[0]){case me.NON_WITNESS_UTXO:if(Lt("input",d.key,me.NON_WITNESS_UTXO),l.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");l.nonWitnessUtxo=_t.nonWitnessUtxo.decode(d);break;case me.WITNESS_UTXO:if(Lt("input",d.key,me.WITNESS_UTXO),l.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");l.witnessUtxo=_t.witnessUtxo.decode(d);break;case me.PARTIAL_SIG:l.partialSig===void 0&&(l.partialSig=[]),l.partialSig.push(_t.partialSig.decode(d));break;case me.SIGHASH_TYPE:if(Lt("input",d.key,me.SIGHASH_TYPE),l.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");l.sighashType=_t.sighashType.decode(d);break;case me.REDEEM_SCRIPT:if(Lt("input",d.key,me.REDEEM_SCRIPT),l.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");l.redeemScript=_t.redeemScript.decode(d);break;case me.WITNESS_SCRIPT:if(Lt("input",d.key,me.WITNESS_SCRIPT),l.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");l.witnessScript=_t.witnessScript.decode(d);break;case me.BIP32_DERIVATION:l.bip32Derivation===void 0&&(l.bip32Derivation=[]),l.bip32Derivation.push(_t.bip32Derivation.decode(d));break;case me.FINAL_SCRIPTSIG:Lt("input",d.key,me.FINAL_SCRIPTSIG),l.finalScriptSig=_t.finalScriptSig.decode(d);break;case me.FINAL_SCRIPTWITNESS:Lt("input",d.key,me.FINAL_SCRIPTWITNESS),l.finalScriptWitness=_t.finalScriptWitness.decode(d);break;case me.POR_COMMITMENT:Lt("input",d.key,me.POR_COMMITMENT),l.porCommitment=_t.porCommitment.decode(d);break;case me.TAP_KEY_SIG:Lt("input",d.key,me.TAP_KEY_SIG),l.tapKeySig=_t.tapKeySig.decode(d);break;case me.TAP_SCRIPT_SIG:l.tapScriptSig===void 0&&(l.tapScriptSig=[]),l.tapScriptSig.push(_t.tapScriptSig.decode(d));break;case me.TAP_LEAF_SCRIPT:l.tapLeafScript===void 0&&(l.tapLeafScript=[]),l.tapLeafScript.push(_t.tapLeafScript.decode(d));break;case me.TAP_BIP32_DERIVATION:l.tapBip32Derivation===void 0&&(l.tapBip32Derivation=[]),l.tapBip32Derivation.push(_t.tapBip32Derivation.decode(d));break;case me.TAP_INTERNAL_KEY:Lt("input",d.key,me.TAP_INTERNAL_KEY),l.tapInternalKey=_t.tapInternalKey.decode(d);break;case me.TAP_MERKLE_ROOT:Lt("input",d.key,me.TAP_MERKLE_ROOT),l.tapMerkleRoot=_t.tapMerkleRoot.decode(d);break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(d)}a.push(l)}for(const f of ya(c)){const l={};for(const d of r[f])switch(gr.checkPubkey(d),d.key[0]){case pt.REDEEM_SCRIPT:if(Lt("output",d.key,pt.REDEEM_SCRIPT),l.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");l.redeemScript=gr.redeemScript.decode(d);break;case pt.WITNESS_SCRIPT:if(Lt("output",d.key,pt.WITNESS_SCRIPT),l.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");l.witnessScript=gr.witnessScript.decode(d);break;case pt.BIP32_DERIVATION:l.bip32Derivation===void 0&&(l.bip32Derivation=[]),l.bip32Derivation.push(gr.bip32Derivation.decode(d));break;case pt.TAP_INTERNAL_KEY:Lt("output",d.key,pt.TAP_INTERNAL_KEY),l.tapInternalKey=gr.tapInternalKey.decode(d);break;case pt.TAP_TREE:Lt("output",d.key,pt.TAP_TREE),l.tapTree=gr.tapTree.decode(d);break;case pt.TAP_BIP32_DERIVATION:l.tapBip32Derivation===void 0&&(l.tapBip32Derivation=[]),l.tapBip32Derivation.push(gr.tapBip32Derivation.decode(d));break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(d)}u.push(l)}return{globalMap:i,inputs:a,outputs:u}}function d_({globalMap:e,inputs:t,outputs:n}){const{globalKeyVals:r,inputKeyVals:i,outputKeyVals:s}=Df({globalMap:e,inputs:t,outputs:n}),o=Id(r),c=l=>l.length===0?[Uint8Array.from([0])]:l.map(Id),a=c(i),u=c(s),f=new Uint8Array(5);return f.set([112,115,98,116,255],0),at([f,o].concat(a,u))}const p_=(e,t)=>de(e.key,t.key);function Vu(e,t){const n=new Set,r=Object.entries(e).reduce((s,[o,c])=>{if(o==="unknownKeyVals")return s;const a=t[o];if(a===void 0)return s;const u=(Array.isArray(c)?c:[c]).map(a.encode);return u.map(l=>xe(l.key)).forEach(l=>{if(n.has(l))throw new Error("Serialize Error: Duplicate key: "+l);n.add(l)}),s.concat(u)},[]),i=e.unknownKeyVals?e.unknownKeyVals.filter(s=>!n.has(xe(s.key))):[];return r.concat(i).sort(p_)}function Df({globalMap:e,inputs:t,outputs:n}){return{globalKeyVals:Vu(e,Ul),inputKeyVals:t.map(r=>Vu(r,_t)),outputKeyVals:n.map(r=>Vu(r,gr))}}function y_(e){const t=e[0],n=Df(t),r=e.slice(1);if(r.length===0)throw new Error("Combine: Nothing to combine");const i=Od(t);if(i===void 0)throw new Error("Combine: Self missing transaction");const s=ss(n.globalKeyVals),o=n.inputKeyVals.map(ss),c=n.outputKeyVals.map(ss);for(const a of r){const u=Od(a);if(u===void 0||de(u.toBuffer(),i.toBuffer())!==0)throw new Error("Combine: One of the Psbts does not have the same transaction.");const f=Df(a);ss(f.globalKeyVals).forEach(Lu(s,n.globalKeyVals,f.globalKeyVals)),f.inputKeyVals.map(ss).forEach((g,m)=>g.forEach(Lu(o[m],n.inputKeyVals[m],f.inputKeyVals[m]))),f.outputKeyVals.map(ss).forEach((g,m)=>g.forEach(Lu(c[m],n.outputKeyVals[m],f.outputKeyVals[m])))}return Pg(i,{globalMapKeyVals:n.globalKeyVals,inputKeyVals:n.inputKeyVals,outputKeyVals:n.outputKeyVals})}function Lu(e,t,n){return r=>{if(e.has(r))return;const i=n.filter(s=>xe(s.key)===r)[0];t.push(i),e.add(r)}}function Od(e){return e.globalMap.unsignedTx}function ss(e){const t=new Set;return e.forEach(n=>{const r=xe(n.key);if(t.has(r))throw new Error("Combine: KeyValue Map keys should be unique");t.add(r)}),t}function Rt(e,t){const n=e[t];if(n===void 0)throw new Error(`No input #${t}`);return n}function Bo(e,t){const n=e[t];if(n===void 0)throw new Error(`No output #${t}`);return n}function $u(e,t,n){if(e.key[0]<n)throw new Error("Use the method for your specific key instead of addUnknownKeyVal*");if(t&&t.filter(r=>de(r.key,e.key)===0).length!==0)throw new Error(`Duplicate Key: ${xe(e.key)}`)}function Du(e){let t=0;return Object.keys(e).forEach(n=>{Number(isNaN(Number(n)))&&t++}),t}function g_(e,t){let n=!1;if(t.nonWitnessUtxo||t.witnessUtxo){const r=!!t.redeemScript,i=!!t.witnessScript,s=!r||!!t.finalScriptSig,o=!i||!!t.finalScriptWitness,c=!!t.finalScriptSig||!!t.finalScriptWitness;n=s&&o&&c}if(n===!1)throw new Error(`Input #${e} has too much or too little data to clean`)}function Bd(e,t,n,r){throw new Error(`Data for ${e} key ${t} is incorrect: Expected ${n} and got ${JSON.stringify(r)}`)}function Cl(e){return(t,n)=>{for(const r of Object.keys(t)){const i=t[r],{canAdd:s,canAddToArray:o,check:c,expected:a}=f_[e+"s"][r]||{},u=!!o;if(c)if(u){if(!Array.isArray(i)||n[r]&&!Array.isArray(n[r]))throw new Error(`Key type ${r} must be an array`);i.every(c)||Bd(e,r,a,i);const f=n[r]||[],l=new Set;if(!i.every(d=>o(f,d,l)))throw new Error("Can not add duplicate data to array");n[r]=f.concat(i)}else{if(c(i)||Bd(e,r,a,i),!s(n,i))throw new Error(`Can not add duplicate data to ${e}`);n[r]=i}}}}const m_=Cl("global"),Rg=Cl("input"),Ug=Cl("output");function w_(e,t){const n=e.length-1,r=Rt(e,n);Rg(t,r)}function b_(e,t){const n=e.length-1,r=Bo(e,n);Ug(t,r)}let Nd=class{constructor(t){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:t}}static fromBase64(t,n){const r=Ly(t);return this.fromBuffer(r,n)}static fromHex(t,n){const r=kr(t);return this.fromBuffer(r,n)}static fromBuffer(t,n){const r=h_(t,n),i=new this(r.globalMap.unsignedTx);return Object.assign(i,r),i}toBase64(){const t=this.toBuffer();return Z1(t)}toHex(){const t=this.toBuffer();return xe(t)}toBuffer(){return d_(this)}updateGlobal(t){return m_(t,this.globalMap),this}updateInput(t,n){const r=Rt(this.inputs,t);return Rg(n,r),this}updateOutput(t,n){const r=Bo(this.outputs,t);return Ug(n,r),this}addUnknownKeyValToGlobal(t){return $u(t,this.globalMap.unknownKeyVals,Du(nr)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,n){const r=Rt(this.inputs,t);return $u(n,r.unknownKeyVals,Du(me)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(n),this}addUnknownKeyValToOutput(t,n){const r=Bo(this.outputs,t);return $u(n,r.unknownKeyVals,Du(pt)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(n),this}addInput(t){this.globalMap.unsignedTx.addInput(t),this.inputs.push({unknownKeyVals:[]});const n=t.unknownKeyVals||[],r=this.inputs.length-1;if(!Array.isArray(n))throw new Error("unknownKeyVals must be an Array");return n.forEach(i=>this.addUnknownKeyValToInput(r,i)),w_(this.inputs,t),this}addOutput(t){this.globalMap.unsignedTx.addOutput(t),this.outputs.push({unknownKeyVals:[]});const n=t.unknownKeyVals||[],r=this.outputs.length-1;if(!Array.isArray(n))throw new Error("unknownKeyVals must be an Array");return n.forEach(i=>this.addUnknownKeyValToOutput(r,i)),b_(this.outputs,t),this}clearFinalizedInput(t){const n=Rt(this.inputs,t);g_(t,n);for(const r of Object.keys(n))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(r)||delete n[r];return this}combine(...t){const n=y_([this].concat(t));return Object.assign(this,n),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}};function Yi(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}const E_=Yi(Ga),__=Yi(ig),S_=Yi(oc),Ya=Yi(za),kd=Yi(uc),Cg=Yi(cc),Hg=Yi(fc);function ga(e){let t=new Uint8Array(0);function n(o){t=at([t,o])}function r(o){const c=t.length,a=Bn(o);t=at([t,new Uint8Array(a)]),li(o,t,c)}function i(o){r(o.length),n(o)}function s(o){r(o.length),o.forEach(i)}return s(e),t}function Fg(e,t){const n=Ar(e),r=e.slice(1,33),i=lt(t);if(i===null)throw new Error("Unknown script error");return i.findIndex(s=>typeof s=="number"?!1:de(e,s)===0||de(n,s)===0||de(r,s)===0)}function Za(e,t){return Fg(e,t)!==-1}function T_(e,t){return x_(e).some(r=>Mg(r,So.decode,t))}function Mg(e,t,n){const{hashType:r}=t(e),i=[];switch(r&gt.SIGHASH_ANYONECANPAY&&i.push("addInput"),r&31){case gt.SIGHASH_ALL:break;case gt.SIGHASH_SINGLE:case gt.SIGHASH_NONE:i.push("addOutput"),i.push("setInputSequence");break}return i.indexOf(n)===-1}function x_(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=A_(e)}else t=e.partialSig;return t.map(n=>n.signature)}function A_(e){const t=e.finalScriptSig?lt(e.finalScriptSig)||[]:[],n=e.finalScriptWitness?lt(e.finalScriptWitness)||[]:[];return t.concat(n).filter(r=>r instanceof Uint8Array&&Ir(r)).map(r=>({signature:r}))}const zc=e=>e.length===32?e:e.slice(1,33);function Pd(e,t,n){const r=q_(t,e,n);try{const s=F_(t,r).concat(r.script).concat(r.controlBlock);return{finalScriptWitness:ga(s)}}catch(i){throw new Error(`Can not finalize taproot input #${e}: ${i}`)}}function kc(e,t){const n=t?Uint8Array.from([t]):Uint8Array.from([]);return at([e,n])}function Mn(e){return e&&!!(e.tapInternalKey||e.tapMerkleRoot||e.tapLeafScript&&e.tapLeafScript.length||e.tapBip32Derivation&&e.tapBip32Derivation.length||e.witnessUtxo&&Hg(e.witnessUtxo.script))}function ju(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t)}function Rd(e,t,n){U_(e,t,n),H_(e,t,n)}function Ud(e,t,n){C_(e,t,n),v_(e,t)}function v_(e,t){if(!t.tapTree&&!t.tapInternalKey)return;const n=t.tapInternalKey||e.tapInternalKey,r=t.tapTree||e.tapTree;if(n){const{script:i}=e,s=I_(n,r);if(i&&de(s,i)!==0)throw new Error("Error adding output. Script or address mismatch.")}}function I_(e,t){const n=t&&O_(t.leaves),{output:r}=fc({internalPubkey:e,scriptTree:n});return r}function O_(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:R_(e)}function B_(e,t){return k_(e).some(r=>Mg(r,N_,t))}function N_(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||gt.SIGHASH_DEFAULT}}function k_(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(n=>n.signature)),!t.length){const n=P_(e.finalScriptWitness);n&&t.push(n)}return t}function P_(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function R_(e){let t;for(const n of e)if(t=jf(n,t),!t)throw new Error("No room left to insert tapleaf in tree");return t}function jf(e,t,n=0){if(n>T2)throw new Error("Max taptree depth exceeded.");if(e.depth===n)return t?void 0:{output:e.script,version:e.leafVersion};if(vl(t))return;const r=jf(e,t&&t[0],n+1);if(r)return[r,t&&t[1]];const i=jf(e,t&&t[1],n+1);if(i)return[t&&t[0],i]}function U_(e,t,n){const r=Mn(e)&&bs(t),i=bs(e)&&Mn(t),s=e===t&&Mn(t)&&bs(t);if(r||i||s)throw new Error(`Invalid arguments for Psbt.${n}. Cannot use both taproot and non-taproot fields.`)}function C_(e,t,n){const r=ju(e)&&bs(t),i=bs(e)&&ju(t),s=e===t&&ju(t)&&bs(t);if(r||i||s)throw new Error(`Invalid arguments for Psbt.${n}. Cannot use both taproot and non-taproot fields.`)}function H_(e,t,n){if(t.tapMerkleRoot){const r=(t.tapLeafScript||[]).every(s=>Ku(s,t.tapMerkleRoot)),i=(e.tapLeafScript||[]).every(s=>Ku(s,t.tapMerkleRoot));if(!r||!i)throw new Error(`Invalid arguments for Psbt.${n}. Tapleaf not part of taptree.`)}else if(e.tapMerkleRoot&&!(t.tapLeafScript||[]).every(i=>Ku(i,e.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${n}. Tapleaf not part of taptree.`)}function Ku(e,t){if(!t)return!0;const n=Er({output:e.script,version:e.leafVersion}),r=Vf(e.controlBlock,n);return de(r,t)===0}function F_(e,t){const n=Er({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(r=>de(r.leafHash,n)===0).map(r=>M_(t.script,r)).sort((r,i)=>i.positionInScript-r.positionInScript).map(r=>r.signature)}function M_(e,t){return Object.assign({positionInScript:Fg(t.pubkey,e)},t)}function q_(e,t,n){if(!e.tapScriptSig||!e.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${t}. No tapleaf script signature provided.`);const r=(e.tapLeafScript||[]).sort((i,s)=>i.controlBlock.length-s.controlBlock.length).find(i=>V_(i,e.tapScriptSig,n));if(!r)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return r}function V_(e,t,n){const r=Er({output:e.script,version:e.leafVersion});return(!n||de(r,n)===0)&&t.find(s=>de(s.leafHash,r)===0)!==void 0}function bs(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const L_={network:Pn,maximumFeeRate:5e3};class ma{data;static fromBase64(t,n={}){const r=Ly(t);return this.fromBuffer(r,n)}static fromHex(t,n={}){const r=kr(t);return this.fromBuffer(r,n)}static fromBuffer(t,n={}){const r=Nd.fromBuffer(t,$_),i=new ma(n,r);return W_(i.__CACHE.__TX,i.__CACHE),i}__CACHE;opts;constructor(t={},n=new Nd(new qg)){this.data=n,this.opts=Object.assign({},L_,t),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},this.data.inputs.length===0&&this.setVersion(2);const r=(i,s,o,c)=>Object.defineProperty(i,s,{enumerable:o,writable:c});r(this,"__CACHE",!1,!0),r(this,"opts",!1,!0)}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(t){this.setVersion(t)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(t){this.setLocktime(t)}get txInputs(){return this.__CACHE.__TX.ins.map(t=>({hash:Sd(t.hash),index:t.index,sequence:t.sequence}))}get txOutputs(){return this.__CACHE.__TX.outs.map(t=>{let n;try{n=N2(t.script,this.opts.network)}catch{}return{script:Sd(t.script),value:t.value,address:n}})}combine(...t){return this.data.combine(...t.map(n=>n.data)),this}clone(){const t=ma.fromBuffer(this.data.toBuffer());return t.opts=JSON.parse(JSON.stringify(this.opts)),t}setMaximumFeeRate(t){Pc(t),this.opts.maximumFeeRate=t}setVersion(t){Pc(t),Qs(this.data.inputs,"setVersion");const n=this.__CACHE;return n.__TX.version=t,n.__EXTRACTED_TX=void 0,this}setLocktime(t){Pc(t),Qs(this.data.inputs,"setLocktime");const n=this.__CACHE;return n.__TX.locktime=t,n.__EXTRACTED_TX=void 0,this}setInputSequence(t,n){Pc(n),Qs(this.data.inputs,"setInputSequence");const r=this.__CACHE;if(r.__TX.ins.length<=t)throw new Error("Input index too high");return r.__TX.ins[t].sequence=n,r.__EXTRACTED_TX=void 0,this}addInputs(t){return t.forEach(n=>this.addInput(n)),this}addInput(t){if(arguments.length>1||!t||t.hash===void 0||t.index===void 0)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");Rd(t,t,"addInput"),Qs(this.data.inputs,"addInput"),t.witnessScript&&wa(t.witnessScript);const n=this.__CACHE;this.data.addInput(t);const r=n.__TX.ins[n.__TX.ins.length-1];$g(n,r);const i=this.data.inputs.length-1,s=this.data.inputs[i];return s.nonWitnessUtxo&&Gf(this.__CACHE,s,i),n.__FEE=void 0,n.__FEE_RATE=void 0,n.__EXTRACTED_TX=void 0,this}addOutputs(t){return t.forEach(n=>this.addOutput(n)),this}addOutput(t){if(arguments.length>1||!t||t.value===void 0||t.address===void 0&&t.script===void 0)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");Qs(this.data.inputs,"addOutput");const{address:n}=t;if(typeof n=="string"){const{network:i}=this.opts,s=Ag(n,i);t=Object.assign({},t,{script:s})}Ud(t,t,"addOutput");const r=this.__CACHE;return this.data.addOutput(t),r.__FEE=void 0,r.__FEE_RATE=void 0,r.__EXTRACTED_TX=void 0,this}extractTransaction(t){if(!this.data.inputs.every(Vg))throw new Error("Not finalized");const n=this.__CACHE;if(t||j_(this,n,this.opts),n.__EXTRACTED_TX)return n.__EXTRACTED_TX;const r=n.__TX.clone();return Xg(this.data.inputs,r,n,!0),r}getFeeRate(){return qd("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return qd("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Rt(this.data.inputs,0),eo(this.data.inputs.length).forEach(t=>this.finalizeInput(t)),this}finalizeInput(t,n){const r=Rt(this.data.inputs,t);return Mn(r)?this._finalizeTaprootInput(t,r,void 0,n):this._finalizeInput(t,r,n)}finalizeTaprootInput(t,n,r=Pd){const i=Rt(this.data.inputs,t);if(Mn(i))return this._finalizeTaprootInput(t,i,n,r);throw new Error(`Cannot finalize input #${t}. Not Taproot.`)}_finalizeInput(t,n,r=X_){const{script:i,isP2SH:s,isP2WSH:o,isSegwit:c}=J_(t,n,this.__CACHE);if(!i)throw new Error(`No script found for input #${t}`);K_(n);const{finalScriptSig:a,finalScriptWitness:u}=r(t,n,i,c,s,o);if(a&&this.data.updateInput(t,{finalScriptSig:a}),u&&this.data.updateInput(t,{finalScriptWitness:u}),!a&&!u)throw new Error(`Unknown error finalizing input #${t}`);return this.data.clearFinalizedInput(t),this}_finalizeTaprootInput(t,n,r,i=Pd){if(!n.witnessUtxo)throw new Error(`Cannot finalize input #${t}. Missing withness utxo.`);if(n.tapKeySig){const s=fc({output:n.witnessUtxo.script,signature:n.tapKeySig}),o=ga(s.witness);this.data.updateInput(t,{finalScriptWitness:o})}else{const{finalScriptWitness:s}=i(t,n,r);this.data.updateInput(t,{finalScriptWitness:s})}return this.data.clearFinalizedInput(t),this}getInputType(t){const n=Rt(this.data.inputs,t),r=zg(t,n,this.__CACHE),i=Qa(r,t,"input",n.redeemScript||rS(n.finalScriptSig),n.witnessScript||iS(n.finalScriptWitness)),s=i.type==="raw"?"":i.type+"-",o=Zg(i.meaningfulScript);return s+o}inputHasPubkey(t,n){const r=Rt(this.data.inputs,t);return tS(n,r,t,this.__CACHE)}inputHasHDKey(t,n){const r=Rt(this.data.inputs,t),i=Hd(n);return!!r.bip32Derivation&&r.bip32Derivation.some(i)}outputHasPubkey(t,n){const r=Bo(this.data.outputs,t);return nS(n,r,t,this.__CACHE)}outputHasHDKey(t,n){const r=Bo(this.data.outputs,t),i=Hd(n);return!!r.bip32Derivation&&r.bip32Derivation.some(i)}validateSignaturesOfAllInputs(t){return Rt(this.data.inputs,0),eo(this.data.inputs.length).map(r=>this.validateSignaturesOfInput(r,t)).reduce((r,i)=>i===!0&&r,!0)}validateSignaturesOfInput(t,n,r){const i=this.data.inputs[t];return Mn(i)?this.validateSignaturesOfTaprootInput(t,n,r):this._validateSignaturesOfInput(t,n,r)}_validateSignaturesOfInput(t,n,r){const i=this.data.inputs[t],s=(i||{}).partialSig;if(!i||!s||s.length<1)throw new Error("No signatures to validate");if(typeof n!="function")throw new Error("Need validator function to validate signatures");const o=r?s.filter(l=>de(l.pubkey,r)===0):s;if(o.length<1)throw new Error("No signatures for this pubkey");const c=[];let a,u,f;for(const l of o){const d=So.decode(l.signature),{hash:y,script:g}=f!==d.hashType?jg(t,Object.assign({},i,{sighashType:d.hashType}),this.__CACHE,!0):{hash:a,script:u};f=d.hashType,a=y,u=g,Lg(l.pubkey,g,"verify"),c.push(n(l.pubkey,y,d.signature))}return c.every(l=>l===!0)}validateSignaturesOfTaprootInput(t,n,r){const i=this.data.inputs[t],s=(i||{}).tapKeySig,o=(i||{}).tapScriptSig;if(!i&&!s&&!(o&&!o.length))throw new Error("No signatures to validate");if(typeof n!="function")throw new Error("Need validator function to validate signatures");r=r&&zc(r);const c=r?Kf(t,i,this.data.inputs,r,this.__CACHE):Y_(t,i,this.data.inputs,this.__CACHE);if(!c.length)throw new Error("No signatures for this pubkey");const a=c.find(f=>!f.leafHash);let u=0;if(s&&a){if(!n(a.pubkey,a.hash,Ld(s)))return!1;u++}if(o)for(const f of o){const l=c.find(d=>de(d.pubkey,f.pubkey)===0);if(l){if(!n(f.pubkey,l.hash,Ld(f.signature)))return!1;u++}}return u>0}signAllInputsHD(t,n=[gt.SIGHASH_ALL]){if(!t||!t.publicKey||!t.fingerprint)throw new Error("Need HDSigner to sign input");const r=[];for(const i of eo(this.data.inputs.length))try{this.signInputHD(i,t,n),r.push(!0)}catch{r.push(!1)}if(r.every(i=>i===!1))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(t,n=[gt.SIGHASH_ALL]){return new Promise((r,i)=>{if(!t||!t.publicKey||!t.fingerprint)return i(new Error("Need HDSigner to sign input"));const s=[],o=[];for(const c of eo(this.data.inputs.length))o.push(this.signInputHDAsync(c,t,n).then(()=>{s.push(!0)},()=>{s.push(!1)}));return Promise.all(o).then(()=>{if(s.every(c=>c===!1))return i(new Error("No inputs were signed"));r()})})}signInputHD(t,n,r=[gt.SIGHASH_ALL]){if(!n||!n.publicKey||!n.fingerprint)throw new Error("Need HDSigner to sign input");return $d(t,this.data.inputs,n).forEach(s=>this.signInput(t,s,r)),this}signInputHDAsync(t,n,r=[gt.SIGHASH_ALL]){return new Promise((i,s)=>{if(!n||!n.publicKey||!n.fingerprint)return s(new Error("Need HDSigner to sign input"));const c=$d(t,this.data.inputs,n).map(a=>this.signInputAsync(t,a,r));return Promise.all(c).then(()=>{i()}).catch(s)})}signAllInputs(t,n){if(!t||!t.publicKey)throw new Error("Need Signer to sign input");const r=[];for(const i of eo(this.data.inputs.length))try{this.signInput(i,t,n),r.push(!0)}catch{r.push(!1)}if(r.every(i=>i===!1))throw new Error("No inputs were signed");return this}signAllInputsAsync(t,n){return new Promise((r,i)=>{if(!t||!t.publicKey)return i(new Error("Need Signer to sign input"));const s=[],o=[];for(const[c]of this.data.inputs.entries())o.push(this.signInputAsync(c,t,n).then(()=>{s.push(!0)},()=>{s.push(!1)}));return Promise.all(o).then(()=>{if(s.every(c=>c===!1))return i(new Error("No inputs were signed"));r()})})}signInput(t,n,r){if(!n||!n.publicKey)throw new Error("Need Signer to sign input");const i=Rt(this.data.inputs,t);return Mn(i)?this._signTaprootInput(t,i,n,void 0,r):this._signInput(t,n,r)}signTaprootInput(t,n,r,i){if(!n||!n.publicKey)throw new Error("Need Signer to sign input");const s=Rt(this.data.inputs,t);if(Mn(s))return this._signTaprootInput(t,s,n,r,i);throw new Error(`Input #${t} is not of type Taproot.`)}_signInput(t,n,r=[gt.SIGHASH_ALL]){const{hash:i,sighashType:s}=Vd(this.data.inputs,t,n.publicKey,this.__CACHE,r),o=[{pubkey:n.publicKey,signature:So.encode(n.sign(i),s)}];return this.data.updateInput(t,{partialSig:o}),this}_signTaprootInput(t,n,r,i,s=[gt.SIGHASH_DEFAULT]){const o=this.checkTaprootHashesForSig(t,n,r,i,s),c=o.filter(u=>!u.leafHash).map(u=>kc(r.signSchnorr(u.hash),n.sighashType))[0],a=o.filter(u=>!!u.leafHash).map(u=>({pubkey:zc(r.publicKey),signature:kc(r.signSchnorr(u.hash),n.sighashType),leafHash:u.leafHash}));return c&&this.data.updateInput(t,{tapKeySig:c}),a.length&&this.data.updateInput(t,{tapScriptSig:a}),this}signInputAsync(t,n,r){return Promise.resolve().then(()=>{if(!n||!n.publicKey)throw new Error("Need Signer to sign input");const i=Rt(this.data.inputs,t);return Mn(i)?this._signTaprootInputAsync(t,i,n,void 0,r):this._signInputAsync(t,n,r)})}signTaprootInputAsync(t,n,r,i){return Promise.resolve().then(()=>{if(!n||!n.publicKey)throw new Error("Need Signer to sign input");const s=Rt(this.data.inputs,t);if(Mn(s))return this._signTaprootInputAsync(t,s,n,r,i);throw new Error(`Input #${t} is not of type Taproot.`)})}_signInputAsync(t,n,r=[gt.SIGHASH_ALL]){const{hash:i,sighashType:s}=Vd(this.data.inputs,t,n.publicKey,this.__CACHE,r);return Promise.resolve(n.sign(i)).then(o=>{const c=[{pubkey:n.publicKey,signature:So.encode(o,s)}];this.data.updateInput(t,{partialSig:c})})}async _signTaprootInputAsync(t,n,r,i,s=[gt.SIGHASH_DEFAULT]){const o=this.checkTaprootHashesForSig(t,n,r,i,s),c=[],a=o.filter(f=>!f.leafHash)[0];if(a){const f=Promise.resolve(r.signSchnorr(a.hash)).then(l=>({tapKeySig:kc(l,n.sighashType)}));c.push(f)}const u=o.filter(f=>!!f.leafHash);if(u.length){const f=u.map(l=>Promise.resolve(r.signSchnorr(l.hash)).then(d=>({tapScriptSig:[{pubkey:zc(r.publicKey),signature:kc(d,n.sighashType),leafHash:l.leafHash}]})));c.push(...f)}return Promise.all(c).then(f=>{f.forEach(l=>this.data.updateInput(t,l))})}checkTaprootHashesForSig(t,n,r,i,s){if(typeof r.signSchnorr!="function")throw new Error(`Need Schnorr Signer to sign taproot input #${t}.`);const o=Kf(t,n,this.data.inputs,r.publicKey,this.__CACHE,i,s);if(!o||!o.length)throw new Error(`Can not sign for input #${t} with the key ${xe(r.publicKey)}`);return o}toBuffer(){return Gu(this.__CACHE),this.data.toBuffer()}toHex(){return Gu(this.__CACHE),this.data.toHex()}toBase64(){return Gu(this.__CACHE),this.data.toBase64()}updateGlobal(t){return this.data.updateGlobal(t),this}updateInput(t,n){return n.witnessScript&&wa(n.witnessScript),Rd(this.data.inputs[t],n,"updateInput"),this.data.updateInput(t,n),n.nonWitnessUtxo&&Gf(this.__CACHE,this.data.inputs[t],t),this}updateOutput(t,n){const r=this.data.outputs[t];return Ud(r,n,"updateOutput"),this.data.updateOutput(t,n),this}addUnknownKeyValToGlobal(t){return this.data.addUnknownKeyValToGlobal(t),this}addUnknownKeyValToInput(t,n){return this.data.addUnknownKeyValToInput(t,n),this}addUnknownKeyValToOutput(t,n){return this.data.addUnknownKeyValToOutput(t,n),this}clearFinalizedInput(t){return this.data.clearFinalizedInput(t),this}}const $_=e=>new qg(e);class qg{tx;constructor(t=Uint8Array.from([2,0,0,0,0,0,0,0,0,0])){this.tx=gt.fromBuffer(t),G_(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(t){if(t.hash===void 0||t.index===void 0||!(t.hash instanceof Uint8Array)&&typeof t.hash!="string"||typeof t.index!="number")throw new Error("Error adding input.");const n=typeof t.hash=="string"?Nl(kr(t.hash)):t.hash;this.tx.addInput(n,t.index,t.sequence)}addOutput(t){if(t.script===void 0||t.value===void 0||!(t.script instanceof Uint8Array)||typeof t.value!="bigint")throw new Error("Error adding output.");this.tx.addOutput(t.script,t.value)}toBuffer(){return this.tx.toBuffer()}}function D_(e,t,n){switch(n){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Cd(1,e.partialSig);case"multisig":const r=Ga({output:t});return Cd(r.m,e.partialSig,r.pubkeys);default:return!1}}function Gu(e){if(e.__UNSAFE_SIGN_NONSEGWIT!==!1)throw new Error("Not BIP174 compliant, can not export")}function Cd(e,t,n){if(!t)return!1;let r;if(n?r=n.map(i=>{const s=sS(i);return t.find(o=>de(o.pubkey,s)===0)}).filter(i=>!!i):r=t,r.length>e)throw new Error("Too many signatures");return r.length===e}function Vg(e){return!!e.finalScriptSig||!!e.finalScriptWitness}function Hd(e){return t=>!(de(e.fingerprint,t.masterFingerprint)||de(e.derivePath(t.path).publicKey,t.pubkey))}function Pc(e){if(typeof e!="number"||e!==Math.floor(e)||e>4294967295||e<0)throw new Error("Invalid 32 bit integer")}function j_(e,t,n){const r=t.__FEE_RATE||e.getFeeRate(),i=t.__EXTRACTED_TX.virtualSize(),s=r*i;if(r>=n.maximumFeeRate)throw new Error(`Warning: You are paying around ${(s/1e8).toFixed(8)} in fees, which is ${r} satoshi per byte for a transaction with a VSize of ${i} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}function Qs(e,t){e.forEach(n=>{if(Mn(n)?B_(n,t):T_(n,t))throw new Error("Can not modify transaction, signatures exist.")})}function K_(e){if(!e.sighashType||!e.partialSig)return;const{partialSig:t,sighashType:n}=e;t.forEach(r=>{const{hashType:i}=So.decode(r.signature);if(n!==i)throw new Error("Signature sighash does not match input sighash type")})}function Lg(e,t,n){if(!Za(e,t))throw new Error(`Can not ${n} for this input with the key ${xe(e)}`)}function G_(e){if(!e.ins.every(n=>n.script&&n.script.length===0&&n.witness&&n.witness.length===0))throw new Error("Format Error: Transaction ScriptSigs are not empty")}function W_(e,t){e.ins.forEach(n=>{$g(t,n)})}function $g(e,t){const n=xe(Nl(Uint8Array.from(t.hash)))+":"+t.index;if(e.__TX_IN_CACHE[n])throw new Error("Duplicate input detected.");e.__TX_IN_CACHE[n]=1}function Dg(e,t){return(n,r,i,s)=>{const o=e({redeem:{output:i}}).output;if(de(r,o))throw new Error(`${t} for ${s} #${n} doesn't match the scriptPubKey in the prevout`)}}const Fd=Dg(cc,"Redeem script"),Md=Dg(uc,"Witness script");function qd(e,t,n,r){if(!n.every(Vg))throw new Error(`PSBT must be finalized to calculate ${t}`);if(e==="__FEE_RATE"&&r.__FEE_RATE)return r.__FEE_RATE;if(e==="__FEE"&&r.__FEE)return r.__FEE;let i,s=!0;if(r.__EXTRACTED_TX?(i=r.__EXTRACTED_TX,s=!1):i=r.__TX.clone(),Xg(n,i,r,s),e==="__FEE_RATE")return r.__FEE_RATE;if(e==="__FEE")return r.__FEE}function X_(e,t,n,r,i,s){const o=Zg(n);if(!D_(t,n,o))throw new Error(`Can not finalize input #${e}`);return z_(n,o,t.partialSig,r,i,s)}function z_(e,t,n,r,i,s){let o,c;const a=Z_(e,t,n),u=s?uc({redeem:a}):null,f=i?cc({redeem:u||a}):null;return r?(u?c=ga(u.witness):c=ga(a.witness),f&&(o=f.input)):f?o=f.input:o=a.input,{finalScriptSig:o,finalScriptWitness:c}}function Vd(e,t,n,r,i){const s=Rt(e,t),{hash:o,sighashType:c,script:a}=jg(t,s,r,!1,i);return Lg(n,a,"sign"),{hash:o,sighashType:c}}function jg(e,t,n,r,i){const s=n.__TX,o=t.sighashType||gt.SIGHASH_ALL;Gg(o,i);let c,a;if(t.nonWitnessUtxo){const l=Ja(n,t,e),d=s.ins[e].hash,y=l.getHash();if(de(d,y)!==0)throw new Error(`Non-witness UTXO hash for input #${e} doesn't match the hash specified in the prevout`);const g=s.ins[e].index;a=l.outs[g]}else if(t.witnessUtxo)a=t.witnessUtxo;else throw new Error("Need a Utxo input item for signing");const{meaningfulScript:u,type:f}=Qa(a.script,e,"input",t.redeemScript,t.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(f)>=0)c=s.hashForWitnessV0(e,u,a.value,o);else if(Ya(u)){const l=oc({hash:u.slice(2)}).output;c=s.hashForWitnessV0(e,l,a.value,o)}else{if(t.nonWitnessUtxo===void 0&&n.__UNSAFE_SIGN_NONSEGWIT===!1)throw new Error(`Input #${e} has witnessUtxo but non-segwit script: ${xe(u)}`);!r&&n.__UNSAFE_SIGN_NONSEGWIT!==!1&&console.warn(`Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as Psbt's predecessor (TransactionBuilder - now removed) when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.
10
10
  *********************
11
11
  PROCEED WITH CAUTION!
12
12
  *********************`),c=s.hashForSignature(e,u,o)}return{script:u,sighashType:o,hash:c}}function Y_(e,t,n,r){const i=[];if(t.tapInternalKey){const o=Kg(e,t,r);o&&i.push(o)}if(t.tapScriptSig){const o=t.tapScriptSig.map(c=>c.pubkey);i.push(...o)}return i.map(o=>Kf(e,t,n,o,r)).flat()}function Kg(e,t,n){const{script:r}=Hl(e,t,n);return Hg(r)?r.subarray(2,34):null}function Ld(e){return e.length===64?e:e.subarray(0,64)}function Kf(e,t,n,r,i,s,o){const c=i.__TX,a=t.sighashType||gt.SIGHASH_DEFAULT;Gg(a,o);const u=n.map((g,m)=>Hl(m,g,i)),f=u.map(g=>g.script),l=u.map(g=>g.value),d=[];if(t.tapInternalKey&&!s){const g=Kg(e,t,i)||Uint8Array.from([]);if(de(zc(r),g)===0){const m=c.hashForWitnessV1(e,f,l,a);d.push({pubkey:r,hash:m})}}const y=(t.tapLeafScript||[]).filter(g=>Za(r,g.script)).map(g=>{const m=Er({output:g.script,version:g.leafVersion});return Object.assign({hash:m},g)}).filter(g=>!s||de(s,g.hash)===0).map(g=>{const m=c.hashForWitnessV1(e,f,l,a,g.hash);return{pubkey:r,hash:m,leafHash:g.hash}});return d.concat(y)}function Gg(e,t){if(t&&t.indexOf(e)<0){const n=eS(e);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${n}`)}}function Z_(e,t,n){let r;switch(t){case"multisig":const i=Q_(e,n);r=Ga({output:e,signatures:i});break;case"pubkey":r=ig({output:e,signature:n[0].signature});break;case"pubkeyhash":r=oc({output:e,pubkey:n[0].pubkey,signature:n[0].signature});break;case"witnesspubkeyhash":r=za({output:e,pubkey:n[0].pubkey,signature:n[0].signature});break}return r}function J_(e,t,n){const r=n.__TX,i={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(i.isP2SH=!!t.redeemScript,i.isP2WSH=!!t.witnessScript,t.witnessScript)i.script=t.witnessScript;else if(t.redeemScript)i.script=t.redeemScript;else if(t.nonWitnessUtxo){const s=Ja(n,t,e),o=r.ins[e].index;i.script=s.outs[o].script}else t.witnessUtxo&&(i.script=t.witnessUtxo.script);return(t.witnessScript||Ya(i.script))&&(i.isSegwit=!0),i}function $d(e,t,n){const r=Rt(t,e);if(!r.bip32Derivation||r.bip32Derivation.length===0)throw new Error("Need bip32Derivation to sign with HD");const i=r.bip32Derivation.map(o=>{if(de(o.masterFingerprint,n.fingerprint)===0)return o}).filter(o=>!!o);if(i.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return i.map(o=>{const c=n.derivePath(o.path);if(de(o.pubkey,c.publicKey)!==0)throw new Error("pubkey did not match bip32Derivation");return c})}function Q_(e,t){return Ga({output:e}).pubkeys.map(r=>(t.filter(i=>de(i.pubkey,r)===0)[0]||{}).signature).filter(r=>!!r)}function Wg(e){let t=0;function n(o){return t+=o,e.slice(t-o,t)}function r(){const o=Ls(e,t);return t+=Bn(o.bigintValue),o.numberValue}function i(){return n(r())}function s(){const o=r(),c=[];for(let a=0;a<o;a++)c.push(i());return c}return s()}function eS(e){let t=e&gt.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(e&31){case gt.SIGHASH_ALL:t+="SIGHASH_ALL";break;case gt.SIGHASH_SINGLE:t+="SIGHASH_SINGLE";break;case gt.SIGHASH_NONE:t+="SIGHASH_NONE";break}return t}function Gf(e,t,n){e.__NON_WITNESS_UTXO_BUF_CACHE[n]=t.nonWitnessUtxo;const r=gt.fromBuffer(t.nonWitnessUtxo);e.__NON_WITNESS_UTXO_TX_CACHE[n]=r;const i=e,s=n;delete t.nonWitnessUtxo,Object.defineProperty(t,"nonWitnessUtxo",{enumerable:!0,get(){const o=i.__NON_WITNESS_UTXO_BUF_CACHE[s],c=i.__NON_WITNESS_UTXO_TX_CACHE[s];if(o!==void 0)return o;{const a=c.toBuffer();return i.__NON_WITNESS_UTXO_BUF_CACHE[s]=a,a}},set(o){i.__NON_WITNESS_UTXO_BUF_CACHE[s]=o}})}function Xg(e,t,n,r){let i=0n;e.forEach((a,u)=>{if(r&&a.finalScriptSig&&(t.ins[u].script=a.finalScriptSig),r&&a.finalScriptWitness&&(t.ins[u].witness=Wg(a.finalScriptWitness)),a.witnessUtxo)i+=a.witnessUtxo.value;else if(a.nonWitnessUtxo){const f=Ja(n,a,u),l=t.ins[u].index,d=f.outs[l];i+=d.value}});const s=t.outs.reduce((a,u)=>a+u.value,0n),o=i-s;if(o<0)throw new Error("Outputs are spending more than Inputs");const c=t.virtualSize();n.__FEE=o,n.__EXTRACTED_TX=t,n.__FEE_RATE=Math.floor(Number(o/BigInt(c)))}function Ja(e,t,n){const r=e.__NON_WITNESS_UTXO_TX_CACHE;return r[n]||Gf(e,t,n),r[n]}function zg(e,t,n){const{script:r}=Hl(e,t,n);return r}function Hl(e,t,n){if(t.witnessUtxo!==void 0)return{script:t.witnessUtxo.script,value:t.witnessUtxo.value};if(t.nonWitnessUtxo!==void 0){const i=Ja(n,t,e).outs[n.__TX.ins[e].index];return{script:i.script,value:i.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function tS(e,t,n,r){const i=zg(n,t,r),{meaningfulScript:s}=Qa(i,n,"input",t.redeemScript,t.witnessScript);return Za(e,s)}function nS(e,t,n,r){const i=r.__TX.outs[n].script,{meaningfulScript:s}=Qa(i,n,"output",t.redeemScript,t.witnessScript);return Za(e,s)}function rS(e){if(!e)return;const t=lt(e);if(!t)return;const n=t[t.length-1];if(!(!(n instanceof Uint8Array)||Yg(n)||oS(n)||!lt(n)))return n}function iS(e){if(!e)return;const t=Wg(e),n=t[t.length-1];if(!(Yg(n)||!lt(n)))return n}function sS(e){if(e.length===65){const t=e[64]&1,n=e.slice(0,33);return n[0]=2|t,n}return e.slice()}function Yg(e){return e.length===33&&Ab(e)}function oS(e){return Ir(e)}function Qa(e,t,n,r,i){const s=Cg(e),o=s&&r&&kd(r),c=kd(e);if(s&&r===void 0)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((c||o)&&i===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let a;return o?(a=i,Fd(t,e,r,n),Md(t,r,i,n),wa(a)):c?(a=i,Md(t,e,i,n),wa(a)):s?(a=r,Fd(t,e,r,n)):a=e,{meaningfulScript:a,type:o?"p2sh-p2wsh":s?"p2sh":c?"p2wsh":"raw"}}function wa(e){if(Ya(e)||Cg(e))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function Zg(e){return Ya(e)?"witnesspubkeyhash":S_(e)?"pubkeyhash":E_(e)?"multisig":__(e)?"pubkey":"nonstandard"}function eo(e){return[...Array(e).keys()]}u2($1);const Ns={Mainnet:"mainnet",Testnet:"testnet"},ba="abcdefghijklmnopqrstuvwxyz234567",ks=Object.create(null);for(let e=0;e<ba.length;e++)ks[ba[e]]=e;ks[0]=ks.o;ks[1]=ks.i;function cS(e){let t=0,n=0,r="";function i(s){return t<0?n|=s>>-t:n=s<<t&248,t>3?(t-=8,1):(t<4&&(r+=ba[n>>3],t+=5),0)}for(let s=0;s<e.length;)s+=i(e[s]);return r+(t<0?ba[n>>3]:"")}function aS(e){let t=0,n=0;const r=new Uint8Array(e.length*4/3|0);let i=0;function s(o){let c=ks[o.toLowerCase()];if(c===void 0)throw new Error(`Invalid character: ${JSON.stringify(o)}`);c<<=3,n|=c>>>t,t+=5,t>=8&&(r[i++]=n,t-=8,t>0?n=c<<5-t&255:n=0)}for(const o of e)s(o);return r.slice(0,i)}const uS=new Uint32Array([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);function fS(e){let t=-1;for(let n=0;n<e.length;n++){const i=(e[n]^t)&255;t=uS[i]^t>>>8}return(t^-1)>>>0}const Rc="__principal__",lS=2,Dd=4,hS="aaaaa-aa";let Ke=class ds{static anonymous(){return new this(new Uint8Array([Dd]))}static managementCanister(){return this.fromText(hS)}static selfAuthenticating(t){const n=t2(t);return new this(new Uint8Array([...n,lS]))}static from(t){if(typeof t=="string")return ds.fromText(t);if(Object.getPrototypeOf(t)===Uint8Array.prototype)return new ds(t);if(ds.isPrincipal(t))return new ds(t._arr);throw new Error(`Impossible to convert ${JSON.stringify(t)} to Principal.`)}static fromHex(t){return new this(sc(t))}static fromText(t){let n=t;if(t.includes(Rc)){const o=JSON.parse(t);Rc in o&&(n=o[Rc])}const r=n.toLowerCase().replace(/-/g,"");let i=aS(r);i=i.slice(4,i.length);const s=new this(i);if(s.toText()!==n)throw new Error(`Principal "${s.toText()}" does not have a valid checksum (original value "${n}" may not be a valid Principal ID).`);return s}static fromUint8Array(t){return new this(t)}static isPrincipal(t){return t instanceof ds||typeof t=="object"&&t!==null&&"_isPrincipal"in t&&t._isPrincipal===!0&&"_arr"in t&&t._arr instanceof Uint8Array}constructor(t){this._arr=t,this._isPrincipal=!0}isAnonymous(){return this._arr.byteLength===1&&this._arr[0]===Dd}toUint8Array(){return this._arr}toHex(){return rt(this._arr).toUpperCase()}toText(){const t=new ArrayBuffer(4);new DataView(t).setUint32(0,fS(this._arr));const r=new Uint8Array(t),i=new Uint8Array([...r,...this._arr]),o=cS(i).match(/.{1,5}/g);if(!o)throw new Error;return o.join("-")}toString(){return this.toText()}toJSON(){return{[Rc]:this.toText()}}compareTo(t){for(let n=0;n<Math.min(this._arr.length,t._arr.length);n++){if(this._arr[n]<t._arr[n])return"lt";if(this._arr[n]>t._arr[n])return"gt"}return this._arr.length<t._arr.length?"lt":this._arr.length>t._arr.length?"gt":"eq"}ltEq(t){const n=this.compareTo(t);return n=="lt"||n=="eq"}gtEq(t){const n=this.compareTo(t);return n=="gt"||n=="eq"}};function Le(...e){const t=new Uint8Array(e.reduce((r,i)=>r+i.byteLength,0));let n=0;for(const r of e)t.set(r,n),n+=r.byteLength;return t}class $s{save(){return this._view}restore(t){if(!(t instanceof Uint8Array))throw new Error("Checkpoint must be a Uint8Array");this._view=t}constructor(t,n=t?.byteLength||0){if(t&&!(t instanceof Uint8Array))try{t=Jg(t)}catch{throw new Error("Buffer must be a Uint8Array")}if(n<0||!Number.isInteger(n))throw new Error("Length must be a non-negative integer");if(t&&n>t.byteLength)throw new Error("Length cannot exceed buffer length");this._buffer=t||new Uint8Array(0),this._view=new Uint8Array(this._buffer.buffer,0,n)}get buffer(){return this._view.slice()}get byteLength(){return this._view.byteLength}read(t){const n=this._view.subarray(0,t);return this._view=this._view.subarray(t),n.slice()}readUint8(){if(this._view.byteLength===0)return;const t=this._view[0];return this._view=this._view.subarray(1),t}write(t){if(!(t instanceof Uint8Array))throw new Error("Buffer must be a Uint8Array");const n=this._view.byteLength;this._view.byteOffset+this._view.byteLength+t.byteLength>=this._buffer.byteLength?this.alloc(t.byteLength):this._view=new Uint8Array(this._buffer.buffer,this._view.byteOffset,this._view.byteLength+t.byteLength),this._view.set(t,n)}get end(){return this._view.byteLength===0}alloc(t){if(t<=0||!Number.isInteger(t))throw new Error("Amount must be a positive integer");const n=new Uint8Array((this._buffer.byteLength+t)*1.2|0),r=new Uint8Array(n.buffer,0,this._view.byteLength+t);r.set(this._view),this._buffer=n,this._view=r}}function Jg(e){if(!e)throw new Error("Input cannot be null or undefined");return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):"buffer"in e?Jg(e.buffer):new Uint8Array(e)}function dS(e,t){if(e.byteLength!==t.byteLength)return e.byteLength-t.byteLength;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return e[n]-t[n];return 0}function pS(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(e.buffer,e.byteOffset,e.byteLength)}function yS(e){const n=new TextEncoder().encode(e);let r=0;for(const i of n)r=(r*223+i)%2**32;return r}function an(e){if(/^_\d+_$/.test(e)||/^_0x[0-9a-fA-F]+_$/.test(e)){const t=+e.slice(1,-1);if(Number.isSafeInteger(t)&&t>=0&&t<2**32)return t}return yS(e)}function Qg(e){const t=BigInt(e);if(e<=0)throw new RangeError("Input must be positive");return t.toString(2).length-1}function Wf(e){const t=BigInt(e);if(e<0)throw new RangeError("Input must be non-negative");return BigInt(1)<<t}function em(){throw new Error("unexpected end of buffer")}function $i(e,t){return e.byteLength<t&&em(),e.read(t)}function Di(e){const t=e.readUint8();return t===void 0&&em(),t}function ft(e){if(typeof e=="number"&&(e=BigInt(e)),e<BigInt(0))throw new Error("Cannot leb encode negative values.");const t=(e===BigInt(0)?0:Qg(e))+1,n=new $s(new Uint8Array(t),0);for(;;){const r=Number(e&BigInt(127));if(e/=BigInt(128),e===BigInt(0)){n.write(new Uint8Array([r]));break}else n.write(new Uint8Array([r|128]))}return n.buffer}function Bt(e){let t=BigInt(1),n=BigInt(0),r;do r=Di(e),n+=BigInt(r&127).valueOf()*t,t*=BigInt(128);while(r>=128);return n}function vt(e){typeof e=="number"&&(e=BigInt(e));const t=e<BigInt(0);t&&(e=-e-BigInt(1));const n=(e===BigInt(0)?0:Qg(e))+1,r=new $s(new Uint8Array(n),0);for(;;){const s=i(e);if(e/=BigInt(128),t&&e===BigInt(0)&&(s&64)!==0||!t&&e===BigInt(0)&&(s&64)===0){r.write(new Uint8Array([s]));break}else r.write(new Uint8Array([s|128]))}function i(s){const o=s%BigInt(128);return Number(t?BigInt(128)-o-BigInt(1):o)}return r.buffer}function ti(e){const t=new Uint8Array(e.buffer);let n=0;for(;n<t.byteLength;n++)if(t[n]<128){if((t[n]&64)===0)return Bt(e);break}const r=new Uint8Array($i(e,n+1));let i=BigInt(0);for(let s=r.byteLength-1;s>=0;s--)i=i*BigInt(128)+BigInt(128-(r[s]&127)-1);return-i-BigInt(1)}function gS(e,t){if(BigInt(e)<BigInt(0))throw new Error("Cannot write negative values.");return tm(e,t)}function tm(e,t){e=BigInt(e);const n=new $s(new Uint8Array(Math.min(1,t)),0);let r=0,i=BigInt(256),s=BigInt(0),o=Number(e%i);for(n.write(new Uint8Array([o]));++r<t;)e<0&&s===BigInt(0)&&o!==0&&(s=BigInt(1)),o=Number((e/i-s)%BigInt(256)),n.write(new Uint8Array([o])),i*=BigInt(256);return n.buffer}function nm(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let n=BigInt(Di(e)),r=BigInt(1),i=0;for(;++i<t;){r*=BigInt(256);const s=BigInt(Di(e));n=n+r*s}return n}function mS(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let n=nm(e,t);const r=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return n>=r&&(n-=r*BigInt(2)),n}var Ve;(function(e){e[e.Null=-1]="Null",e[e.Bool=-2]="Bool",e[e.Nat=-3]="Nat",e[e.Int=-4]="Int",e[e.Float32=-13]="Float32",e[e.Float64=-14]="Float64",e[e.Text=-15]="Text",e[e.Reserved=-16]="Reserved",e[e.Empty=-17]="Empty",e[e.Opt=-18]="Opt",e[e.Vector=-19]="Vector",e[e.Record=-20]="Record",e[e.Variant=-21]="Variant",e[e.Func=-22]="Func",e[e.Service=-23]="Service",e[e.Principal=-24]="Principal"})(Ve||(Ve={}));const Yc="DIDL",jd=400;function No(e,t,n){return e.map((r,i)=>n(r,t[i]))}class wS{constructor(){this._typs=[],this._idx=new Map,this._idxRefCount=new Map}has(t){return this._idx.has(t.name)}add(t,n){const r=this._typs.length;this._idx.set(t.name,r),this._idxRefCount.set(r,1),this._typs.push(n)}merge(t,n){const r=this._idx.get(t.name),i=this._idx.get(n);if(r===void 0)throw new Error("Missing type index for "+t);if(i===void 0)throw new Error("Missing type index for "+n);this._typs[r]=this._typs[i];const s=this._getIdxRefCount(i);this._idxRefCount.set(i,s-1),this._idx.delete(n),this._compactFromEnd()}_getIdxRefCount(t){return this._idxRefCount.get(t)||0}_compactFromEnd(){for(;this._typs.length>0;){const t=this._typs.length-1;if(this._getIdxRefCount(t)>0)break;this._typs.pop(),this._idxRefCount.delete(t)}}encode(){const t=ft(this._typs.length),n=Le(...this._typs);return Le(t,n)}indexOf(t){if(!this._idx.has(t))throw new Error("Missing type index for "+t);return vt(this._idx.get(t)||0)}}class bS{visitType(t,n){throw new Error("Not implemented")}visitPrimitive(t,n){return this.visitType(t,n)}visitEmpty(t,n){return this.visitPrimitive(t,n)}visitBool(t,n){return this.visitPrimitive(t,n)}visitNull(t,n){return this.visitPrimitive(t,n)}visitReserved(t,n){return this.visitPrimitive(t,n)}visitText(t,n){return this.visitPrimitive(t,n)}visitNumber(t,n){return this.visitPrimitive(t,n)}visitInt(t,n){return this.visitNumber(t,n)}visitNat(t,n){return this.visitNumber(t,n)}visitFloat(t,n){return this.visitPrimitive(t,n)}visitFixedInt(t,n){return this.visitNumber(t,n)}visitFixedNat(t,n){return this.visitNumber(t,n)}visitPrincipal(t,n){return this.visitPrimitive(t,n)}visitConstruct(t,n){return this.visitType(t,n)}visitVec(t,n,r){return this.visitConstruct(t,r)}visitOpt(t,n,r){return this.visitConstruct(t,r)}visitRecord(t,n,r){return this.visitConstruct(t,r)}visitTuple(t,n,r){const i=n.map((s,o)=>[`_${o}_`,s]);return this.visitRecord(t,i,r)}visitVariant(t,n,r){return this.visitConstruct(t,r)}visitRec(t,n,r){return this.visitConstruct(n,r)}visitFunc(t,n){return this.visitConstruct(t,n)}visitService(t,n){return this.visitConstruct(t,n)}}var Be;(function(e){e.EmptyClass="__IDL_EmptyClass__",e.UnknownClass="__IDL_UnknownClass__",e.BoolClass="__IDL_BoolClass__",e.NullClass="__IDL_NullClass__",e.ReservedClass="__IDL_ReservedClass__",e.TextClass="__IDL_TextClass__",e.IntClass="__IDL_IntClass__",e.NatClass="__IDL_NatClass__",e.FloatClass="__IDL_FloatClass__",e.FixedIntClass="__IDL_FixedIntClass__",e.FixedNatClass="__IDL_FixedNatClass__",e.VecClass="__IDL_VecClass__",e.OptClass="__IDL_OptClass__",e.RecordClass="__IDL_RecordClass__",e.TupleClass="__IDL_TupleClass__",e.VariantClass="__IDL_VariantClass__",e.RecClass="__IDL_RecClass__",e.PrincipalClass="__IDL_PrincipalClass__",e.FuncClass="__IDL_FuncClass__",e.ServiceClass="__IDL_ServiceClass__"})(Be||(Be={}));class eu{display(){return this.name}valueToString(t){return wt(t)}buildTypeTable(t){t.has(this)||this._buildTypeTableImpl(t)}}class Rn extends eu{checkType(t){if(this.name!==t.name)throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`);return t}_buildTypeTableImpl(t){}}class pi extends eu{checkType(t){if(t instanceof Nn){const n=t.getType();if(typeof n>"u")throw new Error("type mismatch with uninitialized type");return n}throw new Error(`type mismatch: type on the wire ${t.name}, expect type ${this.name}`)}encodeType(t){return t.indexOf(this.name)}}class Fl extends Rn{get typeName(){return Be.EmptyClass}static[Symbol.hasInstance](t){return t.typeName===Be.EmptyClass}accept(t,n){return t.visitEmpty(this,n)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(){throw new Error("Empty cannot appear as a function argument")}valueToString(){throw new Error("Empty cannot appear as a value")}encodeType(){return vt(Ve.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}}class rm extends eu{get typeName(){return Be.UnknownClass}static[Symbol.hasInstance](t){return t.typeName===Be.UnknownClass}checkType(t){throw new Error("Method not implemented for unknown.")}accept(t,n){throw t.visitType(this,n)}covariant(t){throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(){throw new Error("Unknown cannot appear as a function argument")}valueToString(){throw new Error("Unknown cannot appear as a value")}encodeType(){throw new Error("Unknown cannot be serialized")}decodeValue(t,n){let r=n.decodeValue(t,n);Object(r)!==r&&(r=Object(r));let i;return n instanceof Nn?i=()=>n.getType():i=()=>n,Object.defineProperty(r,"type",{value:i,writable:!0,enumerable:!1,configurable:!0}),r}_buildTypeTableImpl(){throw new Error("Unknown cannot be serialized")}get name(){return"Unknown"}}class im extends Rn{get typeName(){return Be.BoolClass}static[Symbol.hasInstance](t){return t.typeName===Be.BoolClass}accept(t,n){return t.visitBool(this,n)}covariant(t){if(typeof t=="boolean")return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){return new Uint8Array([t?1:0])}encodeType(){return vt(Ve.Bool)}decodeValue(t,n){switch(this.checkType(n),Di(t)){case 0:return!1;case 1:return!0;default:throw new Error("Boolean value out of range")}}get name(){return"bool"}}class ko extends Rn{get typeName(){return Be.NullClass}static[Symbol.hasInstance](t){return t.typeName===Be.NullClass}accept(t,n){return t.visitNull(this,n)}covariant(t){if(t===null)return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(){return new Uint8Array(0)}encodeType(){return vt(Ve.Null)}decodeValue(t,n){return this.checkType(n),null}get name(){return"null"}}class hi extends Rn{get typeName(){return Be.ReservedClass}static[Symbol.hasInstance](t){return t.typeName===Be.ReservedClass}accept(t,n){return t.visitReserved(this,n)}covariant(t){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return vt(Ve.Reserved)}decodeValue(t,n){return n.name!==this.name&&n.decodeValue(t,n),null}get name(){return"reserved"}}class sm extends Rn{get typeName(){return Be.TextClass}static[Symbol.hasInstance](t){return t.typeName===Be.TextClass}accept(t,n){return t.visitText(this,n)}covariant(t){if(typeof t=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=new TextEncoder().encode(t),r=ft(n.byteLength);return Le(r,n)}encodeType(){return vt(Ve.Text)}decodeValue(t,n){this.checkType(n);const r=Bt(t),i=$i(t,Number(r));return new TextDecoder("utf8",{fatal:!0}).decode(i)}get name(){return"text"}valueToString(t){return'"'+t+'"'}}class Ml extends Rn{get typeName(){return Be.IntClass}static[Symbol.hasInstance](t){return t.typeName===Be.IntClass}accept(t,n){return t.visitInt(this,n)}covariant(t){if(typeof t=="bigint"||Number.isInteger(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){return vt(t)}encodeType(){return vt(Ve.Int)}decodeValue(t,n){return this.checkType(n),ti(t)}get name(){return"int"}valueToString(t){return t.toString()}}class ql extends Rn{get typeName(){return Be.NatClass}static[Symbol.hasInstance](t){return t.typeName===Be.NatClass}accept(t,n){return t.visitNat(this,n)}covariant(t){if(typeof t=="bigint"&&t>=BigInt(0)||Number.isInteger(t)&&t>=0)return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){return ft(t)}encodeType(){return vt(Ve.Nat)}decodeValue(t,n){return this.checkType(n),Bt(t)}get name(){return"nat"}valueToString(t){return t.toString()}}class Vl extends Rn{get typeName(){return Be.FloatClass}static[Symbol.hasInstance](t){return t.typeName===Be.FloatClass}constructor(t){if(super(),this._bits=t,t!==32&&t!==64)throw new Error("not a valid float type")}accept(t,n){return t.visitFloat(this,n)}covariant(t){if(typeof t=="number"||t instanceof Number)return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=new ArrayBuffer(this._bits/8),r=new DataView(n);return this._bits===32?r.setFloat32(0,t,!0):r.setFloat64(0,t,!0),new Uint8Array(n)}encodeType(){const t=this._bits===32?Ve.Float32:Ve.Float64;return vt(t)}decodeValue(t,n){this.checkType(n);const r=$i(t,this._bits/8),i=pS(r);return this._bits===32?i.getFloat32(0,!0):i.getFloat64(0,!0)}get name(){return"float"+this._bits}valueToString(t){return t.toString()}}class ji extends Rn{get typeName(){return Be.FixedIntClass}static[Symbol.hasInstance](t){return t.typeName===Be.FixedIntClass}constructor(t){super(),this._bits=t}accept(t,n){return t.visitFixedInt(this,n)}covariant(t){const n=Wf(this._bits-1)*BigInt(-1),r=Wf(this._bits-1)-BigInt(1);let i=!1;if(typeof t=="bigint")i=t>=n&&t<=r;else if(Number.isInteger(t)){const s=BigInt(t);i=s>=n&&s<=r}else i=!1;if(i)return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){return tm(t,this._bits/8)}encodeType(){const t=Math.log2(this._bits)-3;return vt(-9-t)}decodeValue(t,n){this.checkType(n);const r=mS(t,this._bits/8);return this._bits<=32?Number(r):r}get name(){return`int${this._bits}`}valueToString(t){return t.toString()}}class ai extends Rn{get typeName(){return Be.FixedNatClass}static[Symbol.hasInstance](t){return t.typeName===Be.FixedNatClass}constructor(t){super(),this._bits=t}accept(t,n){return t.visitFixedNat(this,n)}covariant(t){const n=Wf(this._bits);let r=!1;if(typeof t=="bigint"&&t>=BigInt(0)?r=t<n:Number.isInteger(t)&&t>=0?r=BigInt(t)<n:r=!1,r)return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){return gS(t,this._bits/8)}encodeType(){const t=Math.log2(this._bits)-3;return vt(-5-t)}decodeValue(t,n){this.checkType(n);const r=nm(t,this._bits/8);return this._bits<=32?Number(r):r}get name(){return`nat${this._bits}`}valueToString(t){return t.toString()}}class Ps extends pi{get typeName(){return Be.VecClass}static[Symbol.hasInstance](t){return t.typeName===Be.VecClass}constructor(t){super(),this._type=t,this._blobOptimization=!1,t instanceof ai&&t._bits===8&&(this._blobOptimization=!0)}accept(t,n){return t.visitVec(this,this._type,n)}covariant(t){const n=this._type instanceof ai?this._type._bits:this._type instanceof ji?this._type._bits:0;if(ArrayBuffer.isView(t)&&n==t.BYTES_PER_ELEMENT*8||Array.isArray(t)&&t.every((r,i)=>{try{return this._type.covariant(r)}catch(s){throw new Error(`Invalid ${this.display()} argument:
@@ -63,17 +63,17 @@ Call context:
63
63
  Headers: ${JSON.stringify(this.headers)}
64
64
  `;return this.bodyText&&(t+=` Body: ${this.bodyText}
65
65
  `),t}}class Aa extends Ue{constructor(){super(),this.name="HttpV3ApiNotSupportedErrorCode",Object.setPrototypeOf(this,Aa.prototype)}toErrorMessage(){return"HTTP request failed: v3 API is not supported"}}class va extends Ue{constructor(t){super(),this.error=t,this.name="HttpFetchErrorCode",Object.setPrototypeOf(this,va.prototype)}toErrorMessage(){return`Failed to fetch HTTP request: ${gc(this.error)}`}}class Ia extends Ue{constructor(t){super(),this.receivedCanisterId=t,this.name="MissingCanisterIdErrorCode",Object.setPrototypeOf(this,Ia.prototype)}toErrorMessage(){return`Canister ID is required, but received ${typeof this.receivedCanisterId} instead. If you are using automatically generated declarations, this may be because your application is not setting the canister ID in process.env correctly.`}}class ah extends Ue{constructor(t){super(),this.request=t,this.name="InvalidReadStateRequestErrorCode",Object.setPrototypeOf(this,ah.prototype)}toErrorMessage(){return`Invalid read state request: ${this.request}`}}class Oa extends Ue{constructor(t){super(),this.error=t,this.name="ExpiryJsonDeserializeErrorCode",Object.setPrototypeOf(this,Oa.prototype)}toErrorMessage(){return`Failed to deserialize expiry: ${this.error}`}}function gc(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e)}catch{return String(e)}}const Ss=new Error("unreachable");function Ba(e){if(!e)throw new Error("Input cannot be null or undefined");return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):Array.isArray(e)?new Uint8Array(e):"buffer"in e?Ba(e.buffer):new Uint8Array(e)}function pu(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function nl(e){if(typeof e=="string")return sw(e);if(typeof e=="number")return En(ft(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return En(Ba(e));if(Array.isArray(e)){const t=e.map(nl);return En($e(...t))}else{if(e&&typeof e=="object"&&e._isPrincipal)return En(e.toUint8Array());if(typeof e=="object"&&e!==null&&typeof e.toHash=="function")return nl(e.toHash());if(typeof e=="object")return Na(e);if(typeof e=="bigint")return En(ft(e))}throw et.fromCode(new nh(e))}const sw=e=>{const t=new TextEncoder().encode(e);return En(t)};function Zu(e){return Na(e)}function Na(e){const r=Object.entries(e).filter(([,o])=>o!==void 0).map(([o,c])=>{const a=sw(o),u=nl(c);return[a,u]}).sort(([o],[c])=>dS(o,c)),i=$e(...r.map(o=>$e(...o)));return En(i)}new TextEncoder().encode(`
66
- ic-request`);const nx=new TextEncoder().encode("\vic-response");new TextEncoder().encode("ic-request-auth-delegation");class s0{getPrincipal(){return Ke.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}}class Ji extends Error{constructor(t){super(t),this.name="DecodingError"}}const ow=55799,cw=Symbol("CBOR_STOP_CODE");var Ln=(e=>(e[e.False=20]="False",e[e.True=21]="True",e[e.Null=22]="Null",e[e.Undefined=23]="Undefined",e[e.Break=31]="Break",e))(Ln||{}),Tt=(e=>(e[e.UnsignedInteger=0]="UnsignedInteger",e[e.NegativeInteger=1]="NegativeInteger",e[e.ByteString=2]="ByteString",e[e.TextString=3]="TextString",e[e.Array=4]="Array",e[e.Map=5]="Map",e[e.Tag=6]="Tag",e[e.Simple=7]="Simple",e))(Tt||{});const rx=23,ix=255,sx=65535,ox=4294967295,cx=BigInt("0xffffffffffffffff");var qn=(e=>(e[e.Value=23]="Value",e[e.OneByte=24]="OneByte",e[e.TwoBytes=25]="TwoBytes",e[e.FourBytes=26]="FourBytes",e[e.EightBytes=27]="EightBytes",e[e.Indefinite=31]="Indefinite",e))(qn||{});const Ts=!1;function ax(e){return e==null}function aw(e,t){const n=new Uint8Array(t);return n.set(e),n}const ux=new TextDecoder;function fx(e){return(e&224)>>5}function lx(e){return e&31}let Ho=new Uint8Array,no,$n=0;function hx(e,t){Ho=e,$n=0;const n=qi();return t?.(n)??n}function qi(e){const[t,n]=ta();switch(t){case Tt.UnsignedInteger:return Gs(n);case Tt.NegativeInteger:return gx(n);case Tt.ByteString:return uw(n);case Tt.TextString:return rl(n);case Tt.Array:return dx(n);case Tt.Map:return yx(n);case Tt.Tag:return mx(n);case Tt.Simple:return px(n)}throw new Ji(`Unsupported major type: ${t}`)}function ta(){const e=Ho.at($n);if(ax(e))throw new Ji("Provided CBOR data is empty");const t=fx(e),n=lx(e);return $n++,[t,n]}function dx(e,t){const n=Gs(e);if(n===1/0){const i=[];let s=qi();for(;s!==cw;)i.push(s),s=qi();return i}const r=new Array(n);for(let i=0;i<n;i++){const s=qi();r[i]=s}return r}function px(e){switch(e){case Ln.False:return!1;case Ln.True:return!0;case Ln.Null:return null;case Ln.Undefined:return;case Ln.Break:return cw}throw new Ji(`Unrecognized simple type: ${e.toString(2)}`)}function yx(e,t){const n=Gs(e),r={};if(n===1/0){let[i,s]=ta();for(;i!==Tt.Simple&&s!==Ln.Break;){const o=rl(s),c=qi();r[o]=c,[i,s]=ta()}return r}for(let i=0;i<n;i++){const[s,o]=ta();if(s!==Tt.TextString)throw new Ji("Map keys must be text strings");const c=rl(o),a=qi();r[c]=a}return r}function Gs(e){if(e<=qn.Value)return e;switch(no=new DataView(Ho.buffer,Ho.byteOffset+$n),e){case qn.OneByte:return $n++,no.getUint8(0);case qn.TwoBytes:return $n+=2,no.getUint16(0,Ts);case qn.FourBytes:return $n+=4,no.getUint32(0,Ts);case qn.EightBytes:return $n+=8,no.getBigUint64(0,Ts);case qn.Indefinite:return 1/0;default:throw new Ji(`Unsupported integer info: ${e.toString(2)}`)}}function gx(e){const t=Gs(e);return typeof t=="number"?-1-t:-1n-t}function uw(e){const t=Gs(e);if(t>Number.MAX_SAFE_INTEGER)throw new Ji("Byte length is too large");const n=Number(t);return $n+=n,Ho.slice($n-n,$n)}function rl(e){const t=uw(e);return ux.decode(t)}function mx(e,t){const n=Gs(e);if(n===ow)return qi();throw new Ji(`Unsupported tag: ${n}.`)}class uh extends Error{constructor(t){super(t),this.name="SerializationError"}}const wx=2*1024,bx=100,Ex=new TextEncoder;function ro(e){return e<<5}let wn=new Uint8Array(wx),Hn=new DataView(wn.buffer),St=0,Ju=[];function _x(e,t){St=0;const n=t?.(e)??e;return Bx(ow,n,t),wn.slice(0,St)}function fh(e,t){if(St>wn.length-bx&&(wn=aw(wn,wn.length*2),Hn=new DataView(wn.buffer)),e===!1||e===!0||e===null||e===void 0){xx(e);return}if(typeof e=="number"||typeof e=="bigint"){Ox(e);return}if(typeof e=="string"){hw(e);return}if(e instanceof Uint8Array){o0(e);return}if(e instanceof ArrayBuffer){o0(new Uint8Array(e));return}if(Array.isArray(e)){Sx(e,t);return}if(typeof e=="object"){Tx(e,t);return}throw new uh(`Unsupported type: ${typeof e}`)}function Sx(e,t){Ws(Tt.Array,e.length),e.forEach((n,r)=>{fh(t?.(n,r.toString())??n,t)})}function Tx(e,t){Ju=Object.entries(e),Ws(Tt.Map,Ju.length),Ju.forEach(([n,r])=>{hw(n),fh(t?.(r,n)??r,t)})}function Ws(e,t){if(t<=rx){Hn.setUint8(St++,ro(e)|Number(t));return}if(t<=ix){Hn.setUint8(St++,ro(e)|qn.OneByte),Hn.setUint8(St,Number(t)),St+=1;return}if(t<=sx){Hn.setUint8(St++,ro(e)|qn.TwoBytes),Hn.setUint16(St,Number(t),Ts),St+=2;return}if(t<=ox){Hn.setUint8(St++,ro(e)|qn.FourBytes),Hn.setUint32(St,Number(t),Ts),St+=4;return}if(t<=cx){Hn.setUint8(St++,ro(e)|qn.EightBytes),Hn.setBigUint64(St,BigInt(t),Ts),St+=8;return}throw new uh(`Value too large to encode: ${t}`)}function xx(e){Ws(Tt.Simple,Ax(e))}function Ax(e){if(e===!1)return Ln.False;if(e===!0)return Ln.True;if(e===null)return Ln.Null;if(e===void 0)return Ln.Undefined;throw new uh(`Unrecognized simple value: ${e.toString()}`)}function fw(e,t){Ws(e,t.length),St>wn.length-t.length&&(wn=aw(wn,wn.length+t.length),Hn=new DataView(wn.buffer)),wn.set(t,St),St+=t.length}function lw(e,t){Ws(e,t)}function vx(e){lw(Tt.UnsignedInteger,e)}function Ix(e){lw(Tt.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function Ox(e){e>=0?vx(e):Ix(e)}function hw(e){fw(Tt.TextString,Ex.encode(e))}function o0(e){fw(Tt.ByteString,e)}function Bx(e,t,n){Ws(Tt.Tag,e),fh(t,n)}function Nx(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function Qu(e){try{return _x(e,t=>Ke.isPrincipal(t)?t.toUint8Array():xs.isExpiry(t)?t.toBigInt():Nx(t)?t.toCborValue():t)}catch(t){throw et.fromCode(new Zl(t,e))}}function er(e){try{return hx(e)}catch(t){throw et.fromCode(new Yl(t,e))}}const Uc=()=>{if(typeof window<"u"&&window.crypto&&window.crypto.getRandomValues){const e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]}if(typeof crypto<"u"&&crypto.getRandomValues){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return typeof crypto<"u"&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)};var Ui;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})(Ui||(Ui={}));var il;(function(e){e.Call="call"})(il||(il={}));var Fo;(function(e){e.Query="query",e.ReadState="read_state"})(Fo||(Fo={}));function sl(){const e=new ArrayBuffer(16),t=new DataView(e),n=Uc(),r=Uc(),i=Uc(),s=Uc();return t.setUint32(0,n),t.setUint32(4,r),t.setUint32(8,i),t.setUint32(12,s),Object.assign(new Uint8Array(e),{__nonce__:void 0})}const Cc="__expiry__",lh=BigInt(1e3),kx=BigInt(1e6),dw=BigInt(60),Px=BigInt(90)*lh;function pw(e){return e/lh}function Rx(e){return pw(e)/dw}class xs{constructor(t){this.__expiry__=t,this._isExpiry=!0}static fromDeltaInMilliseconds(t,n=0){const r=BigInt(t),i=BigInt(Date.now())+r+BigInt(n);let s;return r<Px?s=pw(i):s=Rx(i)*dw,new xs(s*lh*kx)}toBigInt(){return this.__expiry__}toHash(){return ft(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[Cc]:this.toString()}}static fromJSON(t){const n=JSON.parse(t);if(n[Cc])try{const r=BigInt(n[Cc]);return new xs(r)}catch(r){throw new et(new Oa(`Not a valid BigInt: ${r}`))}throw new et(new Oa(`The input does not contain the key ${Cc}`))}static isExpiry(t){return t instanceof xs||typeof t=="object"&&t!==null&&"_isExpiry"in t&&t._isExpiry===!0&&"__expiry__"in t&&typeof t.__expiry__=="bigint"}}function c0(e=sl){return async t=>{const n=t.request.headers;t.request.headers=n,t.endpoint===Ui.Call&&(t.body.nonce=e())}}function ef(e){const t=[];return e.forEach((n,r)=>{t.push([r,n])}),t}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const hh=BigInt(0),ka=BigInt(1);function Mo(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function As(e,t,n=""){const r=ic(e),i=e?.length,s=t!==void 0;if(!r||s&&i!==t){const o=n&&`"${n}" `,c=s?` of length ${t}`:"",a=r?`length=${i}`:`type=${typeof e}`;throw new Error(o+"expected Uint8Array"+c+", got "+a)}return e}function yw(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?hh:BigInt("0x"+e)}function rr(e){return yw(rt(e))}function qo(e){return On(e),yw(rt(Uint8Array.from(e).reverse()))}function Ut(e,t){return sc(e.toString(16).padStart(t*2,"0"))}function gw(e,t){return Ut(e,t).reverse()}function cn(e,t,n){let r;if(typeof t=="string")try{r=sc(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(ic(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}function a0(e){return Uint8Array.from(e)}const tf=e=>typeof e=="bigint"&&hh<=e;function mw(e,t,n){return tf(e)&&tf(t)&&tf(n)&&t<=e&&e<n}function u0(e,t,n,r){if(!mw(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Vo(e){let t;for(t=0;e>hh;e>>=ka,t+=1);return t}function Ux(e,t){return e>>BigInt(t)&ka}const Qi=e=>(ka<<BigInt(e))-ka;function Cx(e){return typeof e=="function"&&Number.isSafeInteger(e.outputLen)}function mc(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(i,s,o){const c=e[i];if(o&&c===void 0)return;const a=typeof c;if(a!==s||c===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${a}`)}Object.entries(t).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}const ww=()=>{throw new Error("not implemented")};function Lo(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(i!==void 0)return i;const s=e(n,...r);return t.set(n,s),s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const hn=BigInt(0),Ft=BigInt(1),Ci=BigInt(2),bw=BigInt(3),Ew=BigInt(4),_w=BigInt(5),Hx=BigInt(7),Sw=BigInt(8),Fx=BigInt(9),Tw=BigInt(16);function mt(e,t){const n=e%t;return n>=hn?n:t+n}function Zn(e,t,n){let r=e;for(;t-- >hn;)r*=r,r%=n;return r}function f0(e,t){if(e===hn)throw new Error("invert: expected non-zero number");if(t<=hn)throw new Error("invert: expected positive modulus, got "+t);let n=mt(e,t),r=t,i=hn,s=Ft;for(;n!==hn;){const c=r/n,a=r%n,u=i-s*c;r=n,n=a,i=s,s=u}if(r!==Ft)throw new Error("invert: does not exist");return mt(i,t)}function dh(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function xw(e,t){const n=(e.ORDER+Ft)/Ew,r=e.pow(t,n);return dh(e,r,t),r}function Mx(e,t){const n=(e.ORDER-_w)/Sw,r=e.mul(t,Ci),i=e.pow(r,n),s=e.mul(t,i),o=e.mul(e.mul(s,Ci),i),c=e.mul(s,e.sub(o,e.ONE));return dh(e,c,t),c}function qx(e){const t=yi(e),n=Aw(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+Hx)/Tw;return(c,a)=>{let u=c.pow(a,o),f=c.mul(u,r);const l=c.mul(u,i),d=c.mul(u,s),y=c.eql(c.sqr(f),a),g=c.eql(c.sqr(l),a);u=c.cmov(u,f,y),f=c.cmov(d,l,g);const m=c.eql(c.sqr(f),a),E=c.cmov(u,f,m);return dh(c,E,a),E}}function Aw(e){if(e<bw)throw new Error("sqrt is not defined for small field");let t=e-Ft,n=0;for(;t%Ci===hn;)t/=Ci,n++;let r=Ci;const i=yi(e);for(;Pa(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return xw;let s=i.pow(r,t);const o=(t+Ft)/Ci;return function(a,u){if(a.is0(u))return u;if(Pa(a,u)!==1)throw new Error("Cannot find square root");let f=n,l=a.mul(a.ONE,s),d=a.pow(u,t),y=a.pow(u,o);for(;!a.eql(d,a.ONE);){if(a.is0(d))return a.ZERO;let g=1,m=a.sqr(d);for(;!a.eql(m,a.ONE);)if(g++,m=a.sqr(m),g===f)throw new Error("Cannot find square root");const E=Ft<<BigInt(f-g-1),_=a.pow(l,E);f=g,l=a.sqr(_),d=a.mul(d,l),y=a.mul(y,_)}return y}}function Vx(e){return e%Ew===bw?xw:e%Sw===_w?Mx:e%Tw===Fx?qx(e):Aw(e)}const Lx=(e,t)=>(mt(e,t)&Ft)===Ft,$x=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vw(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=$x.reduce((r,i)=>(r[i]="function",r),t);return mc(e,n),e}function yu(e,t,n){if(n<hn)throw new Error("invalid exponent, negatives unsupported");if(n===hn)return e.ONE;if(n===Ft)return t;let r=e.ONE,i=t;for(;n>hn;)n&Ft&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Ft;return r}function es(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((o,c,a)=>e.is0(c)?o:(r[a]=o,e.mul(o,c)),e.ONE),s=e.inv(i);return t.reduceRight((o,c,a)=>e.is0(c)?o:(r[a]=e.mul(o,r[a]),e.mul(o,c)),s),r}function Pa(e,t){const n=(e.ORDER-Ft)/Ci,r=e.pow(t,n),i=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Dx(e,t){t!==void 0&&vb(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function yi(e,t,n=!1,r={}){if(e<=hn)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s,o=!1,c;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const d=t;d.BITS&&(i=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(n=d.isLE),typeof d.modFromBytes=="boolean"&&(o=d.modFromBytes),c=d.allowedLengths}else typeof t=="number"&&(i=t),r.sqrt&&(s=r.sqrt);const{nBitLength:a,nByteLength:u}=Dx(e,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let f;const l=Object.freeze({ORDER:e,isLE:n,BITS:a,BYTES:u,MASK:Qi(a),ZERO:hn,ONE:Ft,allowedLengths:c,create:d=>mt(d,e),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return hn<=d&&d<e},is0:d=>d===hn,isValidNot0:d=>!l.is0(d)&&l.isValid(d),isOdd:d=>(d&Ft)===Ft,neg:d=>mt(-d,e),eql:(d,y)=>d===y,sqr:d=>mt(d*d,e),add:(d,y)=>mt(d+y,e),sub:(d,y)=>mt(d-y,e),mul:(d,y)=>mt(d*y,e),pow:(d,y)=>yu(l,d,y),div:(d,y)=>mt(d*f0(y,e),e),sqrN:d=>d*d,addN:(d,y)=>d+y,subN:(d,y)=>d-y,mulN:(d,y)=>d*y,inv:d=>f0(d,e),sqrt:s||(d=>(f||(f=Vx(e)),f(l,d))),toBytes:d=>n?gw(d,u):Ut(d,u),fromBytes:(d,y=!0)=>{if(c){if(!c.includes(d.length)||d.length>u)throw new Error("Field.fromBytes: expected "+c+" bytes, got "+d.length);const m=new Uint8Array(u);m.set(d,n?0:m.length-d.length),d=m}if(d.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+d.length);let g=n?qo(d):rr(d);if(o&&(g=mt(g,e)),!y&&!l.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:d=>es(l,d),cmov:(d,y,g)=>g?y:d});return Object.freeze(l)}function Iw(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ow(e){const t=Iw(e);return t+Math.ceil(t/2)}function jx(e,t,n=!1){const r=e.length,i=Iw(t),s=Ow(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?qo(e):rr(e),c=mt(o,t-Ft)+Ft;return n?gw(c,i):Ut(c,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hs=BigInt(0),Hi=BigInt(1);function Ra(e,t){const n=t.negate();return e?n:t}function _r(e,t){const n=es(e.Fp,t.map(r=>r.Z));return t.map((r,i)=>e.fromAffine(r.toAffine(n[i])))}function Bw(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function nf(e,t){Bw(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e,s=Qi(e),o=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function l0(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let c=Number(e&i),a=e>>o;c>r&&(c-=s,a+=Hi);const u=t*r,f=u+Math.abs(c)-1,l=c===0,d=c<0,y=t%2!==0;return{nextN:a,offset:f,isZero:l,isNeg:d,isNegF:y,offsetF:u}}function Kx(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function Gx(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const rf=new WeakMap,Nw=new WeakMap;function sf(e){return Nw.get(e)||1}function h0(e){if(e!==Hs)throw new Error("invalid wNAF")}class kw{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let i=t;for(;n>Hs;)n&Hi&&(r=r.add(i)),i=i.double(),n>>=Hi;return r}precomputeWindow(t,n){const{windows:r,windowSize:i}=nf(n,this.bits),s=[];let o=t,c=o;for(let a=0;a<r;a++){c=o,s.push(c);for(let u=1;u<i;u++)c=c.add(o),s.push(c);o=c.double()}return s}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=nf(t,this.bits);for(let c=0;c<o.windows;c++){const{nextN:a,offset:u,isZero:f,isNeg:l,isNegF:d,offsetF:y}=l0(r,c,o);r=a,f?s=s.add(Ra(d,n[y])):i=i.add(Ra(l,n[u]))}return h0(r),{p:i,f:s}}wNAFUnsafe(t,n,r,i=this.ZERO){const s=nf(t,this.bits);for(let o=0;o<s.windows&&r!==Hs;o++){const{nextN:c,offset:a,isZero:u,isNeg:f}=l0(r,o,s);if(r=c,!u){const l=n[a];i=i.add(f?l.negate():l)}}return h0(r),i}getPrecomputes(t,n,r){let i=rf.get(n);return i||(i=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(i=r(i)),rf.set(n,i))),i}cached(t,n,r){const i=sf(t);return this.wNAF(i,this.getPrecomputes(i,t,r),n)}unsafe(t,n,r,i){const s=sf(t);return s===1?this._unsafeLadder(t,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,i)}createCache(t,n){Bw(n,this.bits),Nw.set(t,n),rf.delete(t)}hasCache(t){return sf(t)!==1}}function Wx(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>Hs||r>Hs;)n&Hi&&(s=s.add(i)),r&Hi&&(o=o.add(i)),i=i.double(),n>>=Hi,r>>=Hi;return{p1:s,p2:o}}function Pw(e,t,n,r){Kx(n,e),Gx(r,t);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,c=Vo(BigInt(i));let a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);const u=Qi(a),f=new Array(Number(u)+1).fill(o),l=Math.floor((t.BITS-1)/a)*a;let d=o;for(let y=l;y>=0;y-=a){f.fill(o);for(let m=0;m<s;m++){const E=r[m],_=Number(E>>BigInt(y)&u);f[_]=f[_].add(n[m])}let g=o;for(let m=f.length-1,E=o;m>0;m--)E=E.add(f[m]),g=g.add(E);if(d=d.add(g),y!==0)for(let m=0;m<a;m++)d=d.double()}return d}function d0(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return vw(t),t}else return yi(e,{isLE:n})}function Rw(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const u=t[a];if(!(typeof u=="bigint"&&u>Hs))throw new Error(`CURVE.${a} must be positive bigint`)}const i=d0(t.p,n.Fp,r),s=d0(t.n,n.Fn,r),c=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(const a of c)if(!i.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:s}}const Xx=rr;function ni(e,t){if($o(e),$o(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);const n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function zx(e,t){const n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}function $o(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function Uw(e){if(!ic(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?dt(e):e}function Yx(e,t,n,r){On(e),$o(n),t=Uw(t),t.length>255&&(t=r($e(dt("H2C-OVERSIZE-DST-"),t)));const{outputLen:i,blockLen:s}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const c=$e(t,ni(t.length,1)),a=ni(0,s),u=ni(n,2),f=new Array(o),l=r($e(a,e,u,ni(0,1),c));f[0]=r($e(l,ni(1,1),c));for(let y=1;y<=o;y++){const g=[zx(l,f[y-1]),ni(y+1,1),c];f[y]=r($e(...g))}return $e(...f).slice(0,n)}function Zx(e,t,n,r,i){if(On(e),$o(n),t=Uw(t),t.length>255){const s=Math.ceil(2*r/8);t=i.create({dkLen:s}).update(dt("H2C-OVERSIZE-DST-")).update(t).digest()}if(n>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:n}).update(e).update(ni(n,2)).update(t).update(ni(t.length,1)).digest()}function of(e,t,n){mc(n,{p:"bigint",m:"number",k:"number",hash:"function"});const{p:r,k:i,m:s,hash:o,expand:c,DST:a}=n;if(!Cx(n.hash))throw new Error("expected valid hash");On(e),$o(t);const u=r.toString(2).length,f=Math.ceil((u+i)/8),l=t*s*f;let d;if(c==="xmd")d=Yx(e,a,l,o);else if(c==="xof")d=Zx(e,a,l,i,o);else if(c==="_internal_pass")d=e;else throw new Error('expand must be "xmd" or "xof"');const y=new Array(t);for(let g=0;g<t;g++){const m=new Array(s);for(let E=0;E<s;E++){const _=f*(E+g*s),S=d.subarray(_,_+f);m[E]=mt(Xx(S),r)}y[g]=m}return y}function Cw(e,t){const n=t.map(r=>Array.from(r).reverse());return(r,i)=>{const[s,o,c,a]=n.map(l=>l.reduce((d,y)=>e.add(e.mul(d,r),y))),[u,f]=es(e,[o,a],!0);return r=e.mul(s,u),i=e.mul(i,e.mul(c,f)),{x:r,y:i}}}const Jx=dt("HashToScalar-");function p0(e,t,n){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function r(s){return e.fromAffine(t(s))}function i(s){const o=s.clearCofactor();return o.equals(e.ZERO)?e.ZERO:(o.assertValidity(),o)}return{defaults:n,hashToCurve(s,o){const c=Object.assign({},n,o),a=of(s,2,c),u=r(a[0]),f=r(a[1]);return i(u.add(f))},encodeToCurve(s,o){const c=n.encodeDST?{DST:n.encodeDST}:{},a=Object.assign({},n,c,o),u=of(s,1,a),f=r(u[0]);return i(f)},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(const o of s)if(typeof o!="bigint")throw new Error("expected array of bigints");return i(r(s))},hashToScalar(s,o){const c=e.Fn.ORDER,a=Object.assign({},n,{p:c,m:1,DST:Jx},o);return of(s,1,a)[0][0]}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const y0=(e,t)=>(e+(e>=0?t:-t)/pr)/t;function Qx(e,t,n){const[[r,i],[s,o]]=t,c=y0(o*e,n),a=y0(-i*e,n);let u=e-c*r-a*s,f=-c*i-a*o;const l=u<Fi,d=f<Fi;l&&(u=-u),d&&(f=-f);const y=Qi(Math.ceil(Vo(n)/2))+Jt;if(u<Fi||u>=y||f<Fi||f>=y)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:u,k2neg:d,k2:f}}const Fi=BigInt(0),Jt=BigInt(1),pr=BigInt(2),ys=BigInt(3),ol=BigInt(4);function Ua(e,t){const{BYTES:n}=e;let r;if(typeof t=="bigint")r=t;else{let i=cn("private key",t);try{r=e.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function e3(e,t={}){const n=Rw("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:c}=s;mc(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:a}=t;if(a&&(!r.is0(s.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=r3(r,i);function f(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(K,H,$){const{x:P,y:D}=H.toAffine(),F=r.toBytes(P);if(Mo($,"isCompressed"),$){f();const x=!r.isOdd(D);return $e(t3(x),F)}else return $e(Uint8Array.of(4),F,r.toBytes(D))}function d(K){As(K,void 0,"Point");const{publicKey:H,publicKeyUncompressed:$}=u,P=K.length,D=K[0],F=K.subarray(1);if(P===H&&(D===2||D===3)){const x=r.fromBytes(F);if(!r.isValid(x))throw new Error("bad point: is not on curve, wrong x");const B=m(x);let q;try{q=r.sqrt(B)}catch(G){const X=G instanceof Error?": "+G.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}f();const N=r.isOdd(q);return(D&1)===1!==N&&(q=r.neg(q)),{x,y:q}}else if(P===$&&D===4){const x=r.BYTES,B=r.fromBytes(F.subarray(0,x)),q=r.fromBytes(F.subarray(x,x*2));if(!E(B,q))throw new Error("bad point: is not on curve");return{x:B,y:q}}else throw new Error(`bad point: got length ${P}, expected compressed=${H} or uncompressed=${$}`)}const y=t.toBytes||l,g=t.fromBytes||d;function m(K){const H=r.sqr(K),$=r.mul(H,K);return r.add(r.add($,r.mul(K,s.a)),s.b)}function E(K,H){const $=r.sqr(H),P=m(K);return r.eql($,P)}if(!E(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const _=r.mul(r.pow(s.a,ys),ol),S=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(_,S)))throw new Error("bad curve params: a or b");function w(K,H,$=!1){if(!r.isValid(H)||$&&r.is0(H))throw new Error(`bad point coordinate ${K}`);return H}function T(K){if(!(K instanceof v))throw new Error("ProjectivePoint expected")}function O(K){if(!a||!a.basises)throw new Error("no endo");return Qx(K,a.basises,i.ORDER)}const A=Lo((K,H)=>{const{X:$,Y:P,Z:D}=K;if(r.eql(D,r.ONE))return{x:$,y:P};const F=K.is0();H==null&&(H=F?r.ONE:r.inv(D));const x=r.mul($,H),B=r.mul(P,H),q=r.mul(D,H);if(F)return{x:r.ZERO,y:r.ZERO};if(!r.eql(q,r.ONE))throw new Error("invZ was invalid");return{x,y:B}}),R=Lo(K=>{if(K.is0()){if(t.allowInfinityPoint&&!r.is0(K.Y))return;throw new Error("bad point: ZERO")}const{x:H,y:$}=K.toAffine();if(!r.isValid(H)||!r.isValid($))throw new Error("bad point: x or y not field elements");if(!E(H,$))throw new Error("bad point: equation left != right");if(!K.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function M(K,H,$,P,D){return $=new v(r.mul($.X,K),$.Y,$.Z),H=Ra(P,H),$=Ra(D,$),H.add($)}class v{constructor(H,$,P){this.X=w("x",H),this.Y=w("y",$,!0),this.Z=w("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(H){const{x:$,y:P}=H||{};if(!H||!r.isValid($)||!r.isValid(P))throw new Error("invalid affine point");if(H instanceof v)throw new Error("projective point not allowed");return r.is0($)&&r.is0(P)?v.ZERO:new v($,P,r.ONE)}static fromBytes(H){const $=v.fromAffine(g(As(H,void 0,"point")));return $.assertValidity(),$}static fromHex(H){return v.fromBytes(cn("pointHex",H))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(H=8,$=!0){return V.createCache(this,H),$||this.multiply(ys),this}assertValidity(){R(this)}hasEvenY(){const{y:H}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(H)}equals(H){T(H);const{X:$,Y:P,Z:D}=this,{X:F,Y:x,Z:B}=H,q=r.eql(r.mul($,B),r.mul(F,D)),N=r.eql(r.mul(P,B),r.mul(x,D));return q&&N}negate(){return new v(this.X,r.neg(this.Y),this.Z)}double(){const{a:H,b:$}=s,P=r.mul($,ys),{X:D,Y:F,Z:x}=this;let B=r.ZERO,q=r.ZERO,N=r.ZERO,L=r.mul(D,D),G=r.mul(F,F),X=r.mul(x,x),Y=r.mul(D,F);return Y=r.add(Y,Y),N=r.mul(D,x),N=r.add(N,N),B=r.mul(H,N),q=r.mul(P,X),q=r.add(B,q),B=r.sub(G,q),q=r.add(G,q),q=r.mul(B,q),B=r.mul(Y,B),N=r.mul(P,N),X=r.mul(H,X),Y=r.sub(L,X),Y=r.mul(H,Y),Y=r.add(Y,N),N=r.add(L,L),L=r.add(N,L),L=r.add(L,X),L=r.mul(L,Y),q=r.add(q,L),X=r.mul(F,x),X=r.add(X,X),L=r.mul(X,Y),B=r.sub(B,L),N=r.mul(X,G),N=r.add(N,N),N=r.add(N,N),new v(B,q,N)}add(H){T(H);const{X:$,Y:P,Z:D}=this,{X:F,Y:x,Z:B}=H;let q=r.ZERO,N=r.ZERO,L=r.ZERO;const G=s.a,X=r.mul(s.b,ys);let Y=r.mul($,F),ce=r.mul(P,x),ue=r.mul(D,B),te=r.add($,P),Z=r.add(F,x);te=r.mul(te,Z),Z=r.add(Y,ce),te=r.sub(te,Z),Z=r.add($,D);let ae=r.add(F,B);return Z=r.mul(Z,ae),ae=r.add(Y,ue),Z=r.sub(Z,ae),ae=r.add(P,D),q=r.add(x,B),ae=r.mul(ae,q),q=r.add(ce,ue),ae=r.sub(ae,q),L=r.mul(G,Z),q=r.mul(X,ue),L=r.add(q,L),q=r.sub(ce,L),L=r.add(ce,L),N=r.mul(q,L),ce=r.add(Y,Y),ce=r.add(ce,Y),ue=r.mul(G,ue),Z=r.mul(X,Z),ce=r.add(ce,ue),ue=r.sub(Y,ue),ue=r.mul(G,ue),Z=r.add(Z,ue),Y=r.mul(ce,Z),N=r.add(N,Y),Y=r.mul(ae,Z),q=r.mul(te,q),q=r.sub(q,Y),Y=r.mul(te,ce),L=r.mul(ae,L),L=r.add(L,Y),new v(q,N,L)}subtract(H){return this.add(H.negate())}is0(){return this.equals(v.ZERO)}multiply(H){const{endo:$}=t;if(!i.isValidNot0(H))throw new Error("invalid scalar: out of range");let P,D;const F=x=>V.cached(this,x,B=>_r(v,B));if($){const{k1neg:x,k1:B,k2neg:q,k2:N}=O(H),{p:L,f:G}=F(B),{p:X,f:Y}=F(N);D=G.add(Y),P=M($.beta,L,X,x,q)}else{const{p:x,f:B}=F(H);P=x,D=B}return _r(v,[P,D])[0]}multiplyUnsafe(H){const{endo:$}=t,P=this;if(!i.isValid(H))throw new Error("invalid scalar: out of range");if(H===Fi||P.is0())return v.ZERO;if(H===Jt)return P;if(V.hasCache(this))return this.multiply(H);if($){const{k1neg:D,k1:F,k2neg:x,k2:B}=O(H),{p1:q,p2:N}=Wx(v,P,F,B);return M($.beta,q,N,D,x)}else return V.unsafe(P,H)}multiplyAndAddUnsafe(H,$,P){const D=this.multiplyUnsafe($).add(H.multiplyUnsafe(P));return D.is0()?void 0:D}toAffine(H){return A(this,H)}isTorsionFree(){const{isTorsionFree:H}=t;return o===Jt?!0:H?H(v,this):V.unsafe(this,c).is0()}clearCofactor(){const{clearCofactor:H}=t;return o===Jt?this:H?H(v,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(H=!0){return Mo(H,"isCompressed"),this.assertValidity(),y(v,this,H)}toHex(H=!0){return rt(this.toBytes(H))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(H=!0){return this.toBytes(H)}_setWindowSize(H){this.precompute(H)}static normalizeZ(H){return _r(v,H)}static msm(H,$){return Pw(v,i,H,$)}static fromPrivateKey(H){return v.BASE.multiply(Ua(i,H))}}v.BASE=new v(s.Gx,s.Gy,r.ONE),v.ZERO=new v(r.ZERO,r.ONE,r.ZERO),v.Fp=r,v.Fn=i;const U=i.BITS,V=new kw(v,t.endo?Math.ceil(U/2):U);return v.BASE.precompute(8),v}function t3(e){return Uint8Array.of(e?2:3)}function n3(e,t){const n=e.ORDER;let r=Fi;for(let g=n-Jt;g%pr===Fi;g/=pr)r+=Jt;const i=r,s=pr<<i-Jt-Jt,o=s*pr,c=(n-Jt)/o,a=(c-Jt)/pr,u=o-Jt,f=s,l=e.pow(t,c),d=e.pow(t,(c+Jt)/pr);let y=(g,m)=>{let E=l,_=e.pow(m,u),S=e.sqr(_);S=e.mul(S,m);let w=e.mul(g,S);w=e.pow(w,a),w=e.mul(w,_),_=e.mul(w,m),S=e.mul(w,g);let T=e.mul(S,_);w=e.pow(T,f);let O=e.eql(w,e.ONE);_=e.mul(S,d),w=e.mul(T,E),S=e.cmov(_,S,O),T=e.cmov(w,T,O);for(let A=i;A>Jt;A--){let R=A-pr;R=pr<<R-Jt;let M=e.pow(T,R);const v=e.eql(M,e.ONE);_=e.mul(S,E),E=e.mul(E,E),M=e.mul(T,E),S=e.cmov(_,S,v),T=e.cmov(M,T,v)}return{isValid:O,value:S}};if(e.ORDER%ol===ys){const g=(e.ORDER-ys)/ol,m=e.sqrt(e.neg(t));y=(E,_)=>{let S=e.sqr(_);const w=e.mul(E,_);S=e.mul(S,w);let T=e.pow(S,g);T=e.mul(T,w);const O=e.mul(T,m),A=e.mul(e.sqr(T),_),R=e.eql(A,E);let M=e.cmov(O,T,R);return{isValid:R,value:M}}}return y}function Hw(e,t){vw(e);const{A:n,B:r,Z:i}=t;if(!e.isValid(n)||!e.isValid(r)||!e.isValid(i))throw new Error("mapToCurveSimpleSWU: invalid opts");const s=n3(e,i);if(!e.isOdd)throw new Error("Field does not have .isOdd()");return o=>{let c,a,u,f,l,d,y,g;c=e.sqr(o),c=e.mul(c,i),a=e.sqr(c),a=e.add(a,c),u=e.add(a,e.ONE),u=e.mul(u,r),f=e.cmov(i,e.neg(a),!e.eql(a,e.ZERO)),f=e.mul(f,n),a=e.sqr(u),d=e.sqr(f),l=e.mul(d,n),a=e.add(a,l),a=e.mul(a,u),d=e.mul(d,f),l=e.mul(d,r),a=e.add(a,l),y=e.mul(c,u);const{isValid:m,value:E}=s(a,d);g=e.mul(c,o),g=e.mul(g,E),y=e.cmov(y,u,m),g=e.cmov(g,E,m);const _=e.isOdd(o)===e.isOdd(g);g=e.cmov(e.neg(g),g,_);const S=es(e,[f],!0)[0];return y=e.mul(y,S),{x:y,y:g}}}function r3(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function g0(e){const{CURVE:t,curveOpts:n}=i3(e),r=e3(t,n);return o3(e,r)}function i3(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=yi(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function s3(e,t,n){function r(i){const s=e.sqr(i),o=e.mul(s,i);return e.add(e.add(o,e.mul(i,t)),n)}return r}function o3(e,t){const{Fp:n,Fn:r}=t;function i(o){return mw(o,Jt,r.ORDER)}const s=s3(n,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:o=>Ua(r,o),weierstrassEquation:s,isWithinCurveOrder:i})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const c3=BigInt(0),Hc=BigInt(1),m0=BigInt(2),gs=BigInt(3);function a3(e){const t=[];for(;e>Hc;e>>=Hc)(e&Hc)===c3?t.unshift(0):(e&gs)===gs?(t.unshift(-1),e+=Hc):t.unshift(1);return t}function cf(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function u3(e,t,n,r){const{Fp2:i,Fp12:s}=e,{twistType:o,ateLoopSize:c,xNegative:a,postPrecompute:u}=r;let f;if(o==="multiplicative")f=(w,T,O,A,R,M)=>s.mul014(A,w,i.mul(T,R),i.mul(O,M));else if(o==="divisive")f=(w,T,O,A,R,M)=>s.mul034(A,i.mul(O,M),i.mul(T,R),w);else throw new Error("bls: unknown twist type");const l=i.div(i.ONE,i.mul(i.ONE,m0));function d(w,T,O,A){const R=i.sqr(O),M=i.sqr(A),v=i.mulByB(i.mul(M,gs)),U=i.mul(v,gs),V=i.sub(i.sub(i.sqr(i.add(O,A)),M),R),K=i.sub(v,R),H=i.mul(i.sqr(T),gs),$=i.neg(V);return w.push([K,H,$]),T=i.mul(i.mul(i.mul(i.sub(R,U),T),O),l),O=i.sub(i.sqr(i.mul(i.add(R,U),l)),i.mul(i.sqr(v),gs)),A=i.mul(R,V),{Rx:T,Ry:O,Rz:A}}function y(w,T,O,A,R,M){const v=i.sub(O,i.mul(M,A)),U=i.sub(T,i.mul(R,A)),V=i.sub(i.mul(v,R),i.mul(U,M)),K=i.neg(v),H=U;w.push([V,K,H]);const $=i.sqr(U),P=i.mul($,U),D=i.mul($,T),F=i.add(i.sub(P,i.mul(D,m0)),i.mul(i.sqr(v),A));return T=i.mul(U,F),O=i.sub(i.mul(i.sub(D,F),v),i.mul(P,O)),A=i.mul(A,P),{Rx:T,Ry:O,Rz:A}}const g=a3(c),m=Lo(w=>{const T=w,{x:O,y:A}=T.toAffine(),R=O,M=A,v=i.neg(A);let U=R,V=M,K=i.ONE;const H=[];for(const $ of g){const P=[];({Rx:U,Ry:V,Rz:K}=d(P,U,V,K)),$&&({Rx:U,Ry:V,Rz:K}=y(P,U,V,K,R,$===-1?v:M)),H.push(P)}if(u){const $=H[H.length-1];u(U,V,K,R,M,y.bind(null,$))}return H});function E(w,T=!1){let O=s.ONE;if(w.length){const A=w[0][0].length;for(let R=0;R<A;R++){O=s.sqr(O);for(const[M,v,U]of w)for(const[V,K,H]of M[R])O=f(V,K,H,O,v,U)}}return a&&(O=s.conjugate(O)),T?s.finalExponentiate(O):O}function _(w,T=!0){const O=[];_r(t,w.map(({g1:A})=>A)),_r(n,w.map(({g2:A})=>A));for(const{g1:A,g2:R}of w){if(A.is0()||R.is0())throw new Error("pairing is not available for ZERO point");A.assertValidity(),R.assertValidity();const M=A.toAffine();O.push([m(R),M.x,M.y])}return E(O,T)}function S(w,T,O=!0){return _([{g1:w,g2:T}],O)}return{Fp12:s,millerLoopBatch:E,pairing:S,pairingBatch:_,calcPairingPrecomputes:m}}function w0(e,t,n,r,i){const{Fp12:s,pairingBatch:o}=e;function c(l){return l instanceof t.Point?l:t.Point.fromHex(l)}function a(l){return l instanceof n.Point?l:n.Point.fromHex(l)}function u(l){if(!(l instanceof n.Point))throw new Error(`expected valid message hashed to ${i?"G1":"G2"} curve`);return l}const f=i?(l,d)=>({g1:d,g2:l}):(l,d)=>({g1:l,g2:d});return{getPublicKey(l){const d=Ua(t.Point.Fn,l);return t.Point.BASE.multiply(d)},sign(l,d,y){if(y!=null)throw new Error("sign() expects 2 arguments");const g=Ua(t.Point.Fn,d);return u(l).assertValidity(),l.multiply(g)},verify(l,d,y,g){if(g!=null)throw new Error("verify() expects 3 arguments");l=a(l),y=c(y);const m=y.negate(),E=t.Point.BASE,_=u(d),S=l,w=o([f(m,_),f(E,S)]);return s.eql(w,s.ONE)},verifyBatch(l,d,y){if(cf(d),y.length!==d.length)throw new Error("amount of public keys and messages should be equal");const g=a(l),m=d,E=y.map(c),_=new Map;for(let T=0;T<E.length;T++){const O=E[T],A=m[T];let R=_.get(A);R===void 0&&(R=[],_.set(A,R)),R.push(O)}const S=[],w=t.Point.BASE;try{for(const[T,O]of _){const A=O.reduce((R,M)=>R.add(M));S.push(f(A,T))}return S.push(f(w.negate(),g)),s.eql(o(S),s.ONE)}catch{return!1}},aggregatePublicKeys(l){cf(l),l=l.map(y=>c(y));const d=l.reduce((y,g)=>y.add(g),t.Point.ZERO);return d.assertValidity(),d},aggregateSignatures(l){cf(l),l=l.map(y=>a(y));const d=l.reduce((y,g)=>y.add(g),n.Point.ZERO);return d.assertValidity(),d},hash(l,d){On(l);const y=d?{DST:d}:void 0;return n.hashToCurve(l,y)},Signature:r}}function f3(e){const{Fp:t,Fr:n,Fp2:r,Fp6:i,Fp12:s}=e.fields,o=g0(e.G1),c=Object.assign(o,p0(o.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),a=g0(e.G2),u=Object.assign(a,p0(a.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),f=u3(e.fields,c.Point,u.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:l,pairing:d,pairingBatch:y,calcPairingPrecomputes:g}=f,m=w0(f,c,u,e.G2.Signature,!1),E=w0(f,u,c,e.G1.ShortSignature,!0),_=e.randomBytes||cg,S=()=>{const x=Ow(n.ORDER);return jx(_(x),n.ORDER)},w={randomSecretKey:S,randomPrivateKey:S,calcPairingPrecomputes:g},{ShortSignature:T}=e.G1,{Signature:O}=e.G2;function A(x,B){return x instanceof c.Point?x:E.hash(cn("point",x),B?.DST)}function R(x,B){return x instanceof u.Point?x:m.hash(cn("point",x),B?.DST)}function M(x){return m.getPublicKey(x).toBytes(!0)}function v(x){return E.getPublicKey(x).toBytes(!0)}function U(x,B,q){const N=R(x,q),L=m.sign(N,B);return x instanceof u.Point?L:O.toBytes(L)}function V(x,B,q){const N=A(x,q),L=E.sign(N,B);return x instanceof c.Point?L:T.toBytes(L)}function K(x,B,q,N){const L=R(B,N);return m.verify(x,L,q)}function H(x,B,q,N){const L=A(B,N);return E.verify(x,L,q)}function $(x){const B=m.aggregatePublicKeys(x);return x[0]instanceof c.Point?B:B.toBytes(!0)}function P(x){const B=m.aggregateSignatures(x);return x[0]instanceof u.Point?B:O.toBytes(B)}function D(x){const B=E.aggregateSignatures(x);return x[0]instanceof c.Point?B:T.toBytes(B)}function F(x,B,q,N){const L=B.map(G=>R(G,N));return m.verifyBatch(x,L,q)}return c.Point.BASE.precompute(4),{longSignatures:m,shortSignatures:E,millerLoopBatch:l,pairing:d,pairingBatch:y,verifyBatch:F,fields:{Fr:n,Fp:t,Fp2:r,Fp6:i,Fp12:s},params:{ateLoopSize:e.params.ateLoopSize,twistType:e.params.twistType,r:e.params.r,G1b:e.G1.b,G2b:e.G2.b},utils:w,getPublicKey:M,getPublicKeyForShortSignatures:v,sign:U,signShortSignature:V,verify:K,verifyShortSignature:H,aggregatePublicKeys:$,aggregateSignatures:P,aggregateShortSignatures:D,G1:c,G2:u,Signature:O,ShortSignature:T}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const b0=BigInt(0),Sr=BigInt(1),en=BigInt(2),E0=BigInt(3);function ph(e,t,n,r,i=1,s){const o=BigInt(s===void 0?r:s),c=n**BigInt(r),a=[];for(let u=0;u<i;u++){const f=BigInt(u+1),l=[];for(let d=0,y=Sr;d<r;d++){const g=(f*y-f)/o%c;l.push(e.pow(t,g)),y*=n}a.push(l)}return a}function l3(e,t,n){const r=t.pow(n,(e.ORDER-Sr)/E0),i=t.pow(n,(e.ORDER-Sr)/en);function s(d,y){const g=t.mul(t.frobeniusMap(d,1),r),m=t.mul(t.frobeniusMap(y,1),i);return[g,m]}const o=t.pow(n,(e.ORDER**en-Sr)/E0),c=t.pow(n,(e.ORDER**en-Sr)/en);if(!t.eql(c,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function a(d,y){return[t.mul(d,o),t.neg(y)]}const u=d=>(y,g)=>{const m=g.toAffine(),E=d(m.x,m.y);return y.fromAffine({x:E[0],y:E[1]})},f=u(s),l=u(a);return{psi:s,psi2:a,G2psi:f,G2psi2:l,PSI_X:r,PSI_Y:i,PSI2_X:o,PSI2_Y:c}}const _0=(e,t)=>{if(t.length!==2)throw new Error("invalid tuple");const n=t.map(r=>e.create(r));return{c0:n[0],c1:n[1]}};class h3{constructor(t,n={}){this.MASK=Sr;const r=t.ORDER,i=r*r;this.Fp=t,this.ORDER=i,this.BITS=Vo(i),this.BYTES=Math.ceil(Vo(i)/8),this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.Fp_NONRESIDUE=t.create(n.NONRESIDUE||BigInt(-1)),this.Fp_div2=t.div(t.ONE,en),this.NONRESIDUE=_0(t,n.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=ph(t,this.Fp_NONRESIDUE,t.ORDER,2)[0],this.mulByB=n.Fp2mulByB,Object.seal(this)}fromBigTuple(t){return _0(this.Fp,t)}create(t){return t}isValid({c0:t,c1:n}){function r(i,s){return typeof i=="bigint"&&b0<=i&&i<s}return r(t,this.ORDER)&&r(n,this.ORDER)}is0({c0:t,c1:n}){return this.Fp.is0(t)&&this.Fp.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}eql({c0:t,c1:n},{c0:r,c1:i}){return this.Fp.eql(t,r)&&this.Fp.eql(n,i)}neg({c0:t,c1:n}){return{c0:this.Fp.neg(t),c1:this.Fp.neg(n)}}pow(t,n){return yu(this,t,n)}invertBatch(t){return es(this,t)}add(t,n){const{c0:r,c1:i}=t,{c0:s,c1:o}=n;return{c0:this.Fp.add(r,s),c1:this.Fp.add(i,o)}}sub({c0:t,c1:n},{c0:r,c1:i}){return{c0:this.Fp.sub(t,r),c1:this.Fp.sub(n,i)}}mul({c0:t,c1:n},r){const{Fp:i}=this;if(typeof r=="bigint")return{c0:i.mul(t,r),c1:i.mul(n,r)};const{c0:s,c1:o}=r;let c=i.mul(t,s),a=i.mul(n,o);const u=i.sub(c,a),f=i.sub(i.mul(i.add(t,n),i.add(s,o)),i.add(c,a));return{c0:u,c1:f}}sqr({c0:t,c1:n}){const{Fp:r}=this,i=r.add(t,n),s=r.sub(t,n),o=r.add(t,t);return{c0:r.mul(i,s),c1:r.mul(o,n)}}addN(t,n){return this.add(t,n)}subN(t,n){return this.sub(t,n)}mulN(t,n){return this.mul(t,n)}sqrN(t){return this.sqr(t)}div(t,n){const{Fp:r}=this;return this.mul(t,typeof n=="bigint"?r.inv(r.create(n)):this.inv(n))}inv({c0:t,c1:n}){const{Fp:r}=this,i=r.inv(r.create(t*t+n*n));return{c0:r.mul(i,r.create(t)),c1:r.mul(i,r.create(-n))}}sqrt(t){const{Fp:n}=this,r=this,{c0:i,c1:s}=t;if(n.is0(s))return Pa(n,i)===1?r.create({c0:n.sqrt(i),c1:n.ZERO}):r.create({c0:n.ZERO,c1:n.sqrt(n.div(i,this.Fp_NONRESIDUE))});const o=n.sqrt(n.sub(n.sqr(i),n.mul(n.sqr(s),this.Fp_NONRESIDUE)));let c=n.mul(n.add(o,i),this.Fp_div2);Pa(n,c)===-1&&(c=n.sub(c,o));const u=n.sqrt(c),f=r.create({c0:u,c1:n.div(n.mul(s,this.Fp_div2),u)});if(!r.eql(r.sqr(f),t))throw new Error("Cannot find square root");const l=f,d=r.neg(l),{re:y,im:g}=r.reim(l),{re:m,im:E}=r.reim(d);return g>E||g===E&&y>m?l:d}isOdd(t){const{re:n,im:r}=this.reim(t),i=n%en,s=n===b0,o=r%en;return BigInt(i||s&&o)==Sr}fromBytes(t){const{Fp:n}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:n.fromBytes(t.subarray(0,n.BYTES)),c1:n.fromBytes(t.subarray(n.BYTES))}}toBytes({c0:t,c1:n}){return $e(this.Fp.toBytes(t),this.Fp.toBytes(n))}cmov({c0:t,c1:n},{c0:r,c1:i},s){return{c0:this.Fp.cmov(t,r,s),c1:this.Fp.cmov(n,i,s)}}reim({c0:t,c1:n}){return{re:t,im:n}}Fp4Square(t,n){const r=this,i=r.sqr(t),s=r.sqr(n);return{first:r.add(r.mulByNonresidue(s),i),second:r.sub(r.sub(r.sqr(r.add(t,n)),i),s)}}mulByNonresidue({c0:t,c1:n}){return this.mul({c0:t,c1:n},this.NONRESIDUE)}frobeniusMap({c0:t,c1:n},r){return{c0:t,c1:this.Fp.mul(n,this.FROBENIUS_COEFFICIENTS[r%2])}}}class d3{constructor(t){this.MASK=Sr,this.Fp2=t,this.ORDER=t.ORDER,this.BITS=3*t.BITS,this.BYTES=3*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO,c2:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO,c2:t.ZERO};const{Fp:n}=t,r=ph(t,t.NONRESIDUE,n.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=r[0],this.FROBENIUS_COEFFICIENTS_2=r[1],Object.seal(this)}add({c0:t,c1:n,c2:r},{c0:i,c1:s,c2:o}){const{Fp2:c}=this;return{c0:c.add(t,i),c1:c.add(n,s),c2:c.add(r,o)}}sub({c0:t,c1:n,c2:r},{c0:i,c1:s,c2:o}){const{Fp2:c}=this;return{c0:c.sub(t,i),c1:c.sub(n,s),c2:c.sub(r,o)}}mul({c0:t,c1:n,c2:r},i){const{Fp2:s}=this;if(typeof i=="bigint")return{c0:s.mul(t,i),c1:s.mul(n,i),c2:s.mul(r,i)};const{c0:o,c1:c,c2:a}=i,u=s.mul(t,o),f=s.mul(n,c),l=s.mul(r,a);return{c0:s.add(u,s.mulByNonresidue(s.sub(s.mul(s.add(n,r),s.add(c,a)),s.add(f,l)))),c1:s.add(s.sub(s.mul(s.add(t,n),s.add(o,c)),s.add(u,f)),s.mulByNonresidue(l)),c2:s.sub(s.add(f,s.mul(s.add(t,r),s.add(o,a))),s.add(u,l))}}sqr({c0:t,c1:n,c2:r}){const{Fp2:i}=this;let s=i.sqr(t),o=i.mul(i.mul(t,n),en),c=i.mul(i.mul(n,r),en),a=i.sqr(r);return{c0:i.add(i.mulByNonresidue(c),s),c1:i.add(i.mulByNonresidue(a),o),c2:i.sub(i.sub(i.add(i.add(o,i.sqr(i.add(i.sub(t,n),r))),c),s),a)}}addN(t,n){return this.add(t,n)}subN(t,n){return this.sub(t,n)}mulN(t,n){return this.mul(t,n)}sqrN(t){return this.sqr(t)}create(t){return t}isValid({c0:t,c1:n,c2:r}){const{Fp2:i}=this;return i.isValid(t)&&i.isValid(n)&&i.isValid(r)}is0({c0:t,c1:n,c2:r}){const{Fp2:i}=this;return i.is0(t)&&i.is0(n)&&i.is0(r)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:n,c2:r}){const{Fp2:i}=this;return{c0:i.neg(t),c1:i.neg(n),c2:i.neg(r)}}eql({c0:t,c1:n,c2:r},{c0:i,c1:s,c2:o}){const{Fp2:c}=this;return c.eql(t,i)&&c.eql(n,s)&&c.eql(r,o)}sqrt(t){return ww()}div(t,n){const{Fp2:r}=this,{Fp:i}=r;return this.mul(t,typeof n=="bigint"?i.inv(i.create(n)):this.inv(n))}pow(t,n){return yu(this,t,n)}invertBatch(t){return es(this,t)}inv({c0:t,c1:n,c2:r}){const{Fp2:i}=this;let s=i.sub(i.sqr(t),i.mulByNonresidue(i.mul(r,n))),o=i.sub(i.mulByNonresidue(i.sqr(r)),i.mul(t,n)),c=i.sub(i.sqr(n),i.mul(t,r)),a=i.inv(i.add(i.mulByNonresidue(i.add(i.mul(r,o),i.mul(n,c))),i.mul(t,s)));return{c0:i.mul(a,s),c1:i.mul(a,o),c2:i.mul(a,c)}}fromBytes(t){const{Fp2:n}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);const r=n.BYTES;return{c0:n.fromBytes(t.subarray(0,r)),c1:n.fromBytes(t.subarray(r,r*2)),c2:n.fromBytes(t.subarray(2*r))}}toBytes({c0:t,c1:n,c2:r}){const{Fp2:i}=this;return $e(i.toBytes(t),i.toBytes(n),i.toBytes(r))}cmov({c0:t,c1:n,c2:r},{c0:i,c1:s,c2:o},c){const{Fp2:a}=this;return{c0:a.cmov(t,i,c),c1:a.cmov(n,s,c),c2:a.cmov(r,o,c)}}fromBigSix(t){const{Fp2:n}=this;if(!Array.isArray(t)||t.length!==6)throw new Error("invalid Fp6 usage");return{c0:n.fromBigTuple(t.slice(0,2)),c1:n.fromBigTuple(t.slice(2,4)),c2:n.fromBigTuple(t.slice(4,6))}}frobeniusMap({c0:t,c1:n,c2:r},i){const{Fp2:s}=this;return{c0:s.frobeniusMap(t,i),c1:s.mul(s.frobeniusMap(n,i),this.FROBENIUS_COEFFICIENTS_1[i%6]),c2:s.mul(s.frobeniusMap(r,i),this.FROBENIUS_COEFFICIENTS_2[i%6])}}mulByFp2({c0:t,c1:n,c2:r},i){const{Fp2:s}=this;return{c0:s.mul(t,i),c1:s.mul(n,i),c2:s.mul(r,i)}}mulByNonresidue({c0:t,c1:n,c2:r}){const{Fp2:i}=this;return{c0:i.mulByNonresidue(r),c1:t,c2:n}}mul1({c0:t,c1:n,c2:r},i){const{Fp2:s}=this;return{c0:s.mulByNonresidue(s.mul(r,i)),c1:s.mul(t,i),c2:s.mul(n,i)}}mul01({c0:t,c1:n,c2:r},i,s){const{Fp2:o}=this;let c=o.mul(t,i),a=o.mul(n,s);return{c0:o.add(o.mulByNonresidue(o.sub(o.mul(o.add(n,r),s),a)),c),c1:o.sub(o.sub(o.mul(o.add(i,s),o.add(t,n)),c),a),c2:o.add(o.sub(o.mul(o.add(t,r),i),c),a)}}}class p3{constructor(t,n){this.MASK=Sr;const{Fp2:r}=t,{Fp:i}=r;this.Fp6=t,this.ORDER=r.ORDER,this.BITS=2*t.BITS,this.BYTES=2*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.FROBENIUS_COEFFICIENTS=ph(r,r.NONRESIDUE,i.ORDER,12,1,6)[0],this.X_LEN=n.X_LEN,this.finalExponentiate=n.Fp12finalExponentiate}create(t){return t}isValid({c0:t,c1:n}){const{Fp6:r}=this;return r.isValid(t)&&r.isValid(n)}is0({c0:t,c1:n}){const{Fp6:r}=this;return r.is0(t)&&r.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:n}){const{Fp6:r}=this;return{c0:r.neg(t),c1:r.neg(n)}}eql({c0:t,c1:n},{c0:r,c1:i}){const{Fp6:s}=this;return s.eql(t,r)&&s.eql(n,i)}sqrt(t){ww()}inv({c0:t,c1:n}){const{Fp6:r}=this;let i=r.inv(r.sub(r.sqr(t),r.mulByNonresidue(r.sqr(n))));return{c0:r.mul(t,i),c1:r.neg(r.mul(n,i))}}div(t,n){const{Fp6:r}=this,{Fp2:i}=r,{Fp:s}=i;return this.mul(t,typeof n=="bigint"?s.inv(s.create(n)):this.inv(n))}pow(t,n){return yu(this,t,n)}invertBatch(t){return es(this,t)}add({c0:t,c1:n},{c0:r,c1:i}){const{Fp6:s}=this;return{c0:s.add(t,r),c1:s.add(n,i)}}sub({c0:t,c1:n},{c0:r,c1:i}){const{Fp6:s}=this;return{c0:s.sub(t,r),c1:s.sub(n,i)}}mul({c0:t,c1:n},r){const{Fp6:i}=this;if(typeof r=="bigint")return{c0:i.mul(t,r),c1:i.mul(n,r)};let{c0:s,c1:o}=r,c=i.mul(t,s),a=i.mul(n,o);return{c0:i.add(c,i.mulByNonresidue(a)),c1:i.sub(i.mul(i.add(t,n),i.add(s,o)),i.add(c,a))}}sqr({c0:t,c1:n}){const{Fp6:r}=this;let i=r.mul(t,n);return{c0:r.sub(r.sub(r.mul(r.add(r.mulByNonresidue(n),t),r.add(t,n)),i),r.mulByNonresidue(i)),c1:r.add(i,i)}}addN(t,n){return this.add(t,n)}subN(t,n){return this.sub(t,n)}mulN(t,n){return this.mul(t,n)}sqrN(t){return this.sqr(t)}fromBytes(t){const{Fp6:n}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:n.fromBytes(t.subarray(0,n.BYTES)),c1:n.fromBytes(t.subarray(n.BYTES))}}toBytes({c0:t,c1:n}){const{Fp6:r}=this;return $e(r.toBytes(t),r.toBytes(n))}cmov({c0:t,c1:n},{c0:r,c1:i},s){const{Fp6:o}=this;return{c0:o.cmov(t,r,s),c1:o.cmov(n,i,s)}}fromBigTwelve(t){const{Fp6:n}=this;return{c0:n.fromBigSix(t.slice(0,6)),c1:n.fromBigSix(t.slice(6,12))}}frobeniusMap(t,n){const{Fp6:r}=this,{Fp2:i}=r,{c0:s,c1:o,c2:c}=r.frobeniusMap(t.c1,n),a=this.FROBENIUS_COEFFICIENTS[n%12];return{c0:r.frobeniusMap(t.c0,n),c1:r.create({c0:i.mul(s,a),c1:i.mul(o,a),c2:i.mul(c,a)})}}mulByFp2({c0:t,c1:n},r){const{Fp6:i}=this;return{c0:i.mulByFp2(t,r),c1:i.mulByFp2(n,r)}}conjugate({c0:t,c1:n}){return{c0:t,c1:this.Fp6.neg(n)}}mul014({c0:t,c1:n},r,i,s){const{Fp6:o}=this,{Fp2:c}=o;let a=o.mul01(t,r,i),u=o.mul1(n,s);return{c0:o.add(o.mulByNonresidue(u),a),c1:o.sub(o.sub(o.mul01(o.add(n,t),r,c.add(i,s)),a),u)}}mul034({c0:t,c1:n},r,i,s){const{Fp6:o}=this,{Fp2:c}=o,a=o.create({c0:c.mul(t.c0,r),c1:c.mul(t.c1,r),c2:c.mul(t.c2,r)}),u=o.mul01(n,i,s),f=o.mul01(o.add(t,n),c.add(r,i),s);return{c0:o.add(o.mulByNonresidue(u),a),c1:o.sub(f,o.add(a,u))}}_cyclotomicSquare({c0:t,c1:n}){const{Fp6:r}=this,{Fp2:i}=r,{c0:s,c1:o,c2:c}=t,{c0:a,c1:u,c2:f}=n,{first:l,second:d}=i.Fp4Square(s,u),{first:y,second:g}=i.Fp4Square(a,c),{first:m,second:E}=i.Fp4Square(o,f),_=i.mulByNonresidue(E);return{c0:r.create({c0:i.add(i.mul(i.sub(l,s),en),l),c1:i.add(i.mul(i.sub(y,o),en),y),c2:i.add(i.mul(i.sub(m,c),en),m)}),c1:r.create({c0:i.add(i.mul(i.add(_,a),en),_),c1:i.add(i.mul(i.add(d,u),en),d),c2:i.add(i.mul(i.add(g,f),en),g)})}}_cyclotomicExp(t,n){let r=this.ONE;for(let i=this.X_LEN-1;i>=0;i--)r=this._cyclotomicSquare(r),Ux(n,i)&&(r=this.mul(r,t));return r}}function y3(e){const t=yi(e.ORDER),n=new h3(t,e),r=new d3(n),i=new p3(r,e);return{Fp:t,Fp2:n,Fp6:r,Fp12:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const jt=BigInt(0),Ca=BigInt(1),kn=BigInt(2),gu=BigInt(3),Do=BigInt(4),ri=BigInt("0xd201000000010000"),g3=Vo(ri),Wi={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:jt,b:Do,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},m3=yi(Wi.n,{modFromBytes:!0,isLE:!0}),{Fp:Ee,Fp2:Re,Fp6:w3,Fp12:Me}=y3({ORDER:Wi.p,X_LEN:g3,FP2_NONRESIDUE:[Ca,Ca],Fp2mulByB:({c0:e,c1:t})=>{const n=Ee.mul(e,Do),r=Ee.mul(t,Do);return{c0:Ee.sub(n,r),c1:Ee.add(n,r)}},Fp12finalExponentiate:e=>{const t=ri,n=Me.div(Me.frobeniusMap(e,6),e),r=Me.mul(Me.frobeniusMap(n,2),n),i=Me.conjugate(Me._cyclotomicExp(r,t)),s=Me.mul(Me.conjugate(Me._cyclotomicSquare(r)),i),o=Me.conjugate(Me._cyclotomicExp(s,t)),c=Me.conjugate(Me._cyclotomicExp(o,t)),a=Me.mul(Me.conjugate(Me._cyclotomicExp(c,t)),Me._cyclotomicSquare(i)),u=Me.conjugate(Me._cyclotomicExp(a,t)),f=Me.frobeniusMap(Me.mul(i,c),2),l=Me.frobeniusMap(Me.mul(o,r),3),d=Me.frobeniusMap(Me.mul(a,Me.conjugate(r)),1),y=Me.mul(Me.mul(u,Me.conjugate(s)),r);return Me.mul(Me.mul(Me.mul(f,l),d),y)}}),{G2psi:S0,G2psi2:b3}=l3(Ee,Re,Re.div(Re.ONE,Re.NONRESIDUE)),af=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:Ee.ORDER,m:2,k:128,expand:"xmd",hash:En}),yh={p:Re.ORDER,n:Wi.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:Re.ZERO,b:Re.fromBigTuple([Do,Do]),Gx:Re.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:Re.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},mu=wc(Ee.toBytes(jt),{infinity:!0,compressed:!0});function wu(e){e=e.slice();const t=e[0]&224,n=!!(t>>7&1),r=!!(t>>6&1),i=!!(t>>5&1);return e[0]&=31,{compressed:n,infinity:r,sort:i,value:e}}function wc(e,t){if(e[0]&224)throw new Error("setMask: non-empty mask");return t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}function E3(e,t,n){const{BYTES:r,ORDER:i}=Ee,s=t.is0(),{x:o,y:c}=t.toAffine();if(n){if(s)return mu.slice();const a=!!(c*kn/i);return wc(Ut(o,r),{compressed:!0,sort:a})}else return s?$e(Uint8Array.of(64),new Uint8Array(2*r-1)):$e(Ut(o,r),Ut(c,r))}function uf(e){e.assertValidity();const{BYTES:t,ORDER:n}=Ee,{x:r,y:i}=e.toAffine();if(e.is0())return mu.slice();const s=!!(i*kn/n);return wc(Ut(r,t),{compressed:!0,sort:s})}function _3(e){const{compressed:t,infinity:n,sort:r,value:i}=wu(e),{BYTES:s,ORDER:o}=Ee;if(i.length===48&&t){const c=rr(i),a=Ee.create(c&Qi(Ee.BITS));if(n){if(a!==jt)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:jt,y:jt}}const u=Ee.add(Ee.pow(a,gu),Ee.create(Wi.b));let f=Ee.sqrt(u);if(!f)throw new Error("invalid G1 point: compressed point");return f*kn/o!==BigInt(r)&&(f=Ee.neg(f)),{x:Ee.create(a),y:Ee.create(f)}}else if(i.length===96&&!t){const c=rr(i.subarray(0,s)),a=rr(i.subarray(s));if(n){if(c!==jt||a!==jt)throw new Error("G1: non-empty point at infinity");return bu.G1.Point.ZERO.toAffine()}return{x:Ee.create(c),y:Ee.create(a)}}else throw new Error("invalid G1 point: expected 48/96 bytes")}function T0(e){const{infinity:t,sort:n,value:r}=wu(cn("signatureHex",e,48)),i=Ee.ORDER,s=bu.G1.Point,o=rr(r);if(t)return s.ZERO;const c=Ee.create(o&Qi(Ee.BITS)),a=Ee.add(Ee.pow(c,gu),Ee.create(Wi.b));let u=Ee.sqrt(a);if(!u)throw new Error("invalid G1 point: compressed");const f=BigInt(n);u*kn/i!==f&&(u=Ee.neg(u));const l=s.fromAffine({x:c,y:u});return l.assertValidity(),l}function S3(e,t,n){const{BYTES:r,ORDER:i}=Ee,s=t.is0(),{x:o,y:c}=t.toAffine();if(n){if(s)return $e(mu,Ut(jt,r));const a=!!(c.c1===jt?c.c0*kn/i:c.c1*kn/i);return $e(wc(Ut(o.c1,r),{compressed:!0,sort:a}),Ut(o.c0,r))}else{if(s)return $e(Uint8Array.of(64),new Uint8Array(4*r-1));const{re:a,im:u}=Re.reim(o),{re:f,im:l}=Re.reim(c);return $e(Ut(u,r),Ut(a,r),Ut(l,r),Ut(f,r))}}function ff(e){e.assertValidity();const{BYTES:t}=Ee;if(e.is0())return $e(mu,Ut(jt,t));const{x:n,y:r}=e.toAffine(),{re:i,im:s}=Re.reim(n),{re:o,im:c}=Re.reim(r),u=!!((c>jt?c*kn:o*kn)/Ee.ORDER&Ca),f=i;return $e(wc(Ut(s,t),{sort:u,compressed:!0}),Ut(f,t))}function T3(e){const{BYTES:t,ORDER:n}=Ee,{compressed:r,infinity:i,sort:s,value:o}=wu(e);if(!r&&!i&&s||!r&&i&&s||s&&i&&r)throw new Error("invalid encoding flag: "+(e[0]&224));const c=(a,u,f)=>rr(a.slice(u,f));if(o.length===96&&r){if(i){if(o.reduce((g,m)=>g!==0?m+1:m,0)>0)throw new Error("invalid G2 point: compressed");return{x:Re.ZERO,y:Re.ZERO}}const a=c(o,0,t),u=c(o,t,2*t),f=Re.create({c0:Ee.create(u),c1:Ee.create(a)}),l=Re.add(Re.pow(f,gu),yh.b);let d=Re.sqrt(l);const y=d.c1===jt?d.c0*kn/n:d.c1*kn/n?Ca:jt;return d=s&&y>0?d:Re.neg(d),{x:f,y:d}}else if(o.length===192&&!r){if(i){if(o.reduce((d,y)=>d!==0?y+1:y,0)>0)throw new Error("invalid G2 point: uncompressed");return{x:Re.ZERO,y:Re.ZERO}}const a=c(o,0*t,1*t),u=c(o,1*t,2*t),f=c(o,2*t,3*t),l=c(o,3*t,4*t);return{x:Re.fromBigTuple([u,a]),y:Re.fromBigTuple([l,f])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function x0(e){const{ORDER:t}=Ee,{infinity:n,sort:r,value:i}=wu(cn("signatureHex",e)),s=bu.G2.Point,o=i.length/2;if(o!==48&&o!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");const c=rr(i.slice(0,o)),a=rr(i.slice(o));if(n)return s.ZERO;const u=Ee.create(c&Qi(Ee.BITS)),f=Ee.create(a),l=Re.create({c0:f,c1:u}),d=Re.add(Re.pow(l,gu),yh.b);let y=Re.sqrt(d);if(!y)throw new Error("Failed to find a square root");const{re:g,im:m}=Re.reim(y),E=BigInt(r),_=m>jt&&m*kn/t!==E,S=m===jt&&g*kn/t!==E;(_||S)&&(y=Re.neg(y));const w=s.fromAffine({x:l,y});return w.assertValidity(),w}const bu=f3({fields:{Fp:Ee,Fp2:Re,Fp6:w3,Fp12:Me,Fr:m3},G1:{...Wi,Fp:Ee,htfDefaults:{...af,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(e,t)=>{const n=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),r=new e(Ee.mul(t.X,n),t.Y,t.Z);return t.multiplyUnsafe(ri).negate().multiplyUnsafe(ri).equals(r)},clearCofactor:(e,t)=>t.multiplyUnsafe(ri).add(t),mapToCurve:O3,fromBytes:_3,toBytes:E3,ShortSignature:{fromBytes(e){return On(e),T0(e)},fromHex(e){return T0(e)},toBytes(e){return uf(e)},toRawBytes(e){return uf(e)},toHex(e){return rt(uf(e))}}},G2:{...yh,Fp:Re,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...af},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:B3,isTorsionFree:(e,t)=>t.multiplyUnsafe(ri).negate().equals(S0(e,t)),clearCofactor:(e,t)=>{const n=ri;let r=t.multiplyUnsafe(n).negate(),i=S0(e,t),s=t.double();return s=b3(e,s),s=s.subtract(i),i=r.add(i),i=i.multiplyUnsafe(n).negate(),s=s.add(i),s=s.subtract(r),s.subtract(t)},fromBytes:T3,toBytes:S3,Signature:{fromBytes(e){return On(e),x0(e)},fromHex(e){return x0(e)},toBytes(e){return ff(e)},toRawBytes(e){return ff(e)},toHex(e){return rt(ff(e))}}},params:{ateLoopSize:ri,r:Wi.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:af}),x3=Cw(Re,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(e=>e.map(t=>Re.fromBigTuple(t.map(BigInt))))),A3=Cw(Ee,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),v3=Hw(Ee,{A:Ee.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:Ee.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:Ee.create(BigInt(11))}),I3=Hw(Re,{A:Re.create({c0:Ee.create(jt),c1:Ee.create(BigInt(240))}),B:Re.create({c0:Ee.create(BigInt(1012)),c1:Ee.create(BigInt(1012))}),Z:Re.create({c0:Ee.create(BigInt(-2)),c1:Ee.create(BigInt(-1))})});function O3(e){const{x:t,y:n}=v3(Ee.create(e[0]));return A3(t,n)}function B3(e){const{x:t,y:n}=I3(Re.fromBigTuple(e));return x3(t,n)}function N3(e,t,n){const r=typeof e=="string"?e:rt(e),i=typeof t=="string"?t:rt(t),s=typeof n=="string"?n:rt(n);return bu.verifyShortSignature(i,s,r)}const k3=BigInt(1e6),Fw=e=>Bt(new $s(e)),gh=e=>{const n=Fw(e)/k3;return new Date(Number(n))},A0=60*1e3,P3=60,R3=24,U3=R3*P3,C3=5,H3=5,F3=30*U3;var Ct;(function(e){e[e.Empty=0]="Empty",e[e.Fork=1]="Fork",e[e.Labeled=2]="Labeled",e[e.Leaf=3]="Leaf",e[e.Pruned=4]="Pruned"})(Ct||(Ct={}));function M3(e,t){for(let n=0;n<e.length;n++)if(e[n]>t[n])return!0;return!1}class Vi{#t=!1;#e=void 0;static async create(t){const n=Vi.createUnverified(t);return await n.verify(),n}static createUnverified(t){return new Vi(t.certificate,t.rootKey,t.canisterId,t.blsVerify??N3,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,n,r,i,s=C3,o=!1,c){this._rootKey=n,this._canisterId=r,this._blsVerify=i,this._maxAgeInMinutes=s,this.#t=o,this.cert=er(t),c&&"getTimeDiffMsecs"in c&&"hasSyncedTime"in c&&"syncTime"in c&&(this.#e=c)}lookup_path(t){return bc(t,this.cert.tree)}lookup_subtree(t){return mh(t,this.cert.tree)}async verify(){const t=await na(this.cert.tree),n=await this._checkDelegationAndGetKey(this.cert.delegation),r=this.cert.signature,i=V3(n),s=$e(bo("ic-state-root"),t),o=_n(this.lookup_path(["time"]));if(!o)throw yt.fromCode(new _s("Certificate does not contain a time"));if(!this.#t){const c=this.#e?.getTimeDiffMsecs()??0,a=this._maxAgeInMinutes*A0,u=new Date,f=u.getTime()+c,l=f-a,d=f+H3*A0,y=gh(o),g=y.getTime()<l,m=y.getTime()>d;if((g||m)&&this.#e&&!this.#e.hasSyncedTime())return await this.#e.syncTime(this._canisterId),await this.verify();if(g)throw An.fromCode(new Uo(this._maxAgeInMinutes,y,u,c,"past"));if(m)throw this.#e?.hasSyncedTime()?fn.fromCode(new Vn("System time has been synced with the IC network, but certificate is still too far in the future.")):An.fromCode(new Uo(5,y,u,c,"future"))}try{if(!await this._blsVerify(i,r,s))throw An.fromCode(new _s("Invalid signature"))}catch(c){throw An.fromCode(new _s("Signature verification failed",c))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;const n=Vi.createUnverified({certificate:t.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,disableTimeVerification:this.#t,maxAgeInMinutes:F3,agent:this.#e});if(n.cert.delegation)throw yt.fromCode(new Gl);await n.verify();const r=t.subnet_id,i=Ke.fromUint8Array(r);if(!qw({canisterId:this._canisterId,subnetId:i,tree:n.cert.tree}))throw An.fromCode(new uu(this._canisterId,i));const o=_n(n.lookup_path(["subnet",r,"public_key"]));if(!o)throw An.fromCode(new Wl(`Could not find subnet key for subnet ID ${i.toText()}`));return o}}const io=sc("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),q3=96;function V3(e){const t=io.byteLength+q3;if(e.byteLength!==t)throw yt.fromCode(new lu(t,e.byteLength));const n=e.slice(0,io.byteLength);if(!pu(n,io))throw yt.fromCode(new Xl(io,n));return e.slice(io.byteLength)}function _n(e){if(e.status===vn.Found&&e.value instanceof Uint8Array)return e.value}async function na(e){switch(e[0]){case Ct.Empty:return En(bo("ic-hashtree-empty"));case Ct.Pruned:return e[1];case Ct.Leaf:return En($e(bo("ic-hashtree-leaf"),e[1]));case Ct.Labeled:return En($e(bo("ic-hashtree-labeled"),e[1],await na(e[2])));case Ct.Fork:return En($e(bo("ic-hashtree-fork"),await na(e[1]),await na(e[2])));default:throw Ss}}function bo(e){const t=new Uint8Array([e.length]),n=new TextEncoder().encode(e);return $e(t,n)}function Mw(e){return typeof e[0]=="string"?dt(e[0]):e[0]}var vn;(function(e){e.Unknown="Unknown",e.Absent="Absent",e.Found="Found",e.Error="Error"})(vn||(vn={}));var vs;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found"})(vs||(vs={}));var ot;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found",e.Less="Less",e.Greater="Greater"})(ot||(ot={}));function bc(e,t){if(e.length===0)switch(t[0]){case Ct.Empty:return{status:vn.Absent};case Ct.Leaf:{if(!t[1])throw fn.fromCode(new yc("Invalid tree structure for leaf"));if(t[1]instanceof Uint8Array)return{status:vn.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw Ss}case Ct.Pruned:return{status:vn.Unknown};case Ct.Labeled:case Ct.Fork:return{status:vn.Error};default:throw Ss}const n=Mw(e),r=Ao(n,t);switch(r.status){case ot.Found:return bc(e.slice(1),r.value);case ot.Absent:case ot.Greater:case ot.Less:return{status:vn.Absent};case ot.Unknown:return{status:vn.Unknown};default:throw Ss}}function mh(e,t){if(e.length===0)return{status:vs.Found,value:t};const n=Mw(e),r=Ao(n,t);switch(r.status){case ot.Found:return mh(e.slice(1),r.value);case ot.Unknown:return{status:vs.Unknown};case ot.Absent:case ot.Greater:case ot.Less:return{status:vs.Absent};default:throw Ss}}function cl(e){switch(e[0]){case Ct.Empty:return[];case Ct.Fork:return cl(e[1]).concat(cl(e[2]));default:return[e]}}function Ao(e,t){switch(t[0]){case Ct.Labeled:return M3(e,t[1])?{status:ot.Greater}:pu(e,t[1])?{status:ot.Found,value:t[2]}:{status:ot.Less};case Ct.Fork:{const n=Ao(e,t[1]);switch(n.status){case ot.Greater:{const r=Ao(e,t[2]);return r.status===ot.Less?{status:ot.Absent}:r}case ot.Unknown:{const r=Ao(e,t[2]);return r.status===ot.Less?{status:ot.Unknown}:r}default:return n}}case Ct.Pruned:return{status:ot.Unknown};default:return{status:ot.Absent}}}function qw(e){const{canisterId:t,subnetId:n,tree:r}=e,i=bc(["subnet",n.toUint8Array(),"canister_ranges"],r);if(i.status!==vn.Found)throw yt.fromCode(new Cs(`Could not find canister ranges for subnet ${n.toText()}`,i.status));if(!(i.value instanceof Uint8Array))throw yt.fromCode(new fu(`Could not find canister ranges for subnet ${n.toText()}`));return er(i.value).map(a=>[Ke.fromUint8Array(a[0]),Ke.fromUint8Array(a[1])]).some(a=>a[0].ltEq(t)&&a[1].gtEq(t))}const v0=async e=>{const{agent:t,paths:n,disableCertificateTimeVerification:r=!1}=e,i=Ke.from(e.canisterId),s=[...new Set(n)],o=new Map,c=s.map((a,u)=>{const f=$3(a,i);return(async()=>{try{if(t.rootKey===null)throw un.fromCode(new Ks);const l=t.rootKey,d=await t.readState(i,{paths:[f]}),y=await Vi.create({certificate:d.certificate,rootKey:l,canisterId:i,disableTimeVerification:r,agent:t}),g=(_,S)=>{if(S==="subnet"){const w=L3(d.certificate,i,l);return{path:S,data:w}}else return{path:S,data:_n(_.lookup_path(f))}},{path:m,data:E}=g(y,s[u]);if(!E)console.warn(`Expected to find result for path ${m}, but instead found nothing.`),typeof m=="string"?o.set(m,null):o.set(m.key,null);else switch(m){case"time":{o.set(m,gh(E));break}case"controllers":{o.set(m,D3(E));break}case"module_hash":{o.set(m,rt(E));break}case"subnet":{o.set(m,E);break}case"candid":{o.set(m,new TextDecoder().decode(E));break}default:if(typeof m!="string"&&"key"in m&&"path"in m)switch(m.decodeStrategy){case"raw":o.set(m.key,E);break;case"leb128":{o.set(m.key,Fw(E));break}case"cbor":{o.set(m.key,er(E));break}case"hex":{o.set(m.key,rt(E));break}case"utf-8":o.set(m.key,new TextDecoder().decode(E))}}}catch(l){if(l instanceof wr&&(l.hasCode(_s)||l.hasCode(Uo)))throw l;typeof a!="string"&&"key"in a&&"path"in a?o.set(a.key,null):o.set(a,null),console.group(),console.warn(`Expected to find result for path ${a}, but instead found nothing.`),console.warn(l),console.groupEnd()}})()});return await Promise.all(c),o},L3=(e,t,n)=>{if(!t._isPrincipal)throw et.fromCode(new Vn("Invalid canisterId"));const r=er(e),i=r.tree;let s=r.delegation,o;if(s&&s.subnet_id?o=Ke.fromUint8Array(new Uint8Array(s.subnet_id)):!s&&typeof n<"u"?(o=Ke.selfAuthenticating(new Uint8Array(n)),s={subnet_id:o.toUint8Array(),certificate:new Uint8Array(0)}):(o=Ke.selfAuthenticating(Ke.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),s={subnet_id:o.toUint8Array(),certificate:new Uint8Array(0)}),!qw({canisterId:t,subnetId:o,tree:i}))throw An.fromCode(new uu(t,o));const a=mh(["subnet",s.subnet_id,"node"],i);if(a.status!==vs.Found)throw yt.fromCode(new Cs("Node not found",a.status));if(a.value instanceof Uint8Array)throw fn.fromCode(new yc("Invalid node tree"));const u=cl(a.value),f=new Map;return u.forEach(l=>{const d=Ke.from(l[1]).toText(),y=bc(["public_key"],l[2]);if(y.status!==vn.Found)throw yt.fromCode(new Cs("Public key not found",y.status));const g=y.value;if(g.byteLength!==44)throw yt.fromCode(new lu(44,g.byteLength));f.set(d,g)}),{subnetId:Ke.fromUint8Array(new Uint8Array(s.subnet_id)).toText(),nodeKeys:f}},$3=(e,t)=>{const n=t.toUint8Array();switch(e){case"time":return[dt("time")];case"controllers":return[dt("canister"),n,dt("controllers")];case"module_hash":return[dt("canister"),n,dt("module_hash")];case"subnet":return[dt("subnet")];case"candid":return[dt("canister"),n,dt("metadata"),dt("candid:service")];default:if("key"in e&&"path"in e)if(typeof e.path=="string"||e.path instanceof Uint8Array){const r=e.path,i=typeof r=="string"?dt(r):r;return[dt("canister"),n,dt("metadata"),i]}else return e.path}throw fn.fromCode(new Vn(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))},D3=e=>er(e).map(n=>Ke.fromUint8Array(n));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qr=BigInt(0),Ot=BigInt(1),lf=BigInt(2),j3=BigInt(8);function K3(e,t,n,r){const i=e.sqr(n),s=e.sqr(r),o=e.add(e.mul(t.a,i),s),c=e.add(e.ONE,e.mul(t.d,e.mul(i,s)));return e.eql(o,c)}function G3(e,t={}){const n=Rw("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o}=s;mc(t,{},{uvRatio:"function"});const c=lf<<BigInt(i.BYTES*8)-Ot,a=E=>r.create(E),u=t.uvRatio||((E,_)=>{try{return{isValid:!0,value:r.sqrt(r.div(E,_))}}catch{return{isValid:!1,value:qr}}});if(!K3(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(E,_,S=!1){const w=S?Ot:qr;return u0("coordinate "+E,_,w,c),_}function l(E){if(!(E instanceof g))throw new Error("ExtendedPoint expected")}const d=Lo((E,_)=>{const{X:S,Y:w,Z:T}=E,O=E.is0();_==null&&(_=O?j3:r.inv(T));const A=a(S*_),R=a(w*_),M=r.mul(T,_);if(O)return{x:qr,y:Ot};if(M!==Ot)throw new Error("invZ was invalid");return{x:A,y:R}}),y=Lo(E=>{const{a:_,d:S}=s;if(E.is0())throw new Error("bad point: ZERO");const{X:w,Y:T,Z:O,T:A}=E,R=a(w*w),M=a(T*T),v=a(O*O),U=a(v*v),V=a(R*_),K=a(v*a(V+M)),H=a(U+a(S*a(R*M)));if(K!==H)throw new Error("bad point: equation left != right (1)");const $=a(w*T),P=a(O*A);if($!==P)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(_,S,w,T){this.X=f("x",_),this.Y=f("y",S),this.Z=f("z",w,!0),this.T=f("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(_){if(_ instanceof g)throw new Error("extended point not allowed");const{x:S,y:w}=_||{};return f("x",S),f("y",w),new g(S,w,Ot,a(S*w))}static fromBytes(_,S=!1){const w=r.BYTES,{a:T,d:O}=s;_=a0(As(_,w,"point")),Mo(S,"zip215");const A=a0(_),R=_[w-1];A[w-1]=R&-129;const M=qo(A),v=S?c:r.ORDER;u0("point.y",M,qr,v);const U=a(M*M),V=a(U-Ot),K=a(O*U-T);let{isValid:H,value:$}=u(V,K);if(!H)throw new Error("bad point: invalid y coordinate");const P=($&Ot)===Ot,D=(R&128)!==0;if(!S&&$===qr&&D)throw new Error("bad point: x=0 and x_0=1");return D!==P&&($=a(-$)),g.fromAffine({x:$,y:M})}static fromHex(_,S=!1){return g.fromBytes(cn("point",_),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,S=!0){return m.createCache(this,_),S||this.multiply(lf),this}assertValidity(){y(this)}equals(_){l(_);const{X:S,Y:w,Z:T}=this,{X:O,Y:A,Z:R}=_,M=a(S*R),v=a(O*T),U=a(w*R),V=a(A*T);return M===v&&U===V}is0(){return this.equals(g.ZERO)}negate(){return new g(a(-this.X),this.Y,this.Z,a(-this.T))}double(){const{a:_}=s,{X:S,Y:w,Z:T}=this,O=a(S*S),A=a(w*w),R=a(lf*a(T*T)),M=a(_*O),v=S+w,U=a(a(v*v)-O-A),V=M+A,K=V-R,H=M-A,$=a(U*K),P=a(V*H),D=a(U*H),F=a(K*V);return new g($,P,F,D)}add(_){l(_);const{a:S,d:w}=s,{X:T,Y:O,Z:A,T:R}=this,{X:M,Y:v,Z:U,T:V}=_,K=a(T*M),H=a(O*v),$=a(R*w*V),P=a(A*U),D=a((T+O)*(M+v)-K-H),F=P-$,x=P+$,B=a(H-S*K),q=a(D*F),N=a(x*B),L=a(D*B),G=a(F*x);return new g(q,N,G,L)}subtract(_){return this.add(_.negate())}multiply(_){if(!i.isValidNot0(_))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:S,f:w}=m.cached(this,_,T=>_r(g,T));return _r(g,[S,w])[0]}multiplyUnsafe(_,S=g.ZERO){if(!i.isValid(_))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return _===qr?g.ZERO:this.is0()||_===Ot?this:m.unsafe(this,_,w=>_r(g,w),S)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(_){return d(this,_)}clearCofactor(){return o===Ot?this:this.multiplyUnsafe(o)}toBytes(){const{x:_,y:S}=this.toAffine(),w=r.toBytes(S);return w[w.length-1]|=_&Ot?128:0,w}toHex(){return rt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(_){return _r(g,_)}static msm(_,S){return Pw(g,i,_,S)}_setWindowSize(_){this.precompute(_)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,Ot,a(s.Gx*s.Gy)),g.ZERO=new g(qr,Ot,Ot,qr),g.Fp=r,g.Fn=i;const m=new kw(g,i.BITS);return g.BASE.precompute(8),g}function W3(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');mc(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:s,Fn:o}=e,c=n.randomBytes||cg,a=n.adjustScalarBytes||(v=>v),u=n.domain||((v,U,V)=>{if(Mo(V,"phflag"),U.length||V)throw new Error("Contexts/pre-hash are not supported");return v});function f(v){return o.create(qo(v))}function l(v){const U=w.secretKey;v=cn("private key",v,U);const V=cn("hashed private key",t(v),2*U),K=a(V.slice(0,U)),H=V.slice(U,2*U),$=f(K);return{head:K,prefix:H,scalar:$}}function d(v){const{head:U,prefix:V,scalar:K}=l(v),H=i.multiply(K),$=H.toBytes();return{head:U,prefix:V,scalar:K,point:H,pointBytes:$}}function y(v){return d(v).pointBytes}function g(v=Uint8Array.of(),...U){const V=$e(...U);return f(t(u(V,cn("context",v),!!r)))}function m(v,U,V={}){v=cn("message",v),r&&(v=r(v));const{prefix:K,scalar:H,pointBytes:$}=d(U),P=g(V.context,K,v),D=i.multiply(P).toBytes(),F=g(V.context,D,$,v),x=o.create(P+F*H);if(!o.isValid(x))throw new Error("sign failed: invalid s");const B=$e(D,o.toBytes(x));return As(B,w.signature,"result")}const E={zip215:!0};function _(v,U,V,K=E){const{context:H,zip215:$}=K,P=w.signature;v=cn("signature",v,P),U=cn("message",U),V=cn("publicKey",V,w.publicKey),$!==void 0&&Mo($,"zip215"),r&&(U=r(U));const D=P/2,F=v.subarray(0,D),x=qo(v.subarray(D,P));let B,q,N;try{B=e.fromBytes(V,$),q=e.fromBytes(F,$),N=i.multiplyUnsafe(x)}catch{return!1}if(!$&&B.isSmallOrder())return!1;const L=g(H,q.toBytes(),B.toBytes(),U);return q.add(B.multiplyUnsafe(L)).subtract(N).clearCofactor().is0()}const S=s.BYTES,w={secretKey:S,publicKey:S,signature:2*S,seed:S};function T(v=c(w.seed)){return As(v,w.seed,"seed")}function O(v){const U=M.randomSecretKey(v);return{secretKey:U,publicKey:y(U)}}function A(v){return ic(v)&&v.length===o.BYTES}function R(v,U){try{return!!e.fromBytes(v,U)}catch{return!1}}const M={getExtendedPublicKey:d,randomSecretKey:T,isValidSecretKey:A,isValidPublicKey:R,toMontgomery(v){const{y:U}=e.fromBytes(v),V=w.publicKey,K=V===32;if(!K&&V!==57)throw new Error("only defined for 25519 and 448");const H=K?s.div(Ot+U,Ot-U):s.div(U-Ot,U+Ot);return s.toBytes(H)},toMontgomerySecret(v){const U=w.secretKey;As(v,U);const V=t(v.subarray(0,U));return a(V).subarray(0,U)},randomPrivateKey:T,precompute(v=8,U=e.BASE){return U.precompute(v,!1)}};return Object.freeze({keygen:O,getPublicKey:y,sign:m,verify:_,utils:M,Point:e,lengths:w})}function X3(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=yi(t.n,e.nBitLength,!0),i={Fp:n,Fn:r,uvRatio:e.uvRatio},s={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:i,hash:e.hash,eddsaOpts:s}}function z3(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function Y3(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:i}=X3(e),s=G3(t,n),o=W3(s,r,i);return z3(e,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Z3=BigInt(1),I0=BigInt(2);BigInt(3);const J3=BigInt(5),Q3=BigInt(8),wh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Vw={p:wh,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Q3,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function e8(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=wh,c=e*e%s*e%s,a=Zn(c,I0,s)*c%s,u=Zn(a,Z3,s)*e%s,f=Zn(u,J3,s)*u%s,l=Zn(f,t,s)*f%s,d=Zn(l,n,s)*l%s,y=Zn(d,r,s)*d%s,g=Zn(y,i,s)*y%s,m=Zn(g,i,s)*y%s,E=Zn(m,t,s)*f%s;return{pow_p_5_8:Zn(E,I0,s)*e%s,b2:c}}function t8(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const O0=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function n8(e,t){const n=wh,r=mt(t*t*t,n),i=mt(r*r*t,n),s=e8(e*i).pow_p_5_8;let o=mt(e*r*s,n);const c=mt(t*o*o,n),a=o,u=mt(o*O0,n),f=c===e,l=c===mt(-e,n),d=c===mt(-e*O0,n);return f&&(o=a),(l||d)&&(o=u),Lx(o,n)&&(o=mt(-o,n)),{isValid:f||l,value:o}}const r8=yi(Vw.p,{isLE:!0}),i8={...Vw,Fp:r8,hash:n2,adjustScalarBytes:t8,uvRatio:n8},s8=Y3(i8);var B0,N0,Pt,Os;class o8{constructor(t={}){rn(this,Pt);rn(this,Os);this[B0]=this.entries.bind(this),this[N0]="ExpirableMap";const{source:n=[],expirationTime:r=600*1e3}=t,i=Date.now();zt(this,Pt,new Map([...n].map(([s,o])=>[s,{value:o,timestamp:i}]))),zt(this,Os,r)}prune(){const t=Date.now();for(const[n,r]of Fe(this,Pt).entries())t-r.timestamp>Fe(this,Os)&&Fe(this,Pt).delete(n);return this}set(t,n){this.prune();const r={value:n,timestamp:Date.now()};return Fe(this,Pt).set(t,r),this}get(t){const n=Fe(this,Pt).get(t);if(n!==void 0){if(Date.now()-n.timestamp>Fe(this,Os)){Fe(this,Pt).delete(t);return}return n.value}}clear(){Fe(this,Pt).clear()}entries(){const t=Fe(this,Pt).entries();return function*(){for(const[r,i]of t)yield[r,i.value]}()}values(){const t=Fe(this,Pt).values();return function*(){for(const r of t)yield r.value}()}keys(){return Fe(this,Pt).keys()}forEach(t,n){for(const[r,i]of Fe(this,Pt).entries())t.call(n,i.value,r,this)}has(t){return Fe(this,Pt).has(t)}delete(t){return Fe(this,Pt).delete(t)}get size(){return Fe(this,Pt).size}}Pt=new WeakMap,Os=new WeakMap,B0=Symbol.iterator,N0=Symbol.toStringTag;const k0=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw et.fromCode(new hu("Length too long (> 4 bytes)"))},P0=(e,t,n)=>{if(n<=127)return e[t]=n,1;if(n<=255)return e[t]=129,e[t+1]=n,2;if(n<=65535)return e[t]=130,e[t+1]=n>>8,e[t+2]=n,3;if(n<=16777215)return e[t]=131,e[t+1]=n>>16,e[t+2]=n>>8,e[t+3]=n,4;throw et.fromCode(new hu("Length too long (> 4 bytes)"))},al=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw et.fromCode(new Nr("Invalid length 0"));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw et.fromCode(new Nr("Length too long (> 4 bytes)"))},c8=(e,t)=>{const n=al(e,t);if(n===1)return e[t];if(n===2)return e[t+1];if(n===3)return(e[t+1]<<8)+e[t+2];if(n===4)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw et.fromCode(new Nr("Length too long (> 4 bytes)"))};Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]);const R0=Uint8Array.from([48,5,6,3,43,101,112]);Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]);Uint8Array.from([48,29,6,13,43,6,1,4,1,130,220,124,5,3,1,2,1,6,12,43,6,1,4,1,130,220,124,5,3,2,1]);function a8(e,t){const n=2+k0(e.byteLength+1),r=t.byteLength+n+e.byteLength;let i=0;const s=new Uint8Array(1+k0(r)+r);return s[i++]=48,i+=P0(s,i,r),s.set(t,i),i+=t.byteLength,s[i++]=3,i+=P0(s,i,e.byteLength+1),s[i++]=0,s.set(new Uint8Array(e),i),s}const u8=(e,t)=>{let n=0;const r=(c,a)=>{if(i[n++]!==c)throw et.fromCode(new Nr(`Expected ${a} at offset ${n}`))},i=new Uint8Array(e);if(r(48,"sequence"),n+=al(i,n),!pu(i.slice(n,n+t.byteLength),t))throw et.fromCode(new Nr("Not the expected OID."));n+=t.byteLength,r(3,"bit string");const s=c8(i,n)-1;n+=al(i,n),r(0,"0 padding");const o=i.slice(n);if(s!==o.length)throw et.fromCode(new zl(s,o.length));return o};var Go,Wo;const Pi=class Pi{constructor(t){rn(this,Go);rn(this,Wo);if(t.byteLength!==Pi.RAW_KEY_LENGTH)throw et.fromCode(new Nr("An Ed25519 public key must be exactly 32 bytes long"));zt(this,Go,t),zt(this,Wo,Pi.derEncode(t))}static from(t){return this.fromDer(t.toDer())}static fromRaw(t){return new Pi(t)}static fromDer(t){return new Pi(this.derDecode(t))}static derEncode(t){return a8(t,R0)}static derDecode(t){const n=u8(t,R0);if(n.length!==this.RAW_KEY_LENGTH)throw et.fromCode(new Nr("An Ed25519 public key must be exactly 32 bytes long"));return n}get rawKey(){return Fe(this,Go)}get derKey(){return Fe(this,Wo)}toDer(){return this.derKey}toRaw(){return this.rawKey}};Go=new WeakMap,Wo=new WeakMap,Pi.RAW_KEY_LENGTH=32;let ul=Pi;class f8{constructor(){this.observers=[]}subscribe(t){this.observers.push(t)}unsubscribe(t){this.observers=this.observers.filter(n=>n!==t)}notify(t,...n){this.observers.forEach(r=>r(t,...n))}}class l8 extends f8{constructor(){super()}print(t,...n){this.notify({message:t,level:"info"},...n)}warn(t,...n){this.notify({message:t,level:"warn"},...n)}error(t,n,...r){this.notify({message:t,level:"error",error:n},...r)}}const U0=.5,C0=1.5,H0=500,F0=6e4,M0=9e5,q0=10;var Fn,Xo,zo,Yo,Zo,Jo,Qo,ec,Bs;const La=class La{constructor(t=La.default){rn(this,Fn);rn(this,Xo);rn(this,zo);rn(this,Yo);rn(this,Zo);rn(this,Jo);rn(this,Qo);rn(this,ec);rn(this,Bs,0);const{initialInterval:n=H0,randomizationFactor:r=U0,multiplier:i=C0,maxInterval:s=F0,maxElapsedTime:o=M0,maxIterations:c=q0,date:a=Date}=t;zt(this,Fn,n),zt(this,Xo,r),zt(this,zo,i),zt(this,Yo,s),zt(this,ec,a),zt(this,Zo,a.now()),zt(this,Jo,o),zt(this,Qo,c)}get ellapsedTimeInMsec(){return Fe(this,ec).now()-Fe(this,Zo)}get currentInterval(){return Fe(this,Fn)}get count(){return Fe(this,Bs)}get randomValueFromInterval(){const t=Fe(this,Xo)*Fe(this,Fn),n=Fe(this,Fn)-t,r=Fe(this,Fn)+t;return Math.random()*(r-n)+n}incrementCurrentInterval(){return zt(this,Fn,Math.min(Fe(this,Fn)*Fe(this,zo),Fe(this,Yo))),Mh(this,Bs)._++,Fe(this,Fn)}next(){return this.ellapsedTimeInMsec>=Fe(this,Jo)||Fe(this,Bs)>=Fe(this,Qo)?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};Fn=new WeakMap,Xo=new WeakMap,zo=new WeakMap,Yo=new WeakMap,Zo=new WeakMap,Jo=new WeakMap,Qo=new WeakMap,ec=new WeakMap,Bs=new WeakMap,La.default={initialInterval:H0,randomizationFactor:U0,multiplier:C0,maxInterval:F0,maxElapsedTime:M0,maxIterations:q0,date:Date};let fl=La;var mr;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(mr||(mr={}));const ll=60*1e3,h8=1e6,d8=0,p8="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae",y8="ic0.app",g8=".ic0.app",m8="icp0.io",w8=".icp0.io",b8="icp-api.io",E8=".icp-api.io",hf=200,_8=202,S8=404;function T8(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw un.fromCode(new xo("Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present."));else if(typeof globalThis<"u")if(globalThis.fetch)e=globalThis.fetch.bind(globalThis);else throw un.fromCode(new xo("Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available."));else typeof self<"u"&&self.fetch&&(e=self.fetch.bind(self));if(e)return e;throw un.fromCode(new xo("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function x8(e){let t;if(e!==void 0)!e.match(/^[a-z]+:/)&&typeof window<"u"?t=new URL(window.location.protocol+"//"+e):t=new URL(e);else{const n=["ic0.app","icp0.io","127.0.0.1","localhost"],r=[".github.dev",".gitpod.io"],i=typeof window<"u"?window.location:void 0,s=i?.hostname;let o;s&&typeof s=="string"&&(r.some(c=>s.endsWith(c))?o=s:o=n.find(c=>s.endsWith(c))),i&&o?t=new URL(`${i.protocol}//${o}${i.port?":"+i.port:""}`):t=new URL("https://icp-api.io")}return t.toString()}class Tr{#t;#e;#i;#g;#a;#w;#n;#s;#m;#b;#r;#c;#u;#o;get#T(){return this.#o*ll}#f;#l;#h;#d;constructor(t={}){this.#t=null,this.#e=!1,this.#i=d8,this.#g=!1,this.#a=null,this.#w=!1,this._isAgent=!0,this.config={},this.log=new l8,this.#f=[],this.#l=[],this.#h=new o8({expirationTime:5*ll}),this.#d=!0,this.#_=(i,s)=>{if(this.#d===!1)return i;const{status:o,signatures:c=[],requestId:a}=i;for(const u of c){const{timestamp:f,identity:l}=u,d=Ke.fromUint8Array(l).toText();let y;if(o===Us.Replied){const{reply:S}=i;y=Na({status:o,reply:S,timestamp:BigInt(f),request_id:a})}else if(o===Us.Rejected){const{reject_code:S,reject_message:w,error_code:T}=i;y=Na({status:o,reject_code:S,reject_message:w,error_code:T,timestamp:BigInt(f),request_id:a})}else throw fn.fromCode(new Vn(`Unknown status: ${o}`));const g=$e(nx,y),m=s.nodeKeys.get(d);if(!m)throw yt.fromCode(new oh);const E=ul.fromDer(m).rawKey;if(s8.verify(u.signature,g,E))return i;throw An.fromCode(new ch(d))}return i},this.config=t,this.#s=t.fetch||T8()||fetch.bind(globalThis),this.#m=t.fetchOptions,this.#b=t.callOptions,this.#e=t.shouldFetchRootKey??!1,this.#w=t.shouldSyncTime??!1,t.rootKey?this.rootKey=t.rootKey:this.#e?this.rootKey=null:this.rootKey=sc(p8);const n=x8(t.host);this.host=new URL(n),t.verifyQuerySignatures!==void 0&&(this.#d=t.verifyQuerySignatures),this.#c=t.retryTimes??3;const r=()=>new fl({maxIterations:this.#c});if(this.#u=t.backoffStrategy||r,this.host.hostname.endsWith(g8)?this.host.hostname=y8:this.host.hostname.endsWith(w8)?this.host.hostname=m8:this.host.hostname.endsWith(E8)&&(this.host.hostname=b8),t.credentials){const{name:i,password:s}=t.credentials;this.#r=`${i}${s?":"+s:""}`}if(this.#n=Promise.resolve(t.identity||new s0),t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes>5)throw et.fromCode(new ps("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw et.fromCode(new ps("Ingress expiry time must be greater than 0.",t.ingressExpiryInMinutes));this.#o=t.ingressExpiryInMinutes||5,this.addTransform("update",c0(sl)),t.useQueryNonces&&this.addTransform("query",c0(sl)),t.logToConsole&&this.log.subscribe(i=>{i.level==="error"?console.error(i.message):i.level==="warn"?console.warn(i.message):console.log(i.message)})}static createSync(t={}){return new this({...t})}static async create(t={}){const n=Tr.createSync(t);return await n.#y(),n}static async from(t){try{return"config"in t?await Tr.create(t.config):await Tr.create({fetch:t._fetch,fetchOptions:t._fetchOptions,callOptions:t._callOptions,host:t._host.toString(),identity:t._identity??void 0})}catch{throw et.fromCode(new rh)}}isLocal(){const t=this.host.hostname;return t==="127.0.0.1"||t.endsWith("127.0.0.1")}addTransform(t,n,r=n.priority||0){if(t==="update"){const i=this.#l.findIndex(s=>(s.priority||0)<r);this.#l.splice(i>=0?i:this.#l.length,0,Object.assign(n,{priority:r}))}else if(t==="query"){const i=this.#f.findIndex(s=>(s.priority||0)<r);this.#f.splice(i>=0?i:this.#f.length,0,Object.assign(n,{priority:r}))}}async getPrincipal(){if(!this.#n)throw un.fromCode(new ki);return(await this.#n).getPrincipal()}async call(t,n,r){const i=n.callSync??!0,s=await(r??this.#n);if(!s)throw un.fromCode(new ki);const o=Ke.from(t),c=n.effectiveCanisterId?Ke.from(n.effectiveCanisterId):o;await this.#y(c);const a=s.getPrincipal(),u=df(this.#o,this.#i),f={request_type:il.Call,canister_id:o,method_name:n.methodName,arg:n.arg,sender:a,ingress_expiry:u};let l=await this._transform({request:{body:null,method:"POST",headers:{"Content-Type":"application/cbor",...this.#r?{Authorization:"Basic "+btoa(this.#r)}:{}}},endpoint:Ui.Call,body:f}),d;n?.nonce?d=y(n.nonce):l.body.nonce?d=y(l.body.nonce):d=void 0,f.nonce=d;function y(_){return Object.assign(_,{__nonce__:void 0})}l=await s.transformRequest(l);const g=Qu(l.body),m=this.#u(),E=Zu(f);try{const w=i?()=>(this.log.print(`fetching "/api/v3/canister/${c.toText()}/call" with request:`,l),this.#s(""+new URL(`/api/v3/canister/${c.toText()}/call`,this.host),{...this.#b,...l.request,body:g})):()=>(this.log.print(`fetching "/api/v2/canister/${c.toText()}/call" with request:`,l),this.#s(""+new URL(`/api/v2/canister/${c.toText()}/call`,this.host),{...this.#b,...l.request,body:g})),{responseBodyBytes:T,...O}=await this.#p({requestFn:w,backoff:m,tries:0}),A=T.byteLength>0?er(T):null;return{requestId:E,response:{...O,body:A},requestDetails:f}}catch(_){let S;if(_ instanceof wr){if(_.hasCode(Aa))return this.log.warn("v3 api not supported. Fall back to v2"),this.call(t,{...n,callSync:!1},r);if(_.hasCode(ps)&&!this.#g)return await this.syncTime(o),this.call(o,n,r);_.code.requestContext={requestId:E,senderPubKey:l.body.sender_pubkey,senderSignature:l.body.sender_sig,ingressExpiry:l.body.content.ingress_expiry},S=_}else S=fn.fromCode(new Vn(_));throw this.log.error(`Error while making call: ${S.message}`,S),S}}async#E(t){const{ecid:n,transformedRequest:r,body:i,requestId:s,backoff:o,tries:c}=t,a=c===0?0:o.next();if(this.log.print(`fetching "/api/v2/canister/${n.toString()}/query" with tries:`,{tries:c,backoff:o,delay:a}),a===null)throw fn.fromCode(new Co(`Backoff strategy exhausted after ${c} attempts.`,s));a>0&&await new Promise(y=>setTimeout(y,a));let u;try{this.log.print(`fetching "/api/v2/canister/${n.toString()}/query" with request:`,r);const y=await this.#s(""+new URL(`/api/v2/canister/${n.toString()}/query`,this.host),{...this.#m,...r.request,body:i});if(y.status===hf)u={...er(Ba(await y.arrayBuffer())),httpDetails:{ok:y.ok,status:y.status,statusText:y.statusText,headers:ef(y.headers)},requestId:s};else throw yt.fromCode(new xa(y.status,y.statusText,ef(y.headers),await y.text()))}catch(y){if(c<this.#c)return this.log.warn(`Caught exception while attempting to make query:
66
+ ic-request`);const nx=new TextEncoder().encode("\vic-response");new TextEncoder().encode("ic-request-auth-delegation");class s0{getPrincipal(){return Ke.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}}class Ji extends Error{constructor(t){super(t),this.name="DecodingError"}}const ow=55799,cw=Symbol("CBOR_STOP_CODE");var Ln=(e=>(e[e.False=20]="False",e[e.True=21]="True",e[e.Null=22]="Null",e[e.Undefined=23]="Undefined",e[e.Break=31]="Break",e))(Ln||{}),Tt=(e=>(e[e.UnsignedInteger=0]="UnsignedInteger",e[e.NegativeInteger=1]="NegativeInteger",e[e.ByteString=2]="ByteString",e[e.TextString=3]="TextString",e[e.Array=4]="Array",e[e.Map=5]="Map",e[e.Tag=6]="Tag",e[e.Simple=7]="Simple",e))(Tt||{});const rx=23,ix=255,sx=65535,ox=4294967295,cx=BigInt("0xffffffffffffffff");var qn=(e=>(e[e.Value=23]="Value",e[e.OneByte=24]="OneByte",e[e.TwoBytes=25]="TwoBytes",e[e.FourBytes=26]="FourBytes",e[e.EightBytes=27]="EightBytes",e[e.Indefinite=31]="Indefinite",e))(qn||{});const Ts=!1;function ax(e){return e==null}function aw(e,t){const n=new Uint8Array(t);return n.set(e),n}const ux=new TextDecoder;function fx(e){return(e&224)>>5}function lx(e){return e&31}let Ho=new Uint8Array,no,$n=0;function hx(e,t){Ho=e,$n=0;const n=qi();return t?.(n)??n}function qi(e){const[t,n]=ta();switch(t){case Tt.UnsignedInteger:return Gs(n);case Tt.NegativeInteger:return gx(n);case Tt.ByteString:return uw(n);case Tt.TextString:return rl(n);case Tt.Array:return dx(n);case Tt.Map:return yx(n);case Tt.Tag:return mx(n);case Tt.Simple:return px(n)}throw new Ji(`Unsupported major type: ${t}`)}function ta(){const e=Ho.at($n);if(ax(e))throw new Ji("Provided CBOR data is empty");const t=fx(e),n=lx(e);return $n++,[t,n]}function dx(e,t){const n=Gs(e);if(n===1/0){const i=[];let s=qi();for(;s!==cw;)i.push(s),s=qi();return i}const r=new Array(n);for(let i=0;i<n;i++){const s=qi();r[i]=s}return r}function px(e){switch(e){case Ln.False:return!1;case Ln.True:return!0;case Ln.Null:return null;case Ln.Undefined:return;case Ln.Break:return cw}throw new Ji(`Unrecognized simple type: ${e.toString(2)}`)}function yx(e,t){const n=Gs(e),r={};if(n===1/0){let[i,s]=ta();for(;i!==Tt.Simple&&s!==Ln.Break;){const o=rl(s),c=qi();r[o]=c,[i,s]=ta()}return r}for(let i=0;i<n;i++){const[s,o]=ta();if(s!==Tt.TextString)throw new Ji("Map keys must be text strings");const c=rl(o),a=qi();r[c]=a}return r}function Gs(e){if(e<=qn.Value)return e;switch(no=new DataView(Ho.buffer,Ho.byteOffset+$n),e){case qn.OneByte:return $n++,no.getUint8(0);case qn.TwoBytes:return $n+=2,no.getUint16(0,Ts);case qn.FourBytes:return $n+=4,no.getUint32(0,Ts);case qn.EightBytes:return $n+=8,no.getBigUint64(0,Ts);case qn.Indefinite:return 1/0;default:throw new Ji(`Unsupported integer info: ${e.toString(2)}`)}}function gx(e){const t=Gs(e);return typeof t=="number"?-1-t:-1n-t}function uw(e){const t=Gs(e);if(t>Number.MAX_SAFE_INTEGER)throw new Ji("Byte length is too large");const n=Number(t);return $n+=n,Ho.slice($n-n,$n)}function rl(e){const t=uw(e);return ux.decode(t)}function mx(e,t){const n=Gs(e);if(n===ow)return qi();throw new Ji(`Unsupported tag: ${n}.`)}class uh extends Error{constructor(t){super(t),this.name="SerializationError"}}const wx=2*1024,bx=100,Ex=new TextEncoder;function ro(e){return e<<5}let wn=new Uint8Array(wx),Hn=new DataView(wn.buffer),St=0,Ju=[];function _x(e,t){St=0;const n=t?.(e)??e;return Bx(ow,n,t),wn.slice(0,St)}function fh(e,t){if(St>wn.length-bx&&(wn=aw(wn,wn.length*2),Hn=new DataView(wn.buffer)),e===!1||e===!0||e===null||e===void 0){xx(e);return}if(typeof e=="number"||typeof e=="bigint"){Ox(e);return}if(typeof e=="string"){hw(e);return}if(e instanceof Uint8Array){o0(e);return}if(e instanceof ArrayBuffer){o0(new Uint8Array(e));return}if(Array.isArray(e)){Sx(e,t);return}if(typeof e=="object"){Tx(e,t);return}throw new uh(`Unsupported type: ${typeof e}`)}function Sx(e,t){Ws(Tt.Array,e.length),e.forEach((n,r)=>{fh(t?.(n,r.toString())??n,t)})}function Tx(e,t){Ju=Object.entries(e),Ws(Tt.Map,Ju.length),Ju.forEach(([n,r])=>{hw(n),fh(t?.(r,n)??r,t)})}function Ws(e,t){if(t<=rx){Hn.setUint8(St++,ro(e)|Number(t));return}if(t<=ix){Hn.setUint8(St++,ro(e)|qn.OneByte),Hn.setUint8(St,Number(t)),St+=1;return}if(t<=sx){Hn.setUint8(St++,ro(e)|qn.TwoBytes),Hn.setUint16(St,Number(t),Ts),St+=2;return}if(t<=ox){Hn.setUint8(St++,ro(e)|qn.FourBytes),Hn.setUint32(St,Number(t),Ts),St+=4;return}if(t<=cx){Hn.setUint8(St++,ro(e)|qn.EightBytes),Hn.setBigUint64(St,BigInt(t),Ts),St+=8;return}throw new uh(`Value too large to encode: ${t}`)}function xx(e){Ws(Tt.Simple,Ax(e))}function Ax(e){if(e===!1)return Ln.False;if(e===!0)return Ln.True;if(e===null)return Ln.Null;if(e===void 0)return Ln.Undefined;throw new uh(`Unrecognized simple value: ${e.toString()}`)}function fw(e,t){Ws(e,t.length),St>wn.length-t.length&&(wn=aw(wn,wn.length+t.length),Hn=new DataView(wn.buffer)),wn.set(t,St),St+=t.length}function lw(e,t){Ws(e,t)}function vx(e){lw(Tt.UnsignedInteger,e)}function Ix(e){lw(Tt.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function Ox(e){e>=0?vx(e):Ix(e)}function hw(e){fw(Tt.TextString,Ex.encode(e))}function o0(e){fw(Tt.ByteString,e)}function Bx(e,t,n){Ws(Tt.Tag,e),fh(t,n)}function Nx(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function Qu(e){try{return _x(e,t=>Ke.isPrincipal(t)?t.toUint8Array():xs.isExpiry(t)?t.toBigInt():Nx(t)?t.toCborValue():t)}catch(t){throw et.fromCode(new Zl(t,e))}}function er(e){try{return hx(e)}catch(t){throw et.fromCode(new Yl(t,e))}}const Uc=()=>{if(typeof window<"u"&&window.crypto&&window.crypto.getRandomValues){const e=new Uint32Array(1);return window.crypto.getRandomValues(e),e[0]}if(typeof crypto<"u"&&crypto.getRandomValues){const e=new Uint32Array(1);return crypto.getRandomValues(e),e[0]}return typeof crypto<"u"&&crypto.randomInt?crypto.randomInt(0,4294967295):Math.floor(Math.random()*4294967295)};var Ui;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})(Ui||(Ui={}));var il;(function(e){e.Call="call"})(il||(il={}));var Fo;(function(e){e.Query="query",e.ReadState="read_state"})(Fo||(Fo={}));function sl(){const e=new ArrayBuffer(16),t=new DataView(e),n=Uc(),r=Uc(),i=Uc(),s=Uc();return t.setUint32(0,n),t.setUint32(4,r),t.setUint32(8,i),t.setUint32(12,s),Object.assign(new Uint8Array(e),{__nonce__:void 0})}const Cc="__expiry__",lh=BigInt(1e3),kx=BigInt(1e6),dw=BigInt(60),Px=BigInt(90)*lh;function pw(e){return e/lh}function Rx(e){return pw(e)/dw}class xs{constructor(t){this.__expiry__=t,this._isExpiry=!0}static fromDeltaInMilliseconds(t,n=0){const r=BigInt(t),i=BigInt(Date.now())+r+BigInt(n);let s;return r<Px?s=pw(i):s=Rx(i)*dw,new xs(s*lh*kx)}toBigInt(){return this.__expiry__}toHash(){return ft(this.__expiry__)}toString(){return this.__expiry__.toString()}toJSON(){return{[Cc]:this.toString()}}static fromJSON(t){const n=JSON.parse(t);if(n[Cc])try{const r=BigInt(n[Cc]);return new xs(r)}catch(r){throw new et(new Oa(`Not a valid BigInt: ${r}`))}throw new et(new Oa(`The input does not contain the key ${Cc}`))}static isExpiry(t){return t instanceof xs||typeof t=="object"&&t!==null&&"_isExpiry"in t&&t._isExpiry===!0&&"__expiry__"in t&&typeof t.__expiry__=="bigint"}}function c0(e=sl){return async t=>{const n=t.request.headers;t.request.headers=n,t.endpoint===Ui.Call&&(t.body.nonce=e())}}function ef(e){const t=[];return e.forEach((n,r)=>{t.push([r,n])}),t}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const hh=BigInt(0),ka=BigInt(1);function Mo(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function As(e,t,n=""){const r=ic(e),i=e?.length,s=t!==void 0;if(!r||s&&i!==t){const o=n&&`"${n}" `,c=s?` of length ${t}`:"",a=r?`length=${i}`:`type=${typeof e}`;throw new Error(o+"expected Uint8Array"+c+", got "+a)}return e}function yw(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?hh:BigInt("0x"+e)}function rr(e){return yw(rt(e))}function qo(e){return On(e),yw(rt(Uint8Array.from(e).reverse()))}function Ut(e,t){return sc(e.toString(16).padStart(t*2,"0"))}function gw(e,t){return Ut(e,t).reverse()}function cn(e,t,n){let r;if(typeof t=="string")try{r=sc(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(ic(t))r=Uint8Array.from(t);else throw new Error(e+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(e+" of length "+n+" expected, got "+i);return r}function a0(e){return Uint8Array.from(e)}const tf=e=>typeof e=="bigint"&&hh<=e;function mw(e,t,n){return tf(e)&&tf(t)&&tf(n)&&t<=e&&e<n}function u0(e,t,n,r){if(!mw(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Vo(e){let t;for(t=0;e>hh;e>>=ka,t+=1);return t}function Ux(e,t){return e>>BigInt(t)&ka}const Qi=e=>(ka<<BigInt(e))-ka;function Cx(e){return typeof e=="function"&&Number.isSafeInteger(e.outputLen)}function mc(e,t,n={}){if(!e||typeof e!="object")throw new Error("expected valid options object");function r(i,s,o){const c=e[i];if(o&&c===void 0)return;const a=typeof c;if(a!==s||c===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${a}`)}Object.entries(t).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}const ww=()=>{throw new Error("not implemented")};function Lo(e){const t=new WeakMap;return(n,...r)=>{const i=t.get(n);if(i!==void 0)return i;const s=e(n,...r);return t.set(n,s),s}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const hn=BigInt(0),Ft=BigInt(1),Ci=BigInt(2),bw=BigInt(3),Ew=BigInt(4),_w=BigInt(5),Hx=BigInt(7),Sw=BigInt(8),Fx=BigInt(9),Tw=BigInt(16);function mt(e,t){const n=e%t;return n>=hn?n:t+n}function Zn(e,t,n){let r=e;for(;t-- >hn;)r*=r,r%=n;return r}function f0(e,t){if(e===hn)throw new Error("invert: expected non-zero number");if(t<=hn)throw new Error("invert: expected positive modulus, got "+t);let n=mt(e,t),r=t,i=hn,s=Ft;for(;n!==hn;){const c=r/n,a=r%n,u=i-s*c;r=n,n=a,i=s,s=u}if(r!==Ft)throw new Error("invert: does not exist");return mt(i,t)}function dh(e,t,n){if(!e.eql(e.sqr(t),n))throw new Error("Cannot find square root")}function xw(e,t){const n=(e.ORDER+Ft)/Ew,r=e.pow(t,n);return dh(e,r,t),r}function Mx(e,t){const n=(e.ORDER-_w)/Sw,r=e.mul(t,Ci),i=e.pow(r,n),s=e.mul(t,i),o=e.mul(e.mul(s,Ci),i),c=e.mul(s,e.sub(o,e.ONE));return dh(e,c,t),c}function qx(e){const t=yi(e),n=Aw(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+Hx)/Tw;return(c,a)=>{let u=c.pow(a,o),f=c.mul(u,r);const l=c.mul(u,i),d=c.mul(u,s),y=c.eql(c.sqr(f),a),g=c.eql(c.sqr(l),a);u=c.cmov(u,f,y),f=c.cmov(d,l,g);const m=c.eql(c.sqr(f),a),E=c.cmov(u,f,m);return dh(c,E,a),E}}function Aw(e){if(e<bw)throw new Error("sqrt is not defined for small field");let t=e-Ft,n=0;for(;t%Ci===hn;)t/=Ci,n++;let r=Ci;const i=yi(e);for(;Pa(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return xw;let s=i.pow(r,t);const o=(t+Ft)/Ci;return function(a,u){if(a.is0(u))return u;if(Pa(a,u)!==1)throw new Error("Cannot find square root");let f=n,l=a.mul(a.ONE,s),d=a.pow(u,t),y=a.pow(u,o);for(;!a.eql(d,a.ONE);){if(a.is0(d))return a.ZERO;let g=1,m=a.sqr(d);for(;!a.eql(m,a.ONE);)if(g++,m=a.sqr(m),g===f)throw new Error("Cannot find square root");const E=Ft<<BigInt(f-g-1),_=a.pow(l,E);f=g,l=a.sqr(_),d=a.mul(d,l),y=a.mul(y,_)}return y}}function Vx(e){return e%Ew===bw?xw:e%Sw===_w?Mx:e%Tw===Fx?qx(e):Aw(e)}const Lx=(e,t)=>(mt(e,t)&Ft)===Ft,$x=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vw(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=$x.reduce((r,i)=>(r[i]="function",r),t);return mc(e,n),e}function yu(e,t,n){if(n<hn)throw new Error("invalid exponent, negatives unsupported");if(n===hn)return e.ONE;if(n===Ft)return t;let r=e.ONE,i=t;for(;n>hn;)n&Ft&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Ft;return r}function es(e,t,n=!1){const r=new Array(t.length).fill(n?e.ZERO:void 0),i=t.reduce((o,c,a)=>e.is0(c)?o:(r[a]=o,e.mul(o,c)),e.ONE),s=e.inv(i);return t.reduceRight((o,c,a)=>e.is0(c)?o:(r[a]=e.mul(o,r[a]),e.mul(o,c)),s),r}function Pa(e,t){const n=(e.ORDER-Ft)/Ci,r=e.pow(t,n),i=e.eql(r,e.ONE),s=e.eql(r,e.ZERO),o=e.eql(r,e.neg(e.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Dx(e,t){t!==void 0&&vb(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function yi(e,t,n=!1,r={}){if(e<=hn)throw new Error("invalid field: expected ORDER > 0, got "+e);let i,s,o=!1,c;if(typeof t=="object"&&t!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const d=t;d.BITS&&(i=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(n=d.isLE),typeof d.modFromBytes=="boolean"&&(o=d.modFromBytes),c=d.allowedLengths}else typeof t=="number"&&(i=t),r.sqrt&&(s=r.sqrt);const{nBitLength:a,nByteLength:u}=Dx(e,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let f;const l=Object.freeze({ORDER:e,isLE:n,BITS:a,BYTES:u,MASK:Qi(a),ZERO:hn,ONE:Ft,allowedLengths:c,create:d=>mt(d,e),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return hn<=d&&d<e},is0:d=>d===hn,isValidNot0:d=>!l.is0(d)&&l.isValid(d),isOdd:d=>(d&Ft)===Ft,neg:d=>mt(-d,e),eql:(d,y)=>d===y,sqr:d=>mt(d*d,e),add:(d,y)=>mt(d+y,e),sub:(d,y)=>mt(d-y,e),mul:(d,y)=>mt(d*y,e),pow:(d,y)=>yu(l,d,y),div:(d,y)=>mt(d*f0(y,e),e),sqrN:d=>d*d,addN:(d,y)=>d+y,subN:(d,y)=>d-y,mulN:(d,y)=>d*y,inv:d=>f0(d,e),sqrt:s||(d=>(f||(f=Vx(e)),f(l,d))),toBytes:d=>n?gw(d,u):Ut(d,u),fromBytes:(d,y=!0)=>{if(c){if(!c.includes(d.length)||d.length>u)throw new Error("Field.fromBytes: expected "+c+" bytes, got "+d.length);const m=new Uint8Array(u);m.set(d,n?0:m.length-d.length),d=m}if(d.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+d.length);let g=n?qo(d):rr(d);if(o&&(g=mt(g,e)),!y&&!l.isValid(g))throw new Error("invalid field element: outside of range 0..ORDER");return g},invertBatch:d=>es(l,d),cmov:(d,y,g)=>g?y:d});return Object.freeze(l)}function Iw(e){if(typeof e!="bigint")throw new Error("field order must be bigint");const t=e.toString(2).length;return Math.ceil(t/8)}function Ow(e){const t=Iw(e);return t+Math.ceil(t/2)}function jx(e,t,n=!1){const r=e.length,i=Iw(t),s=Ow(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?qo(e):rr(e),c=mt(o,t-Ft)+Ft;return n?gw(c,i):Ut(c,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hs=BigInt(0),Hi=BigInt(1);function Ra(e,t){const n=t.negate();return e?n:t}function _r(e,t){const n=es(e.Fp,t.map(r=>r.Z));return t.map((r,i)=>e.fromAffine(r.toAffine(n[i])))}function Bw(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function nf(e,t){Bw(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e,s=Qi(e),o=BigInt(e);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function l0(e,t,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let c=Number(e&i),a=e>>o;c>r&&(c-=s,a+=Hi);const u=t*r,f=u+Math.abs(c)-1,l=c===0,d=c<0,y=t%2!==0;return{nextN:a,offset:f,isZero:l,isNeg:d,isNegF:y,offsetF:u}}function Kx(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach((n,r)=>{if(!(n instanceof t))throw new Error("invalid point at index "+r)})}function Gx(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach((n,r)=>{if(!t.isValid(n))throw new Error("invalid scalar at index "+r)})}const rf=new WeakMap,Nw=new WeakMap;function sf(e){return Nw.get(e)||1}function h0(e){if(e!==Hs)throw new Error("invalid wNAF")}class kw{constructor(t,n){this.BASE=t.BASE,this.ZERO=t.ZERO,this.Fn=t.Fn,this.bits=n}_unsafeLadder(t,n,r=this.ZERO){let i=t;for(;n>Hs;)n&Hi&&(r=r.add(i)),i=i.double(),n>>=Hi;return r}precomputeWindow(t,n){const{windows:r,windowSize:i}=nf(n,this.bits),s=[];let o=t,c=o;for(let a=0;a<r;a++){c=o,s.push(c);for(let u=1;u<i;u++)c=c.add(o),s.push(c);o=c.double()}return s}wNAF(t,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=nf(t,this.bits);for(let c=0;c<o.windows;c++){const{nextN:a,offset:u,isZero:f,isNeg:l,isNegF:d,offsetF:y}=l0(r,c,o);r=a,f?s=s.add(Ra(d,n[y])):i=i.add(Ra(l,n[u]))}return h0(r),{p:i,f:s}}wNAFUnsafe(t,n,r,i=this.ZERO){const s=nf(t,this.bits);for(let o=0;o<s.windows&&r!==Hs;o++){const{nextN:c,offset:a,isZero:u,isNeg:f}=l0(r,o,s);if(r=c,!u){const l=n[a];i=i.add(f?l.negate():l)}}return h0(r),i}getPrecomputes(t,n,r){let i=rf.get(n);return i||(i=this.precomputeWindow(n,t),t!==1&&(typeof r=="function"&&(i=r(i)),rf.set(n,i))),i}cached(t,n,r){const i=sf(t);return this.wNAF(i,this.getPrecomputes(i,t,r),n)}unsafe(t,n,r,i){const s=sf(t);return s===1?this._unsafeLadder(t,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,t,r),n,i)}createCache(t,n){Bw(n,this.bits),Nw.set(t,n),rf.delete(t)}hasCache(t){return sf(t)!==1}}function Wx(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>Hs||r>Hs;)n&Hi&&(s=s.add(i)),r&Hi&&(o=o.add(i)),i=i.double(),n>>=Hi,r>>=Hi;return{p1:s,p2:o}}function Pw(e,t,n,r){Kx(n,e),Gx(r,t);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=e.ZERO,c=Vo(BigInt(i));let a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);const u=Qi(a),f=new Array(Number(u)+1).fill(o),l=Math.floor((t.BITS-1)/a)*a;let d=o;for(let y=l;y>=0;y-=a){f.fill(o);for(let m=0;m<s;m++){const E=r[m],_=Number(E>>BigInt(y)&u);f[_]=f[_].add(n[m])}let g=o;for(let m=f.length-1,E=o;m>0;m--)E=E.add(f[m]),g=g.add(E);if(d=d.add(g),y!==0)for(let m=0;m<a;m++)d=d.double()}return d}function d0(e,t,n){if(t){if(t.ORDER!==e)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return vw(t),t}else return yi(e,{isLE:n})}function Rw(e,t,n={},r){if(r===void 0&&(r=e==="edwards"),!t||typeof t!="object")throw new Error(`expected valid ${e} CURVE object`);for(const a of["p","n","h"]){const u=t[a];if(!(typeof u=="bigint"&&u>Hs))throw new Error(`CURVE.${a} must be positive bigint`)}const i=d0(t.p,n.Fp,r),s=d0(t.n,n.Fn,r),c=["Gx","Gy","a",e==="weierstrass"?"b":"d"];for(const a of c)if(!i.isValid(t[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return t=Object.freeze(Object.assign({},t)),{CURVE:t,Fp:i,Fn:s}}const Xx=rr;function ni(e,t){if($o(e),$o(t),e<0||e>=1<<8*t)throw new Error("invalid I2OSP input: "+e);const n=Array.from({length:t}).fill(0);for(let r=t-1;r>=0;r--)n[r]=e&255,e>>>=8;return new Uint8Array(n)}function zx(e,t){const n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e[r]^t[r];return n}function $o(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function Uw(e){if(!ic(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?dt(e):e}function Yx(e,t,n,r){On(e),$o(n),t=Uw(t),t.length>255&&(t=r($e(dt("H2C-OVERSIZE-DST-"),t)));const{outputLen:i,blockLen:s}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const c=$e(t,ni(t.length,1)),a=ni(0,s),u=ni(n,2),f=new Array(o),l=r($e(a,e,u,ni(0,1),c));f[0]=r($e(l,ni(1,1),c));for(let y=1;y<=o;y++){const g=[zx(l,f[y-1]),ni(y+1,1),c];f[y]=r($e(...g))}return $e(...f).slice(0,n)}function Zx(e,t,n,r,i){if(On(e),$o(n),t=Uw(t),t.length>255){const s=Math.ceil(2*r/8);t=i.create({dkLen:s}).update(dt("H2C-OVERSIZE-DST-")).update(t).digest()}if(n>65535||t.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:n}).update(e).update(ni(n,2)).update(t).update(ni(t.length,1)).digest()}function of(e,t,n){mc(n,{p:"bigint",m:"number",k:"number",hash:"function"});const{p:r,k:i,m:s,hash:o,expand:c,DST:a}=n;if(!Cx(n.hash))throw new Error("expected valid hash");On(e),$o(t);const u=r.toString(2).length,f=Math.ceil((u+i)/8),l=t*s*f;let d;if(c==="xmd")d=Yx(e,a,l,o);else if(c==="xof")d=Zx(e,a,l,i,o);else if(c==="_internal_pass")d=e;else throw new Error('expand must be "xmd" or "xof"');const y=new Array(t);for(let g=0;g<t;g++){const m=new Array(s);for(let E=0;E<s;E++){const _=f*(E+g*s),S=d.subarray(_,_+f);m[E]=mt(Xx(S),r)}y[g]=m}return y}function Cw(e,t){const n=t.map(r=>Array.from(r).reverse());return(r,i)=>{const[s,o,c,a]=n.map(l=>l.reduce((d,y)=>e.add(e.mul(d,r),y))),[u,f]=es(e,[o,a],!0);return r=e.mul(s,u),i=e.mul(i,e.mul(c,f)),{x:r,y:i}}}const Jx=dt("HashToScalar-");function p0(e,t,n){if(typeof t!="function")throw new Error("mapToCurve() must be defined");function r(s){return e.fromAffine(t(s))}function i(s){const o=s.clearCofactor();return o.equals(e.ZERO)?e.ZERO:(o.assertValidity(),o)}return{defaults:n,hashToCurve(s,o){const c=Object.assign({},n,o),a=of(s,2,c),u=r(a[0]),f=r(a[1]);return i(u.add(f))},encodeToCurve(s,o){const c=n.encodeDST?{DST:n.encodeDST}:{},a=Object.assign({},n,c,o),u=of(s,1,a),f=r(u[0]);return i(f)},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(const o of s)if(typeof o!="bigint")throw new Error("expected array of bigints");return i(r(s))},hashToScalar(s,o){const c=e.Fn.ORDER,a=Object.assign({},n,{p:c,m:1,DST:Jx},o);return of(s,1,a)[0][0]}}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const y0=(e,t)=>(e+(e>=0?t:-t)/pr)/t;function Qx(e,t,n){const[[r,i],[s,o]]=t,c=y0(o*e,n),a=y0(-i*e,n);let u=e-c*r-a*s,f=-c*i-a*o;const l=u<Fi,d=f<Fi;l&&(u=-u),d&&(f=-f);const y=Qi(Math.ceil(Vo(n)/2))+Qt;if(u<Fi||u>=y||f<Fi||f>=y)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:u,k2neg:d,k2:f}}const Fi=BigInt(0),Qt=BigInt(1),pr=BigInt(2),ys=BigInt(3),ol=BigInt(4);function Ua(e,t){const{BYTES:n}=e;let r;if(typeof t=="bigint")r=t;else{let i=cn("private key",t);try{r=e.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof t}`)}}if(!e.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function e3(e,t={}){const n=Rw("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:c}=s;mc(t,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:a}=t;if(a&&(!r.is0(s.a)||typeof a.beta!="bigint"||!Array.isArray(a.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=r3(r,i);function f(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(K,H,$){const{x:P,y:D}=H.toAffine(),F=r.toBytes(P);if(Mo($,"isCompressed"),$){f();const x=!r.isOdd(D);return $e(t3(x),F)}else return $e(Uint8Array.of(4),F,r.toBytes(D))}function d(K){As(K,void 0,"Point");const{publicKey:H,publicKeyUncompressed:$}=u,P=K.length,D=K[0],F=K.subarray(1);if(P===H&&(D===2||D===3)){const x=r.fromBytes(F);if(!r.isValid(x))throw new Error("bad point: is not on curve, wrong x");const B=m(x);let q;try{q=r.sqrt(B)}catch(G){const X=G instanceof Error?": "+G.message:"";throw new Error("bad point: is not on curve, sqrt error"+X)}f();const N=r.isOdd(q);return(D&1)===1!==N&&(q=r.neg(q)),{x,y:q}}else if(P===$&&D===4){const x=r.BYTES,B=r.fromBytes(F.subarray(0,x)),q=r.fromBytes(F.subarray(x,x*2));if(!E(B,q))throw new Error("bad point: is not on curve");return{x:B,y:q}}else throw new Error(`bad point: got length ${P}, expected compressed=${H} or uncompressed=${$}`)}const y=t.toBytes||l,g=t.fromBytes||d;function m(K){const H=r.sqr(K),$=r.mul(H,K);return r.add(r.add($,r.mul(K,s.a)),s.b)}function E(K,H){const $=r.sqr(H),P=m(K);return r.eql($,P)}if(!E(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const _=r.mul(r.pow(s.a,ys),ol),S=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(_,S)))throw new Error("bad curve params: a or b");function w(K,H,$=!1){if(!r.isValid(H)||$&&r.is0(H))throw new Error(`bad point coordinate ${K}`);return H}function T(K){if(!(K instanceof v))throw new Error("ProjectivePoint expected")}function O(K){if(!a||!a.basises)throw new Error("no endo");return Qx(K,a.basises,i.ORDER)}const A=Lo((K,H)=>{const{X:$,Y:P,Z:D}=K;if(r.eql(D,r.ONE))return{x:$,y:P};const F=K.is0();H==null&&(H=F?r.ONE:r.inv(D));const x=r.mul($,H),B=r.mul(P,H),q=r.mul(D,H);if(F)return{x:r.ZERO,y:r.ZERO};if(!r.eql(q,r.ONE))throw new Error("invZ was invalid");return{x,y:B}}),R=Lo(K=>{if(K.is0()){if(t.allowInfinityPoint&&!r.is0(K.Y))return;throw new Error("bad point: ZERO")}const{x:H,y:$}=K.toAffine();if(!r.isValid(H)||!r.isValid($))throw new Error("bad point: x or y not field elements");if(!E(H,$))throw new Error("bad point: equation left != right");if(!K.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function M(K,H,$,P,D){return $=new v(r.mul($.X,K),$.Y,$.Z),H=Ra(P,H),$=Ra(D,$),H.add($)}class v{constructor(H,$,P){this.X=w("x",H),this.Y=w("y",$,!0),this.Z=w("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(H){const{x:$,y:P}=H||{};if(!H||!r.isValid($)||!r.isValid(P))throw new Error("invalid affine point");if(H instanceof v)throw new Error("projective point not allowed");return r.is0($)&&r.is0(P)?v.ZERO:new v($,P,r.ONE)}static fromBytes(H){const $=v.fromAffine(g(As(H,void 0,"point")));return $.assertValidity(),$}static fromHex(H){return v.fromBytes(cn("pointHex",H))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(H=8,$=!0){return V.createCache(this,H),$||this.multiply(ys),this}assertValidity(){R(this)}hasEvenY(){const{y:H}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(H)}equals(H){T(H);const{X:$,Y:P,Z:D}=this,{X:F,Y:x,Z:B}=H,q=r.eql(r.mul($,B),r.mul(F,D)),N=r.eql(r.mul(P,B),r.mul(x,D));return q&&N}negate(){return new v(this.X,r.neg(this.Y),this.Z)}double(){const{a:H,b:$}=s,P=r.mul($,ys),{X:D,Y:F,Z:x}=this;let B=r.ZERO,q=r.ZERO,N=r.ZERO,L=r.mul(D,D),G=r.mul(F,F),X=r.mul(x,x),Y=r.mul(D,F);return Y=r.add(Y,Y),N=r.mul(D,x),N=r.add(N,N),B=r.mul(H,N),q=r.mul(P,X),q=r.add(B,q),B=r.sub(G,q),q=r.add(G,q),q=r.mul(B,q),B=r.mul(Y,B),N=r.mul(P,N),X=r.mul(H,X),Y=r.sub(L,X),Y=r.mul(H,Y),Y=r.add(Y,N),N=r.add(L,L),L=r.add(N,L),L=r.add(L,X),L=r.mul(L,Y),q=r.add(q,L),X=r.mul(F,x),X=r.add(X,X),L=r.mul(X,Y),B=r.sub(B,L),N=r.mul(X,G),N=r.add(N,N),N=r.add(N,N),new v(B,q,N)}add(H){T(H);const{X:$,Y:P,Z:D}=this,{X:F,Y:x,Z:B}=H;let q=r.ZERO,N=r.ZERO,L=r.ZERO;const G=s.a,X=r.mul(s.b,ys);let Y=r.mul($,F),ce=r.mul(P,x),ue=r.mul(D,B),te=r.add($,P),Z=r.add(F,x);te=r.mul(te,Z),Z=r.add(Y,ce),te=r.sub(te,Z),Z=r.add($,D);let ae=r.add(F,B);return Z=r.mul(Z,ae),ae=r.add(Y,ue),Z=r.sub(Z,ae),ae=r.add(P,D),q=r.add(x,B),ae=r.mul(ae,q),q=r.add(ce,ue),ae=r.sub(ae,q),L=r.mul(G,Z),q=r.mul(X,ue),L=r.add(q,L),q=r.sub(ce,L),L=r.add(ce,L),N=r.mul(q,L),ce=r.add(Y,Y),ce=r.add(ce,Y),ue=r.mul(G,ue),Z=r.mul(X,Z),ce=r.add(ce,ue),ue=r.sub(Y,ue),ue=r.mul(G,ue),Z=r.add(Z,ue),Y=r.mul(ce,Z),N=r.add(N,Y),Y=r.mul(ae,Z),q=r.mul(te,q),q=r.sub(q,Y),Y=r.mul(te,ce),L=r.mul(ae,L),L=r.add(L,Y),new v(q,N,L)}subtract(H){return this.add(H.negate())}is0(){return this.equals(v.ZERO)}multiply(H){const{endo:$}=t;if(!i.isValidNot0(H))throw new Error("invalid scalar: out of range");let P,D;const F=x=>V.cached(this,x,B=>_r(v,B));if($){const{k1neg:x,k1:B,k2neg:q,k2:N}=O(H),{p:L,f:G}=F(B),{p:X,f:Y}=F(N);D=G.add(Y),P=M($.beta,L,X,x,q)}else{const{p:x,f:B}=F(H);P=x,D=B}return _r(v,[P,D])[0]}multiplyUnsafe(H){const{endo:$}=t,P=this;if(!i.isValid(H))throw new Error("invalid scalar: out of range");if(H===Fi||P.is0())return v.ZERO;if(H===Qt)return P;if(V.hasCache(this))return this.multiply(H);if($){const{k1neg:D,k1:F,k2neg:x,k2:B}=O(H),{p1:q,p2:N}=Wx(v,P,F,B);return M($.beta,q,N,D,x)}else return V.unsafe(P,H)}multiplyAndAddUnsafe(H,$,P){const D=this.multiplyUnsafe($).add(H.multiplyUnsafe(P));return D.is0()?void 0:D}toAffine(H){return A(this,H)}isTorsionFree(){const{isTorsionFree:H}=t;return o===Qt?!0:H?H(v,this):V.unsafe(this,c).is0()}clearCofactor(){const{clearCofactor:H}=t;return o===Qt?this:H?H(v,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(H=!0){return Mo(H,"isCompressed"),this.assertValidity(),y(v,this,H)}toHex(H=!0){return rt(this.toBytes(H))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(H=!0){return this.toBytes(H)}_setWindowSize(H){this.precompute(H)}static normalizeZ(H){return _r(v,H)}static msm(H,$){return Pw(v,i,H,$)}static fromPrivateKey(H){return v.BASE.multiply(Ua(i,H))}}v.BASE=new v(s.Gx,s.Gy,r.ONE),v.ZERO=new v(r.ZERO,r.ONE,r.ZERO),v.Fp=r,v.Fn=i;const U=i.BITS,V=new kw(v,t.endo?Math.ceil(U/2):U);return v.BASE.precompute(8),v}function t3(e){return Uint8Array.of(e?2:3)}function n3(e,t){const n=e.ORDER;let r=Fi;for(let g=n-Qt;g%pr===Fi;g/=pr)r+=Qt;const i=r,s=pr<<i-Qt-Qt,o=s*pr,c=(n-Qt)/o,a=(c-Qt)/pr,u=o-Qt,f=s,l=e.pow(t,c),d=e.pow(t,(c+Qt)/pr);let y=(g,m)=>{let E=l,_=e.pow(m,u),S=e.sqr(_);S=e.mul(S,m);let w=e.mul(g,S);w=e.pow(w,a),w=e.mul(w,_),_=e.mul(w,m),S=e.mul(w,g);let T=e.mul(S,_);w=e.pow(T,f);let O=e.eql(w,e.ONE);_=e.mul(S,d),w=e.mul(T,E),S=e.cmov(_,S,O),T=e.cmov(w,T,O);for(let A=i;A>Qt;A--){let R=A-pr;R=pr<<R-Qt;let M=e.pow(T,R);const v=e.eql(M,e.ONE);_=e.mul(S,E),E=e.mul(E,E),M=e.mul(T,E),S=e.cmov(_,S,v),T=e.cmov(M,T,v)}return{isValid:O,value:S}};if(e.ORDER%ol===ys){const g=(e.ORDER-ys)/ol,m=e.sqrt(e.neg(t));y=(E,_)=>{let S=e.sqr(_);const w=e.mul(E,_);S=e.mul(S,w);let T=e.pow(S,g);T=e.mul(T,w);const O=e.mul(T,m),A=e.mul(e.sqr(T),_),R=e.eql(A,E);let M=e.cmov(O,T,R);return{isValid:R,value:M}}}return y}function Hw(e,t){vw(e);const{A:n,B:r,Z:i}=t;if(!e.isValid(n)||!e.isValid(r)||!e.isValid(i))throw new Error("mapToCurveSimpleSWU: invalid opts");const s=n3(e,i);if(!e.isOdd)throw new Error("Field does not have .isOdd()");return o=>{let c,a,u,f,l,d,y,g;c=e.sqr(o),c=e.mul(c,i),a=e.sqr(c),a=e.add(a,c),u=e.add(a,e.ONE),u=e.mul(u,r),f=e.cmov(i,e.neg(a),!e.eql(a,e.ZERO)),f=e.mul(f,n),a=e.sqr(u),d=e.sqr(f),l=e.mul(d,n),a=e.add(a,l),a=e.mul(a,u),d=e.mul(d,f),l=e.mul(d,r),a=e.add(a,l),y=e.mul(c,u);const{isValid:m,value:E}=s(a,d);g=e.mul(c,o),g=e.mul(g,E),y=e.cmov(y,u,m),g=e.cmov(g,E,m);const _=e.isOdd(o)===e.isOdd(g);g=e.cmov(e.neg(g),g,_);const S=es(e,[f],!0)[0];return y=e.mul(y,S),{x:y,y:g}}}function r3(e,t){return{secretKey:t.BYTES,publicKey:1+e.BYTES,publicKeyUncompressed:1+2*e.BYTES,publicKeyHasPrefix:!0,signature:2*t.BYTES}}function g0(e){const{CURVE:t,curveOpts:n}=i3(e),r=e3(t,n);return o3(e,r)}function i3(e){const t={a:e.a,b:e.b,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp;let r=e.allowedPrivateKeyLengths?Array.from(new Set(e.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=yi(t.n,{BITS:e.nBitLength,allowedLengths:r,modFromBytes:e.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:e.allowInfinityPoint,endo:e.endo,isTorsionFree:e.isTorsionFree,clearCofactor:e.clearCofactor,fromBytes:e.fromBytes,toBytes:e.toBytes};return{CURVE:t,curveOpts:s}}function s3(e,t,n){function r(i){const s=e.sqr(i),o=e.mul(s,i);return e.add(e.add(o,e.mul(i,t)),n)}return r}function o3(e,t){const{Fp:n,Fn:r}=t;function i(o){return mw(o,Qt,r.ORDER)}const s=s3(n,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:o=>Ua(r,o),weierstrassEquation:s,isWithinCurveOrder:i})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const c3=BigInt(0),Hc=BigInt(1),m0=BigInt(2),gs=BigInt(3);function a3(e){const t=[];for(;e>Hc;e>>=Hc)(e&Hc)===c3?t.unshift(0):(e&gs)===gs?(t.unshift(-1),e+=Hc):t.unshift(1);return t}function cf(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function u3(e,t,n,r){const{Fp2:i,Fp12:s}=e,{twistType:o,ateLoopSize:c,xNegative:a,postPrecompute:u}=r;let f;if(o==="multiplicative")f=(w,T,O,A,R,M)=>s.mul014(A,w,i.mul(T,R),i.mul(O,M));else if(o==="divisive")f=(w,T,O,A,R,M)=>s.mul034(A,i.mul(O,M),i.mul(T,R),w);else throw new Error("bls: unknown twist type");const l=i.div(i.ONE,i.mul(i.ONE,m0));function d(w,T,O,A){const R=i.sqr(O),M=i.sqr(A),v=i.mulByB(i.mul(M,gs)),U=i.mul(v,gs),V=i.sub(i.sub(i.sqr(i.add(O,A)),M),R),K=i.sub(v,R),H=i.mul(i.sqr(T),gs),$=i.neg(V);return w.push([K,H,$]),T=i.mul(i.mul(i.mul(i.sub(R,U),T),O),l),O=i.sub(i.sqr(i.mul(i.add(R,U),l)),i.mul(i.sqr(v),gs)),A=i.mul(R,V),{Rx:T,Ry:O,Rz:A}}function y(w,T,O,A,R,M){const v=i.sub(O,i.mul(M,A)),U=i.sub(T,i.mul(R,A)),V=i.sub(i.mul(v,R),i.mul(U,M)),K=i.neg(v),H=U;w.push([V,K,H]);const $=i.sqr(U),P=i.mul($,U),D=i.mul($,T),F=i.add(i.sub(P,i.mul(D,m0)),i.mul(i.sqr(v),A));return T=i.mul(U,F),O=i.sub(i.mul(i.sub(D,F),v),i.mul(P,O)),A=i.mul(A,P),{Rx:T,Ry:O,Rz:A}}const g=a3(c),m=Lo(w=>{const T=w,{x:O,y:A}=T.toAffine(),R=O,M=A,v=i.neg(A);let U=R,V=M,K=i.ONE;const H=[];for(const $ of g){const P=[];({Rx:U,Ry:V,Rz:K}=d(P,U,V,K)),$&&({Rx:U,Ry:V,Rz:K}=y(P,U,V,K,R,$===-1?v:M)),H.push(P)}if(u){const $=H[H.length-1];u(U,V,K,R,M,y.bind(null,$))}return H});function E(w,T=!1){let O=s.ONE;if(w.length){const A=w[0][0].length;for(let R=0;R<A;R++){O=s.sqr(O);for(const[M,v,U]of w)for(const[V,K,H]of M[R])O=f(V,K,H,O,v,U)}}return a&&(O=s.conjugate(O)),T?s.finalExponentiate(O):O}function _(w,T=!0){const O=[];_r(t,w.map(({g1:A})=>A)),_r(n,w.map(({g2:A})=>A));for(const{g1:A,g2:R}of w){if(A.is0()||R.is0())throw new Error("pairing is not available for ZERO point");A.assertValidity(),R.assertValidity();const M=A.toAffine();O.push([m(R),M.x,M.y])}return E(O,T)}function S(w,T,O=!0){return _([{g1:w,g2:T}],O)}return{Fp12:s,millerLoopBatch:E,pairing:S,pairingBatch:_,calcPairingPrecomputes:m}}function w0(e,t,n,r,i){const{Fp12:s,pairingBatch:o}=e;function c(l){return l instanceof t.Point?l:t.Point.fromHex(l)}function a(l){return l instanceof n.Point?l:n.Point.fromHex(l)}function u(l){if(!(l instanceof n.Point))throw new Error(`expected valid message hashed to ${i?"G1":"G2"} curve`);return l}const f=i?(l,d)=>({g1:d,g2:l}):(l,d)=>({g1:l,g2:d});return{getPublicKey(l){const d=Ua(t.Point.Fn,l);return t.Point.BASE.multiply(d)},sign(l,d,y){if(y!=null)throw new Error("sign() expects 2 arguments");const g=Ua(t.Point.Fn,d);return u(l).assertValidity(),l.multiply(g)},verify(l,d,y,g){if(g!=null)throw new Error("verify() expects 3 arguments");l=a(l),y=c(y);const m=y.negate(),E=t.Point.BASE,_=u(d),S=l,w=o([f(m,_),f(E,S)]);return s.eql(w,s.ONE)},verifyBatch(l,d,y){if(cf(d),y.length!==d.length)throw new Error("amount of public keys and messages should be equal");const g=a(l),m=d,E=y.map(c),_=new Map;for(let T=0;T<E.length;T++){const O=E[T],A=m[T];let R=_.get(A);R===void 0&&(R=[],_.set(A,R)),R.push(O)}const S=[],w=t.Point.BASE;try{for(const[T,O]of _){const A=O.reduce((R,M)=>R.add(M));S.push(f(A,T))}return S.push(f(w.negate(),g)),s.eql(o(S),s.ONE)}catch{return!1}},aggregatePublicKeys(l){cf(l),l=l.map(y=>c(y));const d=l.reduce((y,g)=>y.add(g),t.Point.ZERO);return d.assertValidity(),d},aggregateSignatures(l){cf(l),l=l.map(y=>a(y));const d=l.reduce((y,g)=>y.add(g),n.Point.ZERO);return d.assertValidity(),d},hash(l,d){On(l);const y=d?{DST:d}:void 0;return n.hashToCurve(l,y)},Signature:r}}function f3(e){const{Fp:t,Fr:n,Fp2:r,Fp6:i,Fp12:s}=e.fields,o=g0(e.G1),c=Object.assign(o,p0(o.Point,e.G1.mapToCurve,{...e.htfDefaults,...e.G1.htfDefaults})),a=g0(e.G2),u=Object.assign(a,p0(a.Point,e.G2.mapToCurve,{...e.htfDefaults,...e.G2.htfDefaults})),f=u3(e.fields,c.Point,u.Point,{...e.params,postPrecompute:e.postPrecompute}),{millerLoopBatch:l,pairing:d,pairingBatch:y,calcPairingPrecomputes:g}=f,m=w0(f,c,u,e.G2.Signature,!1),E=w0(f,u,c,e.G1.ShortSignature,!0),_=e.randomBytes||cg,S=()=>{const x=Ow(n.ORDER);return jx(_(x),n.ORDER)},w={randomSecretKey:S,randomPrivateKey:S,calcPairingPrecomputes:g},{ShortSignature:T}=e.G1,{Signature:O}=e.G2;function A(x,B){return x instanceof c.Point?x:E.hash(cn("point",x),B?.DST)}function R(x,B){return x instanceof u.Point?x:m.hash(cn("point",x),B?.DST)}function M(x){return m.getPublicKey(x).toBytes(!0)}function v(x){return E.getPublicKey(x).toBytes(!0)}function U(x,B,q){const N=R(x,q),L=m.sign(N,B);return x instanceof u.Point?L:O.toBytes(L)}function V(x,B,q){const N=A(x,q),L=E.sign(N,B);return x instanceof c.Point?L:T.toBytes(L)}function K(x,B,q,N){const L=R(B,N);return m.verify(x,L,q)}function H(x,B,q,N){const L=A(B,N);return E.verify(x,L,q)}function $(x){const B=m.aggregatePublicKeys(x);return x[0]instanceof c.Point?B:B.toBytes(!0)}function P(x){const B=m.aggregateSignatures(x);return x[0]instanceof u.Point?B:O.toBytes(B)}function D(x){const B=E.aggregateSignatures(x);return x[0]instanceof c.Point?B:T.toBytes(B)}function F(x,B,q,N){const L=B.map(G=>R(G,N));return m.verifyBatch(x,L,q)}return c.Point.BASE.precompute(4),{longSignatures:m,shortSignatures:E,millerLoopBatch:l,pairing:d,pairingBatch:y,verifyBatch:F,fields:{Fr:n,Fp:t,Fp2:r,Fp6:i,Fp12:s},params:{ateLoopSize:e.params.ateLoopSize,twistType:e.params.twistType,r:e.params.r,G1b:e.G1.b,G2b:e.G2.b},utils:w,getPublicKey:M,getPublicKeyForShortSignatures:v,sign:U,signShortSignature:V,verify:K,verifyShortSignature:H,aggregatePublicKeys:$,aggregateSignatures:P,aggregateShortSignatures:D,G1:c,G2:u,Signature:O,ShortSignature:T}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const b0=BigInt(0),Sr=BigInt(1),tn=BigInt(2),E0=BigInt(3);function ph(e,t,n,r,i=1,s){const o=BigInt(s===void 0?r:s),c=n**BigInt(r),a=[];for(let u=0;u<i;u++){const f=BigInt(u+1),l=[];for(let d=0,y=Sr;d<r;d++){const g=(f*y-f)/o%c;l.push(e.pow(t,g)),y*=n}a.push(l)}return a}function l3(e,t,n){const r=t.pow(n,(e.ORDER-Sr)/E0),i=t.pow(n,(e.ORDER-Sr)/tn);function s(d,y){const g=t.mul(t.frobeniusMap(d,1),r),m=t.mul(t.frobeniusMap(y,1),i);return[g,m]}const o=t.pow(n,(e.ORDER**tn-Sr)/E0),c=t.pow(n,(e.ORDER**tn-Sr)/tn);if(!t.eql(c,t.neg(t.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function a(d,y){return[t.mul(d,o),t.neg(y)]}const u=d=>(y,g)=>{const m=g.toAffine(),E=d(m.x,m.y);return y.fromAffine({x:E[0],y:E[1]})},f=u(s),l=u(a);return{psi:s,psi2:a,G2psi:f,G2psi2:l,PSI_X:r,PSI_Y:i,PSI2_X:o,PSI2_Y:c}}const _0=(e,t)=>{if(t.length!==2)throw new Error("invalid tuple");const n=t.map(r=>e.create(r));return{c0:n[0],c1:n[1]}};class h3{constructor(t,n={}){this.MASK=Sr;const r=t.ORDER,i=r*r;this.Fp=t,this.ORDER=i,this.BITS=Vo(i),this.BYTES=Math.ceil(Vo(i)/8),this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.Fp_NONRESIDUE=t.create(n.NONRESIDUE||BigInt(-1)),this.Fp_div2=t.div(t.ONE,tn),this.NONRESIDUE=_0(t,n.FP2_NONRESIDUE),this.FROBENIUS_COEFFICIENTS=ph(t,this.Fp_NONRESIDUE,t.ORDER,2)[0],this.mulByB=n.Fp2mulByB,Object.seal(this)}fromBigTuple(t){return _0(this.Fp,t)}create(t){return t}isValid({c0:t,c1:n}){function r(i,s){return typeof i=="bigint"&&b0<=i&&i<s}return r(t,this.ORDER)&&r(n,this.ORDER)}is0({c0:t,c1:n}){return this.Fp.is0(t)&&this.Fp.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}eql({c0:t,c1:n},{c0:r,c1:i}){return this.Fp.eql(t,r)&&this.Fp.eql(n,i)}neg({c0:t,c1:n}){return{c0:this.Fp.neg(t),c1:this.Fp.neg(n)}}pow(t,n){return yu(this,t,n)}invertBatch(t){return es(this,t)}add(t,n){const{c0:r,c1:i}=t,{c0:s,c1:o}=n;return{c0:this.Fp.add(r,s),c1:this.Fp.add(i,o)}}sub({c0:t,c1:n},{c0:r,c1:i}){return{c0:this.Fp.sub(t,r),c1:this.Fp.sub(n,i)}}mul({c0:t,c1:n},r){const{Fp:i}=this;if(typeof r=="bigint")return{c0:i.mul(t,r),c1:i.mul(n,r)};const{c0:s,c1:o}=r;let c=i.mul(t,s),a=i.mul(n,o);const u=i.sub(c,a),f=i.sub(i.mul(i.add(t,n),i.add(s,o)),i.add(c,a));return{c0:u,c1:f}}sqr({c0:t,c1:n}){const{Fp:r}=this,i=r.add(t,n),s=r.sub(t,n),o=r.add(t,t);return{c0:r.mul(i,s),c1:r.mul(o,n)}}addN(t,n){return this.add(t,n)}subN(t,n){return this.sub(t,n)}mulN(t,n){return this.mul(t,n)}sqrN(t){return this.sqr(t)}div(t,n){const{Fp:r}=this;return this.mul(t,typeof n=="bigint"?r.inv(r.create(n)):this.inv(n))}inv({c0:t,c1:n}){const{Fp:r}=this,i=r.inv(r.create(t*t+n*n));return{c0:r.mul(i,r.create(t)),c1:r.mul(i,r.create(-n))}}sqrt(t){const{Fp:n}=this,r=this,{c0:i,c1:s}=t;if(n.is0(s))return Pa(n,i)===1?r.create({c0:n.sqrt(i),c1:n.ZERO}):r.create({c0:n.ZERO,c1:n.sqrt(n.div(i,this.Fp_NONRESIDUE))});const o=n.sqrt(n.sub(n.sqr(i),n.mul(n.sqr(s),this.Fp_NONRESIDUE)));let c=n.mul(n.add(o,i),this.Fp_div2);Pa(n,c)===-1&&(c=n.sub(c,o));const u=n.sqrt(c),f=r.create({c0:u,c1:n.div(n.mul(s,this.Fp_div2),u)});if(!r.eql(r.sqr(f),t))throw new Error("Cannot find square root");const l=f,d=r.neg(l),{re:y,im:g}=r.reim(l),{re:m,im:E}=r.reim(d);return g>E||g===E&&y>m?l:d}isOdd(t){const{re:n,im:r}=this.reim(t),i=n%tn,s=n===b0,o=r%tn;return BigInt(i||s&&o)==Sr}fromBytes(t){const{Fp:n}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:n.fromBytes(t.subarray(0,n.BYTES)),c1:n.fromBytes(t.subarray(n.BYTES))}}toBytes({c0:t,c1:n}){return $e(this.Fp.toBytes(t),this.Fp.toBytes(n))}cmov({c0:t,c1:n},{c0:r,c1:i},s){return{c0:this.Fp.cmov(t,r,s),c1:this.Fp.cmov(n,i,s)}}reim({c0:t,c1:n}){return{re:t,im:n}}Fp4Square(t,n){const r=this,i=r.sqr(t),s=r.sqr(n);return{first:r.add(r.mulByNonresidue(s),i),second:r.sub(r.sub(r.sqr(r.add(t,n)),i),s)}}mulByNonresidue({c0:t,c1:n}){return this.mul({c0:t,c1:n},this.NONRESIDUE)}frobeniusMap({c0:t,c1:n},r){return{c0:t,c1:this.Fp.mul(n,this.FROBENIUS_COEFFICIENTS[r%2])}}}class d3{constructor(t){this.MASK=Sr,this.Fp2=t,this.ORDER=t.ORDER,this.BITS=3*t.BITS,this.BYTES=3*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO,c2:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO,c2:t.ZERO};const{Fp:n}=t,r=ph(t,t.NONRESIDUE,n.ORDER,6,2,3);this.FROBENIUS_COEFFICIENTS_1=r[0],this.FROBENIUS_COEFFICIENTS_2=r[1],Object.seal(this)}add({c0:t,c1:n,c2:r},{c0:i,c1:s,c2:o}){const{Fp2:c}=this;return{c0:c.add(t,i),c1:c.add(n,s),c2:c.add(r,o)}}sub({c0:t,c1:n,c2:r},{c0:i,c1:s,c2:o}){const{Fp2:c}=this;return{c0:c.sub(t,i),c1:c.sub(n,s),c2:c.sub(r,o)}}mul({c0:t,c1:n,c2:r},i){const{Fp2:s}=this;if(typeof i=="bigint")return{c0:s.mul(t,i),c1:s.mul(n,i),c2:s.mul(r,i)};const{c0:o,c1:c,c2:a}=i,u=s.mul(t,o),f=s.mul(n,c),l=s.mul(r,a);return{c0:s.add(u,s.mulByNonresidue(s.sub(s.mul(s.add(n,r),s.add(c,a)),s.add(f,l)))),c1:s.add(s.sub(s.mul(s.add(t,n),s.add(o,c)),s.add(u,f)),s.mulByNonresidue(l)),c2:s.sub(s.add(f,s.mul(s.add(t,r),s.add(o,a))),s.add(u,l))}}sqr({c0:t,c1:n,c2:r}){const{Fp2:i}=this;let s=i.sqr(t),o=i.mul(i.mul(t,n),tn),c=i.mul(i.mul(n,r),tn),a=i.sqr(r);return{c0:i.add(i.mulByNonresidue(c),s),c1:i.add(i.mulByNonresidue(a),o),c2:i.sub(i.sub(i.add(i.add(o,i.sqr(i.add(i.sub(t,n),r))),c),s),a)}}addN(t,n){return this.add(t,n)}subN(t,n){return this.sub(t,n)}mulN(t,n){return this.mul(t,n)}sqrN(t){return this.sqr(t)}create(t){return t}isValid({c0:t,c1:n,c2:r}){const{Fp2:i}=this;return i.isValid(t)&&i.isValid(n)&&i.isValid(r)}is0({c0:t,c1:n,c2:r}){const{Fp2:i}=this;return i.is0(t)&&i.is0(n)&&i.is0(r)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:n,c2:r}){const{Fp2:i}=this;return{c0:i.neg(t),c1:i.neg(n),c2:i.neg(r)}}eql({c0:t,c1:n,c2:r},{c0:i,c1:s,c2:o}){const{Fp2:c}=this;return c.eql(t,i)&&c.eql(n,s)&&c.eql(r,o)}sqrt(t){return ww()}div(t,n){const{Fp2:r}=this,{Fp:i}=r;return this.mul(t,typeof n=="bigint"?i.inv(i.create(n)):this.inv(n))}pow(t,n){return yu(this,t,n)}invertBatch(t){return es(this,t)}inv({c0:t,c1:n,c2:r}){const{Fp2:i}=this;let s=i.sub(i.sqr(t),i.mulByNonresidue(i.mul(r,n))),o=i.sub(i.mulByNonresidue(i.sqr(r)),i.mul(t,n)),c=i.sub(i.sqr(n),i.mul(t,r)),a=i.inv(i.add(i.mulByNonresidue(i.add(i.mul(r,o),i.mul(n,c))),i.mul(t,s)));return{c0:i.mul(a,s),c1:i.mul(a,o),c2:i.mul(a,c)}}fromBytes(t){const{Fp2:n}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);const r=n.BYTES;return{c0:n.fromBytes(t.subarray(0,r)),c1:n.fromBytes(t.subarray(r,r*2)),c2:n.fromBytes(t.subarray(2*r))}}toBytes({c0:t,c1:n,c2:r}){const{Fp2:i}=this;return $e(i.toBytes(t),i.toBytes(n),i.toBytes(r))}cmov({c0:t,c1:n,c2:r},{c0:i,c1:s,c2:o},c){const{Fp2:a}=this;return{c0:a.cmov(t,i,c),c1:a.cmov(n,s,c),c2:a.cmov(r,o,c)}}fromBigSix(t){const{Fp2:n}=this;if(!Array.isArray(t)||t.length!==6)throw new Error("invalid Fp6 usage");return{c0:n.fromBigTuple(t.slice(0,2)),c1:n.fromBigTuple(t.slice(2,4)),c2:n.fromBigTuple(t.slice(4,6))}}frobeniusMap({c0:t,c1:n,c2:r},i){const{Fp2:s}=this;return{c0:s.frobeniusMap(t,i),c1:s.mul(s.frobeniusMap(n,i),this.FROBENIUS_COEFFICIENTS_1[i%6]),c2:s.mul(s.frobeniusMap(r,i),this.FROBENIUS_COEFFICIENTS_2[i%6])}}mulByFp2({c0:t,c1:n,c2:r},i){const{Fp2:s}=this;return{c0:s.mul(t,i),c1:s.mul(n,i),c2:s.mul(r,i)}}mulByNonresidue({c0:t,c1:n,c2:r}){const{Fp2:i}=this;return{c0:i.mulByNonresidue(r),c1:t,c2:n}}mul1({c0:t,c1:n,c2:r},i){const{Fp2:s}=this;return{c0:s.mulByNonresidue(s.mul(r,i)),c1:s.mul(t,i),c2:s.mul(n,i)}}mul01({c0:t,c1:n,c2:r},i,s){const{Fp2:o}=this;let c=o.mul(t,i),a=o.mul(n,s);return{c0:o.add(o.mulByNonresidue(o.sub(o.mul(o.add(n,r),s),a)),c),c1:o.sub(o.sub(o.mul(o.add(i,s),o.add(t,n)),c),a),c2:o.add(o.sub(o.mul(o.add(t,r),i),c),a)}}}class p3{constructor(t,n){this.MASK=Sr;const{Fp2:r}=t,{Fp:i}=r;this.Fp6=t,this.ORDER=r.ORDER,this.BITS=2*t.BITS,this.BYTES=2*t.BYTES,this.isLE=t.isLE,this.ZERO={c0:t.ZERO,c1:t.ZERO},this.ONE={c0:t.ONE,c1:t.ZERO},this.FROBENIUS_COEFFICIENTS=ph(r,r.NONRESIDUE,i.ORDER,12,1,6)[0],this.X_LEN=n.X_LEN,this.finalExponentiate=n.Fp12finalExponentiate}create(t){return t}isValid({c0:t,c1:n}){const{Fp6:r}=this;return r.isValid(t)&&r.isValid(n)}is0({c0:t,c1:n}){const{Fp6:r}=this;return r.is0(t)&&r.is0(n)}isValidNot0(t){return!this.is0(t)&&this.isValid(t)}neg({c0:t,c1:n}){const{Fp6:r}=this;return{c0:r.neg(t),c1:r.neg(n)}}eql({c0:t,c1:n},{c0:r,c1:i}){const{Fp6:s}=this;return s.eql(t,r)&&s.eql(n,i)}sqrt(t){ww()}inv({c0:t,c1:n}){const{Fp6:r}=this;let i=r.inv(r.sub(r.sqr(t),r.mulByNonresidue(r.sqr(n))));return{c0:r.mul(t,i),c1:r.neg(r.mul(n,i))}}div(t,n){const{Fp6:r}=this,{Fp2:i}=r,{Fp:s}=i;return this.mul(t,typeof n=="bigint"?s.inv(s.create(n)):this.inv(n))}pow(t,n){return yu(this,t,n)}invertBatch(t){return es(this,t)}add({c0:t,c1:n},{c0:r,c1:i}){const{Fp6:s}=this;return{c0:s.add(t,r),c1:s.add(n,i)}}sub({c0:t,c1:n},{c0:r,c1:i}){const{Fp6:s}=this;return{c0:s.sub(t,r),c1:s.sub(n,i)}}mul({c0:t,c1:n},r){const{Fp6:i}=this;if(typeof r=="bigint")return{c0:i.mul(t,r),c1:i.mul(n,r)};let{c0:s,c1:o}=r,c=i.mul(t,s),a=i.mul(n,o);return{c0:i.add(c,i.mulByNonresidue(a)),c1:i.sub(i.mul(i.add(t,n),i.add(s,o)),i.add(c,a))}}sqr({c0:t,c1:n}){const{Fp6:r}=this;let i=r.mul(t,n);return{c0:r.sub(r.sub(r.mul(r.add(r.mulByNonresidue(n),t),r.add(t,n)),i),r.mulByNonresidue(i)),c1:r.add(i,i)}}addN(t,n){return this.add(t,n)}subN(t,n){return this.sub(t,n)}mulN(t,n){return this.mul(t,n)}sqrN(t){return this.sqr(t)}fromBytes(t){const{Fp6:n}=this;if(t.length!==this.BYTES)throw new Error("fromBytes invalid length="+t.length);return{c0:n.fromBytes(t.subarray(0,n.BYTES)),c1:n.fromBytes(t.subarray(n.BYTES))}}toBytes({c0:t,c1:n}){const{Fp6:r}=this;return $e(r.toBytes(t),r.toBytes(n))}cmov({c0:t,c1:n},{c0:r,c1:i},s){const{Fp6:o}=this;return{c0:o.cmov(t,r,s),c1:o.cmov(n,i,s)}}fromBigTwelve(t){const{Fp6:n}=this;return{c0:n.fromBigSix(t.slice(0,6)),c1:n.fromBigSix(t.slice(6,12))}}frobeniusMap(t,n){const{Fp6:r}=this,{Fp2:i}=r,{c0:s,c1:o,c2:c}=r.frobeniusMap(t.c1,n),a=this.FROBENIUS_COEFFICIENTS[n%12];return{c0:r.frobeniusMap(t.c0,n),c1:r.create({c0:i.mul(s,a),c1:i.mul(o,a),c2:i.mul(c,a)})}}mulByFp2({c0:t,c1:n},r){const{Fp6:i}=this;return{c0:i.mulByFp2(t,r),c1:i.mulByFp2(n,r)}}conjugate({c0:t,c1:n}){return{c0:t,c1:this.Fp6.neg(n)}}mul014({c0:t,c1:n},r,i,s){const{Fp6:o}=this,{Fp2:c}=o;let a=o.mul01(t,r,i),u=o.mul1(n,s);return{c0:o.add(o.mulByNonresidue(u),a),c1:o.sub(o.sub(o.mul01(o.add(n,t),r,c.add(i,s)),a),u)}}mul034({c0:t,c1:n},r,i,s){const{Fp6:o}=this,{Fp2:c}=o,a=o.create({c0:c.mul(t.c0,r),c1:c.mul(t.c1,r),c2:c.mul(t.c2,r)}),u=o.mul01(n,i,s),f=o.mul01(o.add(t,n),c.add(r,i),s);return{c0:o.add(o.mulByNonresidue(u),a),c1:o.sub(f,o.add(a,u))}}_cyclotomicSquare({c0:t,c1:n}){const{Fp6:r}=this,{Fp2:i}=r,{c0:s,c1:o,c2:c}=t,{c0:a,c1:u,c2:f}=n,{first:l,second:d}=i.Fp4Square(s,u),{first:y,second:g}=i.Fp4Square(a,c),{first:m,second:E}=i.Fp4Square(o,f),_=i.mulByNonresidue(E);return{c0:r.create({c0:i.add(i.mul(i.sub(l,s),tn),l),c1:i.add(i.mul(i.sub(y,o),tn),y),c2:i.add(i.mul(i.sub(m,c),tn),m)}),c1:r.create({c0:i.add(i.mul(i.add(_,a),tn),_),c1:i.add(i.mul(i.add(d,u),tn),d),c2:i.add(i.mul(i.add(g,f),tn),g)})}}_cyclotomicExp(t,n){let r=this.ONE;for(let i=this.X_LEN-1;i>=0;i--)r=this._cyclotomicSquare(r),Ux(n,i)&&(r=this.mul(r,t));return r}}function y3(e){const t=yi(e.ORDER),n=new h3(t,e),r=new d3(n),i=new p3(r,e);return{Fp:t,Fp2:n,Fp6:r,Fp12:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const jt=BigInt(0),Ca=BigInt(1),kn=BigInt(2),gu=BigInt(3),Do=BigInt(4),ri=BigInt("0xd201000000010000"),g3=Vo(ri),Wi={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:jt,b:Do,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},m3=yi(Wi.n,{modFromBytes:!0,isLE:!0}),{Fp:Ee,Fp2:Re,Fp6:w3,Fp12:Me}=y3({ORDER:Wi.p,X_LEN:g3,FP2_NONRESIDUE:[Ca,Ca],Fp2mulByB:({c0:e,c1:t})=>{const n=Ee.mul(e,Do),r=Ee.mul(t,Do);return{c0:Ee.sub(n,r),c1:Ee.add(n,r)}},Fp12finalExponentiate:e=>{const t=ri,n=Me.div(Me.frobeniusMap(e,6),e),r=Me.mul(Me.frobeniusMap(n,2),n),i=Me.conjugate(Me._cyclotomicExp(r,t)),s=Me.mul(Me.conjugate(Me._cyclotomicSquare(r)),i),o=Me.conjugate(Me._cyclotomicExp(s,t)),c=Me.conjugate(Me._cyclotomicExp(o,t)),a=Me.mul(Me.conjugate(Me._cyclotomicExp(c,t)),Me._cyclotomicSquare(i)),u=Me.conjugate(Me._cyclotomicExp(a,t)),f=Me.frobeniusMap(Me.mul(i,c),2),l=Me.frobeniusMap(Me.mul(o,r),3),d=Me.frobeniusMap(Me.mul(a,Me.conjugate(r)),1),y=Me.mul(Me.mul(u,Me.conjugate(s)),r);return Me.mul(Me.mul(Me.mul(f,l),d),y)}}),{G2psi:S0,G2psi2:b3}=l3(Ee,Re,Re.div(Re.ONE,Re.NONRESIDUE)),af=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:Ee.ORDER,m:2,k:128,expand:"xmd",hash:En}),yh={p:Re.ORDER,n:Wi.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:Re.ZERO,b:Re.fromBigTuple([Do,Do]),Gx:Re.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:Re.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},mu=wc(Ee.toBytes(jt),{infinity:!0,compressed:!0});function wu(e){e=e.slice();const t=e[0]&224,n=!!(t>>7&1),r=!!(t>>6&1),i=!!(t>>5&1);return e[0]&=31,{compressed:n,infinity:r,sort:i,value:e}}function wc(e,t){if(e[0]&224)throw new Error("setMask: non-empty mask");return t.compressed&&(e[0]|=128),t.infinity&&(e[0]|=64),t.sort&&(e[0]|=32),e}function E3(e,t,n){const{BYTES:r,ORDER:i}=Ee,s=t.is0(),{x:o,y:c}=t.toAffine();if(n){if(s)return mu.slice();const a=!!(c*kn/i);return wc(Ut(o,r),{compressed:!0,sort:a})}else return s?$e(Uint8Array.of(64),new Uint8Array(2*r-1)):$e(Ut(o,r),Ut(c,r))}function uf(e){e.assertValidity();const{BYTES:t,ORDER:n}=Ee,{x:r,y:i}=e.toAffine();if(e.is0())return mu.slice();const s=!!(i*kn/n);return wc(Ut(r,t),{compressed:!0,sort:s})}function _3(e){const{compressed:t,infinity:n,sort:r,value:i}=wu(e),{BYTES:s,ORDER:o}=Ee;if(i.length===48&&t){const c=rr(i),a=Ee.create(c&Qi(Ee.BITS));if(n){if(a!==jt)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:jt,y:jt}}const u=Ee.add(Ee.pow(a,gu),Ee.create(Wi.b));let f=Ee.sqrt(u);if(!f)throw new Error("invalid G1 point: compressed point");return f*kn/o!==BigInt(r)&&(f=Ee.neg(f)),{x:Ee.create(a),y:Ee.create(f)}}else if(i.length===96&&!t){const c=rr(i.subarray(0,s)),a=rr(i.subarray(s));if(n){if(c!==jt||a!==jt)throw new Error("G1: non-empty point at infinity");return bu.G1.Point.ZERO.toAffine()}return{x:Ee.create(c),y:Ee.create(a)}}else throw new Error("invalid G1 point: expected 48/96 bytes")}function T0(e){const{infinity:t,sort:n,value:r}=wu(cn("signatureHex",e,48)),i=Ee.ORDER,s=bu.G1.Point,o=rr(r);if(t)return s.ZERO;const c=Ee.create(o&Qi(Ee.BITS)),a=Ee.add(Ee.pow(c,gu),Ee.create(Wi.b));let u=Ee.sqrt(a);if(!u)throw new Error("invalid G1 point: compressed");const f=BigInt(n);u*kn/i!==f&&(u=Ee.neg(u));const l=s.fromAffine({x:c,y:u});return l.assertValidity(),l}function S3(e,t,n){const{BYTES:r,ORDER:i}=Ee,s=t.is0(),{x:o,y:c}=t.toAffine();if(n){if(s)return $e(mu,Ut(jt,r));const a=!!(c.c1===jt?c.c0*kn/i:c.c1*kn/i);return $e(wc(Ut(o.c1,r),{compressed:!0,sort:a}),Ut(o.c0,r))}else{if(s)return $e(Uint8Array.of(64),new Uint8Array(4*r-1));const{re:a,im:u}=Re.reim(o),{re:f,im:l}=Re.reim(c);return $e(Ut(u,r),Ut(a,r),Ut(l,r),Ut(f,r))}}function ff(e){e.assertValidity();const{BYTES:t}=Ee;if(e.is0())return $e(mu,Ut(jt,t));const{x:n,y:r}=e.toAffine(),{re:i,im:s}=Re.reim(n),{re:o,im:c}=Re.reim(r),u=!!((c>jt?c*kn:o*kn)/Ee.ORDER&Ca),f=i;return $e(wc(Ut(s,t),{sort:u,compressed:!0}),Ut(f,t))}function T3(e){const{BYTES:t,ORDER:n}=Ee,{compressed:r,infinity:i,sort:s,value:o}=wu(e);if(!r&&!i&&s||!r&&i&&s||s&&i&&r)throw new Error("invalid encoding flag: "+(e[0]&224));const c=(a,u,f)=>rr(a.slice(u,f));if(o.length===96&&r){if(i){if(o.reduce((g,m)=>g!==0?m+1:m,0)>0)throw new Error("invalid G2 point: compressed");return{x:Re.ZERO,y:Re.ZERO}}const a=c(o,0,t),u=c(o,t,2*t),f=Re.create({c0:Ee.create(u),c1:Ee.create(a)}),l=Re.add(Re.pow(f,gu),yh.b);let d=Re.sqrt(l);const y=d.c1===jt?d.c0*kn/n:d.c1*kn/n?Ca:jt;return d=s&&y>0?d:Re.neg(d),{x:f,y:d}}else if(o.length===192&&!r){if(i){if(o.reduce((d,y)=>d!==0?y+1:y,0)>0)throw new Error("invalid G2 point: uncompressed");return{x:Re.ZERO,y:Re.ZERO}}const a=c(o,0*t,1*t),u=c(o,1*t,2*t),f=c(o,2*t,3*t),l=c(o,3*t,4*t);return{x:Re.fromBigTuple([u,a]),y:Re.fromBigTuple([l,f])}}else throw new Error("invalid G2 point: expected 96/192 bytes")}function x0(e){const{ORDER:t}=Ee,{infinity:n,sort:r,value:i}=wu(cn("signatureHex",e)),s=bu.G2.Point,o=i.length/2;if(o!==48&&o!==96)throw new Error("invalid compressed signature length, expected 96/192 bytes");const c=rr(i.slice(0,o)),a=rr(i.slice(o));if(n)return s.ZERO;const u=Ee.create(c&Qi(Ee.BITS)),f=Ee.create(a),l=Re.create({c0:f,c1:u}),d=Re.add(Re.pow(l,gu),yh.b);let y=Re.sqrt(d);if(!y)throw new Error("Failed to find a square root");const{re:g,im:m}=Re.reim(y),E=BigInt(r),_=m>jt&&m*kn/t!==E,S=m===jt&&g*kn/t!==E;(_||S)&&(y=Re.neg(y));const w=s.fromAffine({x:l,y});return w.assertValidity(),w}const bu=f3({fields:{Fp:Ee,Fp2:Re,Fp6:w3,Fp12:Me,Fr:m3},G1:{...Wi,Fp:Ee,htfDefaults:{...af,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(e,t)=>{const n=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),r=new e(Ee.mul(t.X,n),t.Y,t.Z);return t.multiplyUnsafe(ri).negate().multiplyUnsafe(ri).equals(r)},clearCofactor:(e,t)=>t.multiplyUnsafe(ri).add(t),mapToCurve:O3,fromBytes:_3,toBytes:E3,ShortSignature:{fromBytes(e){return On(e),T0(e)},fromHex(e){return T0(e)},toBytes(e){return uf(e)},toRawBytes(e){return uf(e)},toHex(e){return rt(uf(e))}}},G2:{...yh,Fp:Re,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...af},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:B3,isTorsionFree:(e,t)=>t.multiplyUnsafe(ri).negate().equals(S0(e,t)),clearCofactor:(e,t)=>{const n=ri;let r=t.multiplyUnsafe(n).negate(),i=S0(e,t),s=t.double();return s=b3(e,s),s=s.subtract(i),i=r.add(i),i=i.multiplyUnsafe(n).negate(),s=s.add(i),s=s.subtract(r),s.subtract(t)},fromBytes:T3,toBytes:S3,Signature:{fromBytes(e){return On(e),x0(e)},fromHex(e){return x0(e)},toBytes(e){return ff(e)},toRawBytes(e){return ff(e)},toHex(e){return rt(ff(e))}}},params:{ateLoopSize:ri,r:Wi.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:af}),x3=Cw(Re,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(e=>e.map(t=>Re.fromBigTuple(t.map(BigInt))))),A3=Cw(Ee,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(e=>e.map(t=>BigInt(t)))),v3=Hw(Ee,{A:Ee.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:Ee.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:Ee.create(BigInt(11))}),I3=Hw(Re,{A:Re.create({c0:Ee.create(jt),c1:Ee.create(BigInt(240))}),B:Re.create({c0:Ee.create(BigInt(1012)),c1:Ee.create(BigInt(1012))}),Z:Re.create({c0:Ee.create(BigInt(-2)),c1:Ee.create(BigInt(-1))})});function O3(e){const{x:t,y:n}=v3(Ee.create(e[0]));return A3(t,n)}function B3(e){const{x:t,y:n}=I3(Re.fromBigTuple(e));return x3(t,n)}function N3(e,t,n){const r=typeof e=="string"?e:rt(e),i=typeof t=="string"?t:rt(t),s=typeof n=="string"?n:rt(n);return bu.verifyShortSignature(i,s,r)}const k3=BigInt(1e6),Fw=e=>Bt(new $s(e)),gh=e=>{const n=Fw(e)/k3;return new Date(Number(n))},A0=60*1e3,P3=60,R3=24,U3=R3*P3,C3=5,H3=5,F3=30*U3;var Ct;(function(e){e[e.Empty=0]="Empty",e[e.Fork=1]="Fork",e[e.Labeled=2]="Labeled",e[e.Leaf=3]="Leaf",e[e.Pruned=4]="Pruned"})(Ct||(Ct={}));function M3(e,t){for(let n=0;n<e.length;n++)if(e[n]>t[n])return!0;return!1}class Vi{#t=!1;#e=void 0;static async create(t){const n=Vi.createUnverified(t);return await n.verify(),n}static createUnverified(t){return new Vi(t.certificate,t.rootKey,t.canisterId,t.blsVerify??N3,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,n,r,i,s=C3,o=!1,c){this._rootKey=n,this._canisterId=r,this._blsVerify=i,this._maxAgeInMinutes=s,this.#t=o,this.cert=er(t),c&&"getTimeDiffMsecs"in c&&"hasSyncedTime"in c&&"syncTime"in c&&(this.#e=c)}lookup_path(t){return bc(t,this.cert.tree)}lookup_subtree(t){return mh(t,this.cert.tree)}async verify(){const t=await na(this.cert.tree),n=await this._checkDelegationAndGetKey(this.cert.delegation),r=this.cert.signature,i=V3(n),s=$e(bo("ic-state-root"),t),o=_n(this.lookup_path(["time"]));if(!o)throw yt.fromCode(new _s("Certificate does not contain a time"));if(!this.#t){const c=this.#e?.getTimeDiffMsecs()??0,a=this._maxAgeInMinutes*A0,u=new Date,f=u.getTime()+c,l=f-a,d=f+H3*A0,y=gh(o),g=y.getTime()<l,m=y.getTime()>d;if((g||m)&&this.#e&&!this.#e.hasSyncedTime())return await this.#e.syncTime(this._canisterId),await this.verify();if(g)throw An.fromCode(new Uo(this._maxAgeInMinutes,y,u,c,"past"));if(m)throw this.#e?.hasSyncedTime()?fn.fromCode(new Vn("System time has been synced with the IC network, but certificate is still too far in the future.")):An.fromCode(new Uo(5,y,u,c,"future"))}try{if(!await this._blsVerify(i,r,s))throw An.fromCode(new _s("Invalid signature"))}catch(c){throw An.fromCode(new _s("Signature verification failed",c))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;const n=Vi.createUnverified({certificate:t.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,disableTimeVerification:this.#t,maxAgeInMinutes:F3,agent:this.#e});if(n.cert.delegation)throw yt.fromCode(new Gl);await n.verify();const r=t.subnet_id,i=Ke.fromUint8Array(r);if(!qw({canisterId:this._canisterId,subnetId:i,tree:n.cert.tree}))throw An.fromCode(new uu(this._canisterId,i));const o=_n(n.lookup_path(["subnet",r,"public_key"]));if(!o)throw An.fromCode(new Wl(`Could not find subnet key for subnet ID ${i.toText()}`));return o}}const io=sc("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),q3=96;function V3(e){const t=io.byteLength+q3;if(e.byteLength!==t)throw yt.fromCode(new lu(t,e.byteLength));const n=e.slice(0,io.byteLength);if(!pu(n,io))throw yt.fromCode(new Xl(io,n));return e.slice(io.byteLength)}function _n(e){if(e.status===vn.Found&&e.value instanceof Uint8Array)return e.value}async function na(e){switch(e[0]){case Ct.Empty:return En(bo("ic-hashtree-empty"));case Ct.Pruned:return e[1];case Ct.Leaf:return En($e(bo("ic-hashtree-leaf"),e[1]));case Ct.Labeled:return En($e(bo("ic-hashtree-labeled"),e[1],await na(e[2])));case Ct.Fork:return En($e(bo("ic-hashtree-fork"),await na(e[1]),await na(e[2])));default:throw Ss}}function bo(e){const t=new Uint8Array([e.length]),n=new TextEncoder().encode(e);return $e(t,n)}function Mw(e){return typeof e[0]=="string"?dt(e[0]):e[0]}var vn;(function(e){e.Unknown="Unknown",e.Absent="Absent",e.Found="Found",e.Error="Error"})(vn||(vn={}));var vs;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found"})(vs||(vs={}));var ot;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found",e.Less="Less",e.Greater="Greater"})(ot||(ot={}));function bc(e,t){if(e.length===0)switch(t[0]){case Ct.Empty:return{status:vn.Absent};case Ct.Leaf:{if(!t[1])throw fn.fromCode(new yc("Invalid tree structure for leaf"));if(t[1]instanceof Uint8Array)return{status:vn.Found,value:t[1].slice(t[1].byteOffset,t[1].byteLength+t[1].byteOffset)};throw Ss}case Ct.Pruned:return{status:vn.Unknown};case Ct.Labeled:case Ct.Fork:return{status:vn.Error};default:throw Ss}const n=Mw(e),r=Ao(n,t);switch(r.status){case ot.Found:return bc(e.slice(1),r.value);case ot.Absent:case ot.Greater:case ot.Less:return{status:vn.Absent};case ot.Unknown:return{status:vn.Unknown};default:throw Ss}}function mh(e,t){if(e.length===0)return{status:vs.Found,value:t};const n=Mw(e),r=Ao(n,t);switch(r.status){case ot.Found:return mh(e.slice(1),r.value);case ot.Unknown:return{status:vs.Unknown};case ot.Absent:case ot.Greater:case ot.Less:return{status:vs.Absent};default:throw Ss}}function cl(e){switch(e[0]){case Ct.Empty:return[];case Ct.Fork:return cl(e[1]).concat(cl(e[2]));default:return[e]}}function Ao(e,t){switch(t[0]){case Ct.Labeled:return M3(e,t[1])?{status:ot.Greater}:pu(e,t[1])?{status:ot.Found,value:t[2]}:{status:ot.Less};case Ct.Fork:{const n=Ao(e,t[1]);switch(n.status){case ot.Greater:{const r=Ao(e,t[2]);return r.status===ot.Less?{status:ot.Absent}:r}case ot.Unknown:{const r=Ao(e,t[2]);return r.status===ot.Less?{status:ot.Unknown}:r}default:return n}}case Ct.Pruned:return{status:ot.Unknown};default:return{status:ot.Absent}}}function qw(e){const{canisterId:t,subnetId:n,tree:r}=e,i=bc(["subnet",n.toUint8Array(),"canister_ranges"],r);if(i.status!==vn.Found)throw yt.fromCode(new Cs(`Could not find canister ranges for subnet ${n.toText()}`,i.status));if(!(i.value instanceof Uint8Array))throw yt.fromCode(new fu(`Could not find canister ranges for subnet ${n.toText()}`));return er(i.value).map(a=>[Ke.fromUint8Array(a[0]),Ke.fromUint8Array(a[1])]).some(a=>a[0].ltEq(t)&&a[1].gtEq(t))}const v0=async e=>{const{agent:t,paths:n,disableCertificateTimeVerification:r=!1}=e,i=Ke.from(e.canisterId),s=[...new Set(n)],o=new Map,c=s.map((a,u)=>{const f=$3(a,i);return(async()=>{try{if(t.rootKey===null)throw un.fromCode(new Ks);const l=t.rootKey,d=await t.readState(i,{paths:[f]}),y=await Vi.create({certificate:d.certificate,rootKey:l,canisterId:i,disableTimeVerification:r,agent:t}),g=(_,S)=>{if(S==="subnet"){const w=L3(d.certificate,i,l);return{path:S,data:w}}else return{path:S,data:_n(_.lookup_path(f))}},{path:m,data:E}=g(y,s[u]);if(!E)console.warn(`Expected to find result for path ${m}, but instead found nothing.`),typeof m=="string"?o.set(m,null):o.set(m.key,null);else switch(m){case"time":{o.set(m,gh(E));break}case"controllers":{o.set(m,D3(E));break}case"module_hash":{o.set(m,rt(E));break}case"subnet":{o.set(m,E);break}case"candid":{o.set(m,new TextDecoder().decode(E));break}default:if(typeof m!="string"&&"key"in m&&"path"in m)switch(m.decodeStrategy){case"raw":o.set(m.key,E);break;case"leb128":{o.set(m.key,Fw(E));break}case"cbor":{o.set(m.key,er(E));break}case"hex":{o.set(m.key,rt(E));break}case"utf-8":o.set(m.key,new TextDecoder().decode(E))}}}catch(l){if(l instanceof wr&&(l.hasCode(_s)||l.hasCode(Uo)))throw l;typeof a!="string"&&"key"in a&&"path"in a?o.set(a.key,null):o.set(a,null),console.group(),console.warn(`Expected to find result for path ${a}, but instead found nothing.`),console.warn(l),console.groupEnd()}})()});return await Promise.all(c),o},L3=(e,t,n)=>{if(!t._isPrincipal)throw et.fromCode(new Vn("Invalid canisterId"));const r=er(e),i=r.tree;let s=r.delegation,o;if(s&&s.subnet_id?o=Ke.fromUint8Array(new Uint8Array(s.subnet_id)):!s&&typeof n<"u"?(o=Ke.selfAuthenticating(new Uint8Array(n)),s={subnet_id:o.toUint8Array(),certificate:new Uint8Array(0)}):(o=Ke.selfAuthenticating(Ke.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),s={subnet_id:o.toUint8Array(),certificate:new Uint8Array(0)}),!qw({canisterId:t,subnetId:o,tree:i}))throw An.fromCode(new uu(t,o));const a=mh(["subnet",s.subnet_id,"node"],i);if(a.status!==vs.Found)throw yt.fromCode(new Cs("Node not found",a.status));if(a.value instanceof Uint8Array)throw fn.fromCode(new yc("Invalid node tree"));const u=cl(a.value),f=new Map;return u.forEach(l=>{const d=Ke.from(l[1]).toText(),y=bc(["public_key"],l[2]);if(y.status!==vn.Found)throw yt.fromCode(new Cs("Public key not found",y.status));const g=y.value;if(g.byteLength!==44)throw yt.fromCode(new lu(44,g.byteLength));f.set(d,g)}),{subnetId:Ke.fromUint8Array(new Uint8Array(s.subnet_id)).toText(),nodeKeys:f}},$3=(e,t)=>{const n=t.toUint8Array();switch(e){case"time":return[dt("time")];case"controllers":return[dt("canister"),n,dt("controllers")];case"module_hash":return[dt("canister"),n,dt("module_hash")];case"subnet":return[dt("subnet")];case"candid":return[dt("canister"),n,dt("metadata"),dt("candid:service")];default:if("key"in e&&"path"in e)if(typeof e.path=="string"||e.path instanceof Uint8Array){const r=e.path,i=typeof r=="string"?dt(r):r;return[dt("canister"),n,dt("metadata"),i]}else return e.path}throw fn.fromCode(new Vn(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))},D3=e=>er(e).map(n=>Ke.fromUint8Array(n));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qr=BigInt(0),Ot=BigInt(1),lf=BigInt(2),j3=BigInt(8);function K3(e,t,n,r){const i=e.sqr(n),s=e.sqr(r),o=e.add(e.mul(t.a,i),s),c=e.add(e.ONE,e.mul(t.d,e.mul(i,s)));return e.eql(o,c)}function G3(e,t={}){const n=Rw("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o}=s;mc(t,{},{uvRatio:"function"});const c=lf<<BigInt(i.BYTES*8)-Ot,a=E=>r.create(E),u=t.uvRatio||((E,_)=>{try{return{isValid:!0,value:r.sqrt(r.div(E,_))}}catch{return{isValid:!1,value:qr}}});if(!K3(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(E,_,S=!1){const w=S?Ot:qr;return u0("coordinate "+E,_,w,c),_}function l(E){if(!(E instanceof g))throw new Error("ExtendedPoint expected")}const d=Lo((E,_)=>{const{X:S,Y:w,Z:T}=E,O=E.is0();_==null&&(_=O?j3:r.inv(T));const A=a(S*_),R=a(w*_),M=r.mul(T,_);if(O)return{x:qr,y:Ot};if(M!==Ot)throw new Error("invZ was invalid");return{x:A,y:R}}),y=Lo(E=>{const{a:_,d:S}=s;if(E.is0())throw new Error("bad point: ZERO");const{X:w,Y:T,Z:O,T:A}=E,R=a(w*w),M=a(T*T),v=a(O*O),U=a(v*v),V=a(R*_),K=a(v*a(V+M)),H=a(U+a(S*a(R*M)));if(K!==H)throw new Error("bad point: equation left != right (1)");const $=a(w*T),P=a(O*A);if($!==P)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(_,S,w,T){this.X=f("x",_),this.Y=f("y",S),this.Z=f("z",w,!0),this.T=f("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(_){if(_ instanceof g)throw new Error("extended point not allowed");const{x:S,y:w}=_||{};return f("x",S),f("y",w),new g(S,w,Ot,a(S*w))}static fromBytes(_,S=!1){const w=r.BYTES,{a:T,d:O}=s;_=a0(As(_,w,"point")),Mo(S,"zip215");const A=a0(_),R=_[w-1];A[w-1]=R&-129;const M=qo(A),v=S?c:r.ORDER;u0("point.y",M,qr,v);const U=a(M*M),V=a(U-Ot),K=a(O*U-T);let{isValid:H,value:$}=u(V,K);if(!H)throw new Error("bad point: invalid y coordinate");const P=($&Ot)===Ot,D=(R&128)!==0;if(!S&&$===qr&&D)throw new Error("bad point: x=0 and x_0=1");return D!==P&&($=a(-$)),g.fromAffine({x:$,y:M})}static fromHex(_,S=!1){return g.fromBytes(cn("point",_),S)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,S=!0){return m.createCache(this,_),S||this.multiply(lf),this}assertValidity(){y(this)}equals(_){l(_);const{X:S,Y:w,Z:T}=this,{X:O,Y:A,Z:R}=_,M=a(S*R),v=a(O*T),U=a(w*R),V=a(A*T);return M===v&&U===V}is0(){return this.equals(g.ZERO)}negate(){return new g(a(-this.X),this.Y,this.Z,a(-this.T))}double(){const{a:_}=s,{X:S,Y:w,Z:T}=this,O=a(S*S),A=a(w*w),R=a(lf*a(T*T)),M=a(_*O),v=S+w,U=a(a(v*v)-O-A),V=M+A,K=V-R,H=M-A,$=a(U*K),P=a(V*H),D=a(U*H),F=a(K*V);return new g($,P,F,D)}add(_){l(_);const{a:S,d:w}=s,{X:T,Y:O,Z:A,T:R}=this,{X:M,Y:v,Z:U,T:V}=_,K=a(T*M),H=a(O*v),$=a(R*w*V),P=a(A*U),D=a((T+O)*(M+v)-K-H),F=P-$,x=P+$,B=a(H-S*K),q=a(D*F),N=a(x*B),L=a(D*B),G=a(F*x);return new g(q,N,G,L)}subtract(_){return this.add(_.negate())}multiply(_){if(!i.isValidNot0(_))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:S,f:w}=m.cached(this,_,T=>_r(g,T));return _r(g,[S,w])[0]}multiplyUnsafe(_,S=g.ZERO){if(!i.isValid(_))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return _===qr?g.ZERO:this.is0()||_===Ot?this:m.unsafe(this,_,w=>_r(g,w),S)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(_){return d(this,_)}clearCofactor(){return o===Ot?this:this.multiplyUnsafe(o)}toBytes(){const{x:_,y:S}=this.toAffine(),w=r.toBytes(S);return w[w.length-1]|=_&Ot?128:0,w}toHex(){return rt(this.toBytes())}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get ex(){return this.X}get ey(){return this.Y}get ez(){return this.Z}get et(){return this.T}static normalizeZ(_){return _r(g,_)}static msm(_,S){return Pw(g,i,_,S)}_setWindowSize(_){this.precompute(_)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,Ot,a(s.Gx*s.Gy)),g.ZERO=new g(qr,Ot,Ot,qr),g.Fp=r,g.Fn=i;const m=new kw(g,i.BITS);return g.BASE.precompute(8),g}function W3(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');mc(n,{},{adjustScalarBytes:"function",randomBytes:"function",domain:"function",prehash:"function",mapToCurve:"function"});const{prehash:r}=n,{BASE:i,Fp:s,Fn:o}=e,c=n.randomBytes||cg,a=n.adjustScalarBytes||(v=>v),u=n.domain||((v,U,V)=>{if(Mo(V,"phflag"),U.length||V)throw new Error("Contexts/pre-hash are not supported");return v});function f(v){return o.create(qo(v))}function l(v){const U=w.secretKey;v=cn("private key",v,U);const V=cn("hashed private key",t(v),2*U),K=a(V.slice(0,U)),H=V.slice(U,2*U),$=f(K);return{head:K,prefix:H,scalar:$}}function d(v){const{head:U,prefix:V,scalar:K}=l(v),H=i.multiply(K),$=H.toBytes();return{head:U,prefix:V,scalar:K,point:H,pointBytes:$}}function y(v){return d(v).pointBytes}function g(v=Uint8Array.of(),...U){const V=$e(...U);return f(t(u(V,cn("context",v),!!r)))}function m(v,U,V={}){v=cn("message",v),r&&(v=r(v));const{prefix:K,scalar:H,pointBytes:$}=d(U),P=g(V.context,K,v),D=i.multiply(P).toBytes(),F=g(V.context,D,$,v),x=o.create(P+F*H);if(!o.isValid(x))throw new Error("sign failed: invalid s");const B=$e(D,o.toBytes(x));return As(B,w.signature,"result")}const E={zip215:!0};function _(v,U,V,K=E){const{context:H,zip215:$}=K,P=w.signature;v=cn("signature",v,P),U=cn("message",U),V=cn("publicKey",V,w.publicKey),$!==void 0&&Mo($,"zip215"),r&&(U=r(U));const D=P/2,F=v.subarray(0,D),x=qo(v.subarray(D,P));let B,q,N;try{B=e.fromBytes(V,$),q=e.fromBytes(F,$),N=i.multiplyUnsafe(x)}catch{return!1}if(!$&&B.isSmallOrder())return!1;const L=g(H,q.toBytes(),B.toBytes(),U);return q.add(B.multiplyUnsafe(L)).subtract(N).clearCofactor().is0()}const S=s.BYTES,w={secretKey:S,publicKey:S,signature:2*S,seed:S};function T(v=c(w.seed)){return As(v,w.seed,"seed")}function O(v){const U=M.randomSecretKey(v);return{secretKey:U,publicKey:y(U)}}function A(v){return ic(v)&&v.length===o.BYTES}function R(v,U){try{return!!e.fromBytes(v,U)}catch{return!1}}const M={getExtendedPublicKey:d,randomSecretKey:T,isValidSecretKey:A,isValidPublicKey:R,toMontgomery(v){const{y:U}=e.fromBytes(v),V=w.publicKey,K=V===32;if(!K&&V!==57)throw new Error("only defined for 25519 and 448");const H=K?s.div(Ot+U,Ot-U):s.div(U-Ot,U+Ot);return s.toBytes(H)},toMontgomerySecret(v){const U=w.secretKey;As(v,U);const V=t(v.subarray(0,U));return a(V).subarray(0,U)},randomPrivateKey:T,precompute(v=8,U=e.BASE){return U.precompute(v,!1)}};return Object.freeze({keygen:O,getPublicKey:y,sign:m,verify:_,utils:M,Point:e,lengths:w})}function X3(e){const t={a:e.a,d:e.d,p:e.Fp.ORDER,n:e.n,h:e.h,Gx:e.Gx,Gy:e.Gy},n=e.Fp,r=yi(t.n,e.nBitLength,!0),i={Fp:n,Fn:r,uvRatio:e.uvRatio},s={randomBytes:e.randomBytes,adjustScalarBytes:e.adjustScalarBytes,domain:e.domain,prehash:e.prehash,mapToCurve:e.mapToCurve};return{CURVE:t,curveOpts:i,hash:e.hash,eddsaOpts:s}}function z3(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function Y3(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:i}=X3(e),s=G3(t,n),o=W3(s,r,i);return z3(e,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Z3=BigInt(1),I0=BigInt(2);BigInt(3);const J3=BigInt(5),Q3=BigInt(8),wh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Vw={p:wh,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Q3,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function e8(e){const t=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=wh,c=e*e%s*e%s,a=Zn(c,I0,s)*c%s,u=Zn(a,Z3,s)*e%s,f=Zn(u,J3,s)*u%s,l=Zn(f,t,s)*f%s,d=Zn(l,n,s)*l%s,y=Zn(d,r,s)*d%s,g=Zn(y,i,s)*y%s,m=Zn(g,i,s)*y%s,E=Zn(m,t,s)*f%s;return{pow_p_5_8:Zn(E,I0,s)*e%s,b2:c}}function t8(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const O0=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function n8(e,t){const n=wh,r=mt(t*t*t,n),i=mt(r*r*t,n),s=e8(e*i).pow_p_5_8;let o=mt(e*r*s,n);const c=mt(t*o*o,n),a=o,u=mt(o*O0,n),f=c===e,l=c===mt(-e,n),d=c===mt(-e*O0,n);return f&&(o=a),(l||d)&&(o=u),Lx(o,n)&&(o=mt(-o,n)),{isValid:f||l,value:o}}const r8=yi(Vw.p,{isLE:!0}),i8={...Vw,Fp:r8,hash:n2,adjustScalarBytes:t8,uvRatio:n8},s8=Y3(i8);var B0,N0,Pt,Os;class o8{constructor(t={}){sn(this,Pt);sn(this,Os);this[B0]=this.entries.bind(this),this[N0]="ExpirableMap";const{source:n=[],expirationTime:r=600*1e3}=t,i=Date.now();zt(this,Pt,new Map([...n].map(([s,o])=>[s,{value:o,timestamp:i}]))),zt(this,Os,r)}prune(){const t=Date.now();for(const[n,r]of Fe(this,Pt).entries())t-r.timestamp>Fe(this,Os)&&Fe(this,Pt).delete(n);return this}set(t,n){this.prune();const r={value:n,timestamp:Date.now()};return Fe(this,Pt).set(t,r),this}get(t){const n=Fe(this,Pt).get(t);if(n!==void 0){if(Date.now()-n.timestamp>Fe(this,Os)){Fe(this,Pt).delete(t);return}return n.value}}clear(){Fe(this,Pt).clear()}entries(){const t=Fe(this,Pt).entries();return function*(){for(const[r,i]of t)yield[r,i.value]}()}values(){const t=Fe(this,Pt).values();return function*(){for(const r of t)yield r.value}()}keys(){return Fe(this,Pt).keys()}forEach(t,n){for(const[r,i]of Fe(this,Pt).entries())t.call(n,i.value,r,this)}has(t){return Fe(this,Pt).has(t)}delete(t){return Fe(this,Pt).delete(t)}get size(){return Fe(this,Pt).size}}Pt=new WeakMap,Os=new WeakMap,B0=Symbol.iterator,N0=Symbol.toStringTag;const k0=e=>{if(e<=127)return 1;if(e<=255)return 2;if(e<=65535)return 3;if(e<=16777215)return 4;throw et.fromCode(new hu("Length too long (> 4 bytes)"))},P0=(e,t,n)=>{if(n<=127)return e[t]=n,1;if(n<=255)return e[t]=129,e[t+1]=n,2;if(n<=65535)return e[t]=130,e[t+1]=n>>8,e[t+2]=n,3;if(n<=16777215)return e[t]=131,e[t+1]=n>>16,e[t+2]=n>>8,e[t+3]=n,4;throw et.fromCode(new hu("Length too long (> 4 bytes)"))},al=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw et.fromCode(new Nr("Invalid length 0"));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw et.fromCode(new Nr("Length too long (> 4 bytes)"))},c8=(e,t)=>{const n=al(e,t);if(n===1)return e[t];if(n===2)return e[t+1];if(n===3)return(e[t+1]<<8)+e[t+2];if(n===4)return(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];throw et.fromCode(new Nr("Length too long (> 4 bytes)"))};Uint8Array.from([48,12,6,10,43,6,1,4,1,131,184,67,1,1]);const R0=Uint8Array.from([48,5,6,3,43,101,112]);Uint8Array.from([48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10]);Uint8Array.from([48,29,6,13,43,6,1,4,1,130,220,124,5,3,1,2,1,6,12,43,6,1,4,1,130,220,124,5,3,2,1]);function a8(e,t){const n=2+k0(e.byteLength+1),r=t.byteLength+n+e.byteLength;let i=0;const s=new Uint8Array(1+k0(r)+r);return s[i++]=48,i+=P0(s,i,r),s.set(t,i),i+=t.byteLength,s[i++]=3,i+=P0(s,i,e.byteLength+1),s[i++]=0,s.set(new Uint8Array(e),i),s}const u8=(e,t)=>{let n=0;const r=(c,a)=>{if(i[n++]!==c)throw et.fromCode(new Nr(`Expected ${a} at offset ${n}`))},i=new Uint8Array(e);if(r(48,"sequence"),n+=al(i,n),!pu(i.slice(n,n+t.byteLength),t))throw et.fromCode(new Nr("Not the expected OID."));n+=t.byteLength,r(3,"bit string");const s=c8(i,n)-1;n+=al(i,n),r(0,"0 padding");const o=i.slice(n);if(s!==o.length)throw et.fromCode(new zl(s,o.length));return o};var Go,Wo;const Pi=class Pi{constructor(t){sn(this,Go);sn(this,Wo);if(t.byteLength!==Pi.RAW_KEY_LENGTH)throw et.fromCode(new Nr("An Ed25519 public key must be exactly 32 bytes long"));zt(this,Go,t),zt(this,Wo,Pi.derEncode(t))}static from(t){return this.fromDer(t.toDer())}static fromRaw(t){return new Pi(t)}static fromDer(t){return new Pi(this.derDecode(t))}static derEncode(t){return a8(t,R0)}static derDecode(t){const n=u8(t,R0);if(n.length!==this.RAW_KEY_LENGTH)throw et.fromCode(new Nr("An Ed25519 public key must be exactly 32 bytes long"));return n}get rawKey(){return Fe(this,Go)}get derKey(){return Fe(this,Wo)}toDer(){return this.derKey}toRaw(){return this.rawKey}};Go=new WeakMap,Wo=new WeakMap,Pi.RAW_KEY_LENGTH=32;let ul=Pi;class f8{constructor(){this.observers=[]}subscribe(t){this.observers.push(t)}unsubscribe(t){this.observers=this.observers.filter(n=>n!==t)}notify(t,...n){this.observers.forEach(r=>r(t,...n))}}class l8 extends f8{constructor(){super()}print(t,...n){this.notify({message:t,level:"info"},...n)}warn(t,...n){this.notify({message:t,level:"warn"},...n)}error(t,n,...r){this.notify({message:t,level:"error",error:n},...r)}}const U0=.5,C0=1.5,H0=500,F0=6e4,M0=9e5,q0=10;var Fn,Xo,zo,Yo,Zo,Jo,Qo,ec,Bs;const La=class La{constructor(t=La.default){sn(this,Fn);sn(this,Xo);sn(this,zo);sn(this,Yo);sn(this,Zo);sn(this,Jo);sn(this,Qo);sn(this,ec);sn(this,Bs,0);const{initialInterval:n=H0,randomizationFactor:r=U0,multiplier:i=C0,maxInterval:s=F0,maxElapsedTime:o=M0,maxIterations:c=q0,date:a=Date}=t;zt(this,Fn,n),zt(this,Xo,r),zt(this,zo,i),zt(this,Yo,s),zt(this,ec,a),zt(this,Zo,a.now()),zt(this,Jo,o),zt(this,Qo,c)}get ellapsedTimeInMsec(){return Fe(this,ec).now()-Fe(this,Zo)}get currentInterval(){return Fe(this,Fn)}get count(){return Fe(this,Bs)}get randomValueFromInterval(){const t=Fe(this,Xo)*Fe(this,Fn),n=Fe(this,Fn)-t,r=Fe(this,Fn)+t;return Math.random()*(r-n)+n}incrementCurrentInterval(){return zt(this,Fn,Math.min(Fe(this,Fn)*Fe(this,zo),Fe(this,Yo))),Mh(this,Bs)._++,Fe(this,Fn)}next(){return this.ellapsedTimeInMsec>=Fe(this,Jo)||Fe(this,Bs)>=Fe(this,Qo)?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};Fn=new WeakMap,Xo=new WeakMap,zo=new WeakMap,Yo=new WeakMap,Zo=new WeakMap,Jo=new WeakMap,Qo=new WeakMap,ec=new WeakMap,Bs=new WeakMap,La.default={initialInterval:H0,randomizationFactor:U0,multiplier:C0,maxInterval:F0,maxElapsedTime:M0,maxIterations:q0,date:Date};let fl=La;var mr;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(mr||(mr={}));const ll=60*1e3,h8=1e6,d8=0,p8="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae",y8="ic0.app",g8=".ic0.app",m8="icp0.io",w8=".icp0.io",b8="icp-api.io",E8=".icp-api.io",hf=200,_8=202,S8=404;function T8(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw un.fromCode(new xo("Fetch implementation was not available. You appear to be in a browser context, but window.fetch was not present."));else if(typeof globalThis<"u")if(globalThis.fetch)e=globalThis.fetch.bind(globalThis);else throw un.fromCode(new xo("Fetch implementation was not available. You appear to be in a Node.js context, but global.fetch was not available."));else typeof self<"u"&&self.fetch&&(e=self.fetch.bind(self));if(e)return e;throw un.fromCode(new xo("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function x8(e){let t;if(e!==void 0)!e.match(/^[a-z]+:/)&&typeof window<"u"?t=new URL(window.location.protocol+"//"+e):t=new URL(e);else{const n=["ic0.app","icp0.io","127.0.0.1","localhost"],r=[".github.dev",".gitpod.io"],i=typeof window<"u"?window.location:void 0,s=i?.hostname;let o;s&&typeof s=="string"&&(r.some(c=>s.endsWith(c))?o=s:o=n.find(c=>s.endsWith(c))),i&&o?t=new URL(`${i.protocol}//${o}${i.port?":"+i.port:""}`):t=new URL("https://icp-api.io")}return t.toString()}class Tr{#t;#e;#i;#g;#a;#w;#n;#s;#m;#b;#r;#c;#u;#o;get#T(){return this.#o*ll}#f;#l;#h;#d;constructor(t={}){this.#t=null,this.#e=!1,this.#i=d8,this.#g=!1,this.#a=null,this.#w=!1,this._isAgent=!0,this.config={},this.log=new l8,this.#f=[],this.#l=[],this.#h=new o8({expirationTime:5*ll}),this.#d=!0,this.#_=(i,s)=>{if(this.#d===!1)return i;const{status:o,signatures:c=[],requestId:a}=i;for(const u of c){const{timestamp:f,identity:l}=u,d=Ke.fromUint8Array(l).toText();let y;if(o===Us.Replied){const{reply:S}=i;y=Na({status:o,reply:S,timestamp:BigInt(f),request_id:a})}else if(o===Us.Rejected){const{reject_code:S,reject_message:w,error_code:T}=i;y=Na({status:o,reject_code:S,reject_message:w,error_code:T,timestamp:BigInt(f),request_id:a})}else throw fn.fromCode(new Vn(`Unknown status: ${o}`));const g=$e(nx,y),m=s.nodeKeys.get(d);if(!m)throw yt.fromCode(new oh);const E=ul.fromDer(m).rawKey;if(s8.verify(u.signature,g,E))return i;throw An.fromCode(new ch(d))}return i},this.config=t,this.#s=t.fetch||T8()||fetch.bind(globalThis),this.#m=t.fetchOptions,this.#b=t.callOptions,this.#e=t.shouldFetchRootKey??!1,this.#w=t.shouldSyncTime??!1,t.rootKey?this.rootKey=t.rootKey:this.#e?this.rootKey=null:this.rootKey=sc(p8);const n=x8(t.host);this.host=new URL(n),t.verifyQuerySignatures!==void 0&&(this.#d=t.verifyQuerySignatures),this.#c=t.retryTimes??3;const r=()=>new fl({maxIterations:this.#c});if(this.#u=t.backoffStrategy||r,this.host.hostname.endsWith(g8)?this.host.hostname=y8:this.host.hostname.endsWith(w8)?this.host.hostname=m8:this.host.hostname.endsWith(E8)&&(this.host.hostname=b8),t.credentials){const{name:i,password:s}=t.credentials;this.#r=`${i}${s?":"+s:""}`}if(this.#n=Promise.resolve(t.identity||new s0),t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes>5)throw et.fromCode(new ps("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw et.fromCode(new ps("Ingress expiry time must be greater than 0.",t.ingressExpiryInMinutes));this.#o=t.ingressExpiryInMinutes||5,this.addTransform("update",c0(sl)),t.useQueryNonces&&this.addTransform("query",c0(sl)),t.logToConsole&&this.log.subscribe(i=>{i.level==="error"?console.error(i.message):i.level==="warn"?console.warn(i.message):console.log(i.message)})}static createSync(t={}){return new this({...t})}static async create(t={}){const n=Tr.createSync(t);return await n.#y(),n}static async from(t){try{return"config"in t?await Tr.create(t.config):await Tr.create({fetch:t._fetch,fetchOptions:t._fetchOptions,callOptions:t._callOptions,host:t._host.toString(),identity:t._identity??void 0})}catch{throw et.fromCode(new rh)}}isLocal(){const t=this.host.hostname;return t==="127.0.0.1"||t.endsWith("127.0.0.1")}addTransform(t,n,r=n.priority||0){if(t==="update"){const i=this.#l.findIndex(s=>(s.priority||0)<r);this.#l.splice(i>=0?i:this.#l.length,0,Object.assign(n,{priority:r}))}else if(t==="query"){const i=this.#f.findIndex(s=>(s.priority||0)<r);this.#f.splice(i>=0?i:this.#f.length,0,Object.assign(n,{priority:r}))}}async getPrincipal(){if(!this.#n)throw un.fromCode(new ki);return(await this.#n).getPrincipal()}async call(t,n,r){const i=n.callSync??!0,s=await(r??this.#n);if(!s)throw un.fromCode(new ki);const o=Ke.from(t),c=n.effectiveCanisterId?Ke.from(n.effectiveCanisterId):o;await this.#y(c);const a=s.getPrincipal(),u=df(this.#o,this.#i),f={request_type:il.Call,canister_id:o,method_name:n.methodName,arg:n.arg,sender:a,ingress_expiry:u};let l=await this._transform({request:{body:null,method:"POST",headers:{"Content-Type":"application/cbor",...this.#r?{Authorization:"Basic "+btoa(this.#r)}:{}}},endpoint:Ui.Call,body:f}),d;n?.nonce?d=y(n.nonce):l.body.nonce?d=y(l.body.nonce):d=void 0,f.nonce=d;function y(_){return Object.assign(_,{__nonce__:void 0})}l=await s.transformRequest(l);const g=Qu(l.body),m=this.#u(),E=Zu(f);try{const w=i?()=>(this.log.print(`fetching "/api/v3/canister/${c.toText()}/call" with request:`,l),this.#s(""+new URL(`/api/v3/canister/${c.toText()}/call`,this.host),{...this.#b,...l.request,body:g})):()=>(this.log.print(`fetching "/api/v2/canister/${c.toText()}/call" with request:`,l),this.#s(""+new URL(`/api/v2/canister/${c.toText()}/call`,this.host),{...this.#b,...l.request,body:g})),{responseBodyBytes:T,...O}=await this.#p({requestFn:w,backoff:m,tries:0}),A=T.byteLength>0?er(T):null;return{requestId:E,response:{...O,body:A},requestDetails:f}}catch(_){let S;if(_ instanceof wr){if(_.hasCode(Aa))return this.log.warn("v3 api not supported. Fall back to v2"),this.call(t,{...n,callSync:!1},r);if(_.hasCode(ps)&&!this.#g)return await this.syncTime(o),this.call(o,n,r);_.code.requestContext={requestId:E,senderPubKey:l.body.sender_pubkey,senderSignature:l.body.sender_sig,ingressExpiry:l.body.content.ingress_expiry},S=_}else S=fn.fromCode(new Vn(_));throw this.log.error(`Error while making call: ${S.message}`,S),S}}async#E(t){const{ecid:n,transformedRequest:r,body:i,requestId:s,backoff:o,tries:c}=t,a=c===0?0:o.next();if(this.log.print(`fetching "/api/v2/canister/${n.toString()}/query" with tries:`,{tries:c,backoff:o,delay:a}),a===null)throw fn.fromCode(new Co(`Backoff strategy exhausted after ${c} attempts.`,s));a>0&&await new Promise(y=>setTimeout(y,a));let u;try{this.log.print(`fetching "/api/v2/canister/${n.toString()}/query" with request:`,r);const y=await this.#s(""+new URL(`/api/v2/canister/${n.toString()}/query`,this.host),{...this.#m,...r.request,body:i});if(y.status===hf)u={...er(Ba(await y.arrayBuffer())),httpDetails:{ok:y.ok,status:y.status,statusText:y.statusText,headers:ef(y.headers)},requestId:s};else throw yt.fromCode(new xa(y.status,y.statusText,ef(y.headers),await y.text()))}catch(y){if(c<this.#c)return this.log.warn(`Caught exception while attempting to make query:
67
67
  ${y}
68
68
  Retrying query.`),await this.#E({...t,tries:c+1});throw y instanceof wr?y:Ta.fromCode(new va(y))}if(!this.#d)return u;const f=u.signatures?.[0]?.timestamp;if(!f)throw yt.fromCode(new ih("Timestamp not found in query response. This suggests a malformed or malicious response."));const l=Number(BigInt(f)/BigInt(h8));if(Date.now()+this.#i-l>this.#T){if(c<this.#c)return this.log.warn("Timestamp is older than the max ingress expiry. Retrying query.",{requestId:s,signatureTimestampMs:l}),await this.#E({...t,tries:c+1});throw An.fromCode(new Jl(this.#o,s,c))}return u}async#p(t){const{requestFn:n,backoff:r,tries:i}=t,s=i===0?0:r.next();if(s===null)throw yt.fromCode(new Co(`Retry strategy exhausted after ${i} attempts.`));s>0&&await new Promise(f=>setTimeout(f,s));let o,c=new Uint8Array;try{o=await n(),o.status===hf&&(c=Ba(await o.clone().arrayBuffer()))}catch(f){if(i<this.#c)return this.log.warn(`Caught exception while attempting to make request:
69
69
  ${f}
70
- Retrying request.`),await this.#p({requestFn:n,backoff:r,tries:i+1});throw Ta.fromCode(new va(f))}const a=ef(o.headers);if(o.status===hf||o.status===_8)return{ok:o.ok,status:o.status,statusText:o.statusText,responseBodyBytes:c,headers:a};const u=await o.text();if(o.status===S8&&o.url.includes("api/v3"))throw yt.fromCode(new Aa);if(u.startsWith("Invalid request expiry: "))throw et.fromCode(new ps(u,this.#o));if(i<this.#c)return await this.#p({requestFn:n,backoff:r,tries:i+1});throw yt.fromCode(new xa(o.status,o.statusText,a,u))}async query(t,n,r){const i=this.#u(),s=n.effectiveCanisterId?Ke.from(n.effectiveCanisterId):Ke.from(t);await this.#y(s),this.log.print(`ecid ${s.toString()}`),this.log.print(`canisterId ${t.toString()}`);let o;const c=await(r??this.#n);if(!c)throw un.fromCode(new ki);const a=Ke.from(t),u=c.getPrincipal(),f=df(this.#o,this.#i),l={request_type:Fo.Query,canister_id:a,method_name:n.methodName,arg:n.arg,sender:u,ingress_expiry:f},d=Zu(l);o=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#r?{Authorization:"Basic "+btoa(this.#r)}:{}}},endpoint:Ui.Query,body:l}),o=await c.transformRequest(o);const y=Qu(o.body),g={canister:a.toText(),ecid:s,transformedRequest:o,body:y,requestId:d,backoff:i,tries:0},m=async()=>{const _=await this.#E(g);return{requestDetails:l,..._}},E=async()=>{const _=this.#h.get(s.toString());if(_)return _;await this.fetchSubnetKeys(s.toString());const S=this.#h.get(s.toString());if(!S)throw An.fromCode(new sh);return S};try{if(!this.#d)return await m();const[_,S]=await Promise.all([m(),E()]);try{return this.#_(_,S)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),this.#h.delete(s.toString());const w=await E();return this.#_(_,w)}}catch(_){let S;throw _ instanceof wr?(_.code.requestContext={requestId:d,senderPubKey:o.body.sender_pubkey,senderSignature:o.body.sender_sig,ingressExpiry:o.body.content.ingress_expiry},S=_):S=fn.fromCode(new Vn(_)),this.log.error(`Error while making query: ${S.message}`,S),S}}#_;async createReadStateRequest(t,n){await this.#y();const r=await(n??this.#n);if(!r)throw un.fromCode(new ki);const i=r.getPrincipal(),s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#r?{Authorization:"Basic "+btoa(this.#r)}:{}}},endpoint:Ui.ReadState,body:{request_type:Fo.ReadState,paths:t.paths,sender:i,ingress_expiry:df(this.#o,this.#i)}});return r.transformRequest(s)}async readState(t,n,r,i){await this.#S();const s=Ke.from(t);function o(f){for(const l of f.paths){const[d,y]=l,g=new TextEncoder().encode("request_status");if(pu(d,g))return y}}let c,a;if(i)c=i,a=Zu(c);else{a=o(n);const f=await this.#n;if(!f)throw un.fromCode(new ki);c=await this.createReadStateRequest(n,f)}this.log.print(`fetching "/api/v2/canister/${s}/read_state" with request:`,c);const u=this.#u();try{const{responseBodyBytes:f}=await this.#p({requestFn:()=>this.#s(""+new URL(`/api/v2/canister/${s.toString()}/read_state`,this.host),{...this.#m,...c.request,body:Qu(c.body)}),backoff:u,tries:0}),l=er(f);return this.log.print("Read state response:",l),l}catch(f){let l;throw f instanceof wr?(f.code.requestContext={requestId:a,senderPubKey:c.body.sender_pubkey,senderSignature:c.body.sender_sig,ingressExpiry:c.body.content.ingress_expiry},l=f):l=fn.fromCode(new Vn(f)),this.log.error(`Error while making read state: ${l.message}`,l),l}}parseTimeFromResponse(t){let n;if(t.certificate){const r=er(t.certificate);if(r&&"tree"in r)n=r.tree;else throw yt.fromCode(new yc("Could not decode time from response"));const i=bc(["time"],n);if(i.status!==vn.Found)throw yt.fromCode(new Cs("Time was not found in the response or was not in its expected format.",i.status));if(!(i.value instanceof Uint8Array)&&!ArrayBuffer.isView(i))throw yt.fromCode(new fu("Time was not in its expected format."));const s=gh(i.value);return this.log.print("Time from response:",s),this.log.print("Time from response in milliseconds:",s.getTime()),s.getTime()}else this.log.warn("No certificate found in response");return 0}async syncTime(t){this.#a=this.#a??(async()=>{await this.#S();const n=Date.now();try{t||this.log.print("Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai");const r=t??Ke.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),i=Tr.createSync({identity:new s0,host:this.host.toString(),fetch:this.#s,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),o=(await Promise.all(Array(3).fill(null).map(async()=>{const a=(await v0({canisterId:r,agent:i,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(a instanceof Date)return a.getTime()},[]))).reduce((c,a)=>typeof a=="number"&&a>c?a:c,0);o>0&&(this.#i=o-n,this.#g=!0,this.log.notify({message:`Syncing time: offset of ${this.#i}`,level:"info"}))}catch(r){const i=r instanceof wr?r:fn.fromCode(new Vn(r));throw this.log.error("Caught exception while attempting to sync time",i),i}})(),await this.#a.finally(()=>{this.#a=null})}async status(){const t=this.#r?{Authorization:"Basic "+btoa(this.#r)}:{};this.log.print('fetching "/api/v2/status"');const n=this.#u(),{responseBodyBytes:r}=await this.#p({backoff:n,requestFn:()=>this.#s(""+new URL("/api/v2/status",this.host),{headers:t,...this.#m}),tries:0});return er(r)}async fetchRootKey(){return this.#t=this.#t??(async()=>{const t=await this.status();return this.rootKey=t.root_key,this.rootKey})(),await this.#t.finally(()=>{this.#t=null})}async#y(t){await Promise.all([this.#S(),this.#x(t)])}async#S(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#e)await this.fetchRootKey();else throw un.fromCode(new Ks(this.#e))}async#x(t){this.#w&&!this.hasSyncedTime()&&await this.syncTime(t)}invalidateIdentity(){this.#n=null}replaceIdentity(t){this.#n=Promise.resolve(t)}async fetchSubnetKeys(t){const n=Ke.from(t);await this.#y(n);const i=(await v0({canisterId:n,paths:["subnet"],agent:this})).get("subnet");if(i&&typeof i=="object"&&"nodeKeys"in i)return this.#h.set(n.toText(),i),i}_transform(t){let n=Promise.resolve(t);if(t.endpoint===Ui.Call)for(const r of this.#l)n=n.then(i=>r(i).then(s=>s||i));else for(const r of this.#f)n=n.then(i=>r(i).then(s=>s||i));return n}getTimeDiffMsecs(){return this.#i}hasSyncedTime(){return this.#g}}function df(e,t){const n=e*ll;return xs.fromDeltaInMilliseconds(n,t)}const A8=300*1e3;function v8(){return k8(O8(I8(),1e3),N8(1e3,1.2),B8(A8))}function I8(){let e=!0;return async()=>e?(e=!1,!0):!1}function O8(e,t){return async(n,r,i)=>{if(await e(n,r,i))return new Promise(s=>setTimeout(s,t))}}function B8(e){const t=Date.now()+e;return async(n,r,i)=>{if(Date.now()>t)throw yt.fromCode(new Co(`Request timed out after ${e} msec`,r,i))}}function N8(e,t){let n=e;return()=>new Promise(r=>setTimeout(()=>{n*=t,r()},n))}function k8(...e){return async(t,n,r)=>{for(const i of e)await i(t,n,r)}}const P8={preSignReadStateRequest:!1};function Lw(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function pf(e,t){return e!==null&&typeof e=="object"&&Lw(e,t)}function R8(e,t){return Lw(e,t)&&typeof e[t]=="function"}function V0(e){return pf(e,"body")&&pf(e.body,"content")&&e.body.content.request_type===Fo.ReadState&&pf(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&R8(e.body.content.ingress_expiry,"toHash")}async function $w(e,t,n,r={}){const i=[dt("request_status"),n];let s,o;if(r.preSignReadStateRequest??!1?(o=await U8({paths:[i],agent:e,pollingOptions:r}),s=await e.readState(t,{paths:[i]},void 0,o)):s=await e.readState(t,{paths:[i]}),e.rootKey==null)throw un.fromCode(new Ks);const a=await Vi.create({certificate:s.certificate,rootKey:e.rootKey,canisterId:t,blsVerify:r.blsVerify,agent:e}),u=_n(a.lookup_path([...i,dt("status")]));let f;switch(typeof u>"u"?f=mr.Unknown:f=new TextDecoder().decode(u),f){case mr.Replied:return{reply:_n(a.lookup_path([...i,"reply"])),certificate:a};case mr.Received:case mr.Unknown:case mr.Processing:{const l=r.strategy??v8();return await l(t,n,f),$w(e,t,n,{...r,strategy:l,request:o})}case mr.Rejected:{const l=new Uint8Array(_n(a.lookup_path([...i,"reject_code"])))[0],d=new TextDecoder().decode(_n(a.lookup_path([...i,"reject_message"]))),y=_n(a.lookup_path([...i,"error_code"])),g=y?new TextDecoder().decode(y):void 0;throw Es.fromCode(new du(n,l,d,g))}case mr.Done:throw fn.fromCode(new th(n))}throw Ss}async function U8(e){const{paths:t,agent:n,pollingOptions:r}=e;if(r.request&&V0(r.request))return r.request;const i=await n.createReadStateRequest?.({paths:t},void 0);if(!V0(i))throw et.fromCode(new ah(i));return i}const xn=Symbol.for("ic-agent-metadata");class Ha{static agentOf(t){return t[xn].config.agent}static interfaceOf(t){return t[xn].service}static canisterIdOf(t){return Ke.from(t[xn].config.canisterId)}static createActorClass(t,n){const r=t({IDL:SS});class i extends Ha{constructor(o){if(!o.canisterId)throw et.fromCode(new Ia(o.canisterId));const c=typeof o.canisterId=="string"?Ke.fromText(o.canisterId):o.canisterId;super({config:{...Dw,...o,canisterId:c},service:r});for(const[a,u]of r._fields)n?.httpDetails&&u.annotations.push(hl),n?.certificate&&u.annotations.push(jw),this[a]=C8(this,a,u,o.blsVerify)}}return i}static createActor(t,n){if(!n.canisterId)throw et.fromCode(new Ia(n.canisterId));return new(this.createActorClass(t))(n)}static createActorWithHttpDetails(t,n){return new(this.createActorClass(t,{httpDetails:!0}))(n)}static createActorWithExtendedDetails(t,n,r={httpDetails:!0,certificate:!0}){return new(this.createActorClass(t,r))(n)}constructor(t){this[xn]=Object.freeze(t)}}function os(e,t){const n=cm(e,t);switch(n.length){case 0:return;case 1:return n[0];default:return n}}const Dw={pollingOptions:P8},hl="http-details",jw="certificate";function C8(e,t,n,r){let i;n.annotations.includes("query")||n.annotations.includes("composite_query")?i=async(o,...c)=>{o={...o,...e[xn].config.queryTransform?.(t,c,{...e[xn].config,...o})};const a=o.agent||e[xn].config.agent||new Tr,u=Ke.from(o.canisterId||e[xn].config.canisterId),f=Xf(n.argTypes,c),l=await a.query(u,{methodName:t,arg:f,effectiveCanisterId:o.effectiveCanisterId}),d={...l.httpDetails,requestDetails:l.requestDetails};switch(l.status){case Us.Rejected:{const y=new Ql(l.requestId,l.reject_code,l.reject_message,l.error_code,l.signatures);throw y.callContext={canisterId:u,methodName:t,httpDetails:d},Es.fromCode(y)}case Us.Replied:return n.annotations.includes(hl)?{httpDetails:d,result:os(n.retTypes,l.reply.arg)}:os(n.retTypes,l.reply.arg)}}:i=async(o,...c)=>{o={...o,...e[xn].config.callTransform?.(t,c,{...e[xn].config,...o})};const a=o.agent||e[xn].config.agent||Tr.createSync(),{canisterId:u,effectiveCanisterId:f,pollingOptions:l}={...Dw,...e[xn].config,...o},d=Ke.from(u),y=f!==void 0?Ke.from(f):d,g=Xf(n.argTypes,c),{requestId:m,response:E,requestDetails:_}=await a.call(d,{methodName:t,arg:g,effectiveCanisterId:y,nonce:o.nonce});let S,w;if(tx(E.body)){if(a.rootKey==null)throw un.fromCode(new Ks);const R=E.body.certificate;w=await Vi.create({certificate:R,rootKey:a.rootKey,canisterId:y,blsVerify:r,agent:a});const M=[dt("request_status"),m];switch(new TextDecoder().decode(_n(w.lookup_path([...M,"status"])))){case"replied":S=_n(w.lookup_path([...M,"reply"]));break;case"rejected":{const U=new Uint8Array(_n(w.lookup_path([...M,"reject_code"])))[0],V=new TextDecoder().decode(_n(w.lookup_path([...M,"reject_message"]))),K=_n(w.lookup_path([...M,"error_code"])),H=K?new TextDecoder().decode(K):void 0,$=new du(m,U,V,H);throw $.callContext={canisterId:d,methodName:t,httpDetails:E},Es.fromCode($)}}}else if(ex(E.body)){const{reject_code:R,reject_message:M,error_code:v}=E.body,U=new eh(m,R,M,v);throw U.callContext={canisterId:d,methodName:t,httpDetails:E},Es.fromCode(U)}if(E.status===202){const R={...l,blsVerify:r},M=await $w(a,y,m,R);w=M.certificate,S=M.reply}const T=n.annotations.includes(hl),O=n.annotations.includes(jw),A={...E,requestDetails:_};if(S!==void 0)return T&&O?{httpDetails:A,certificate:w,result:os(n.retTypes,S)}:O?{certificate:w,result:os(n.retTypes,S)}:T?{httpDetails:A,result:os(n.retTypes,S)}:os(n.retTypes,S);{const R=new Vn(`Call was returned undefined. We cannot determine if the call was successful or not. Return types: [${n.retTypes.map(M=>M.display()).join(",")}].`);throw R.callContext={canisterId:d,methodName:t,httpDetails:A},fn.fromCode(R)}};const s=(...o)=>i({},...o);return s.withOptions=o=>(...c)=>i(o,...c),s}const on={P2PKH:{P2PKH:null},P2SH_P2WPKH:{P2SH_P2WPKH:null},P2WPKH:{P2WPKH:null},P2WSH:{P2WSH:null},P2SH:{P2SH:null},P2TR:{P2TR:null},UNKNOWN:{UNKNOWN:null}};var Ei={},Xe={},yf={},Yt={},ar={},L0;function Wn(){return L0||(L0=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.testnet=ar.regtest=ar.bitcoin=void 0,ar.bitcoin={messagePrefix:`Bitcoin Signed Message:
70
+ Retrying request.`),await this.#p({requestFn:n,backoff:r,tries:i+1});throw Ta.fromCode(new va(f))}const a=ef(o.headers);if(o.status===hf||o.status===_8)return{ok:o.ok,status:o.status,statusText:o.statusText,responseBodyBytes:c,headers:a};const u=await o.text();if(o.status===S8&&o.url.includes("api/v3"))throw yt.fromCode(new Aa);if(u.startsWith("Invalid request expiry: "))throw et.fromCode(new ps(u,this.#o));if(i<this.#c)return await this.#p({requestFn:n,backoff:r,tries:i+1});throw yt.fromCode(new xa(o.status,o.statusText,a,u))}async query(t,n,r){const i=this.#u(),s=n.effectiveCanisterId?Ke.from(n.effectiveCanisterId):Ke.from(t);await this.#y(s),this.log.print(`ecid ${s.toString()}`),this.log.print(`canisterId ${t.toString()}`);let o;const c=await(r??this.#n);if(!c)throw un.fromCode(new ki);const a=Ke.from(t),u=c.getPrincipal(),f=df(this.#o,this.#i),l={request_type:Fo.Query,canister_id:a,method_name:n.methodName,arg:n.arg,sender:u,ingress_expiry:f},d=Zu(l);o=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#r?{Authorization:"Basic "+btoa(this.#r)}:{}}},endpoint:Ui.Query,body:l}),o=await c.transformRequest(o);const y=Qu(o.body),g={canister:a.toText(),ecid:s,transformedRequest:o,body:y,requestId:d,backoff:i,tries:0},m=async()=>{const _=await this.#E(g);return{requestDetails:l,..._}},E=async()=>{const _=this.#h.get(s.toString());if(_)return _;await this.fetchSubnetKeys(s.toString());const S=this.#h.get(s.toString());if(!S)throw An.fromCode(new sh);return S};try{if(!this.#d)return await m();const[_,S]=await Promise.all([m(),E()]);try{return this.#_(_,S)}catch{this.log.warn("Query response verification failed. Retrying with fresh subnet keys."),this.#h.delete(s.toString());const w=await E();return this.#_(_,w)}}catch(_){let S;throw _ instanceof wr?(_.code.requestContext={requestId:d,senderPubKey:o.body.sender_pubkey,senderSignature:o.body.sender_sig,ingressExpiry:o.body.content.ingress_expiry},S=_):S=fn.fromCode(new Vn(_)),this.log.error(`Error while making query: ${S.message}`,S),S}}#_;async createReadStateRequest(t,n){await this.#y();const r=await(n??this.#n);if(!r)throw un.fromCode(new ki);const i=r.getPrincipal(),s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#r?{Authorization:"Basic "+btoa(this.#r)}:{}}},endpoint:Ui.ReadState,body:{request_type:Fo.ReadState,paths:t.paths,sender:i,ingress_expiry:df(this.#o,this.#i)}});return r.transformRequest(s)}async readState(t,n,r,i){await this.#S();const s=Ke.from(t);function o(f){for(const l of f.paths){const[d,y]=l,g=new TextEncoder().encode("request_status");if(pu(d,g))return y}}let c,a;if(i)c=i,a=Zu(c);else{a=o(n);const f=await this.#n;if(!f)throw un.fromCode(new ki);c=await this.createReadStateRequest(n,f)}this.log.print(`fetching "/api/v2/canister/${s}/read_state" with request:`,c);const u=this.#u();try{const{responseBodyBytes:f}=await this.#p({requestFn:()=>this.#s(""+new URL(`/api/v2/canister/${s.toString()}/read_state`,this.host),{...this.#m,...c.request,body:Qu(c.body)}),backoff:u,tries:0}),l=er(f);return this.log.print("Read state response:",l),l}catch(f){let l;throw f instanceof wr?(f.code.requestContext={requestId:a,senderPubKey:c.body.sender_pubkey,senderSignature:c.body.sender_sig,ingressExpiry:c.body.content.ingress_expiry},l=f):l=fn.fromCode(new Vn(f)),this.log.error(`Error while making read state: ${l.message}`,l),l}}parseTimeFromResponse(t){let n;if(t.certificate){const r=er(t.certificate);if(r&&"tree"in r)n=r.tree;else throw yt.fromCode(new yc("Could not decode time from response"));const i=bc(["time"],n);if(i.status!==vn.Found)throw yt.fromCode(new Cs("Time was not found in the response or was not in its expected format.",i.status));if(!(i.value instanceof Uint8Array)&&!ArrayBuffer.isView(i))throw yt.fromCode(new fu("Time was not in its expected format."));const s=gh(i.value);return this.log.print("Time from response:",s),this.log.print("Time from response in milliseconds:",s.getTime()),s.getTime()}else this.log.warn("No certificate found in response");return 0}async syncTime(t){this.#a=this.#a??(async()=>{await this.#S();const n=Date.now();try{t||this.log.print("Syncing time with the IC. No canisterId provided, so falling back to ryjl3-tyaaa-aaaaa-aaaba-cai");const r=t??Ke.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),i=Tr.createSync({identity:new s0,host:this.host.toString(),fetch:this.#s,retryTimes:0,rootKey:this.rootKey??void 0,shouldSyncTime:!1}),o=(await Promise.all(Array(3).fill(null).map(async()=>{const a=(await v0({canisterId:r,agent:i,paths:["time"],disableCertificateTimeVerification:!0})).get("time");if(a instanceof Date)return a.getTime()},[]))).reduce((c,a)=>typeof a=="number"&&a>c?a:c,0);o>0&&(this.#i=o-n,this.#g=!0,this.log.notify({message:`Syncing time: offset of ${this.#i}`,level:"info"}))}catch(r){const i=r instanceof wr?r:fn.fromCode(new Vn(r));throw this.log.error("Caught exception while attempting to sync time",i),i}})(),await this.#a.finally(()=>{this.#a=null})}async status(){const t=this.#r?{Authorization:"Basic "+btoa(this.#r)}:{};this.log.print('fetching "/api/v2/status"');const n=this.#u(),{responseBodyBytes:r}=await this.#p({backoff:n,requestFn:()=>this.#s(""+new URL("/api/v2/status",this.host),{headers:t,...this.#m}),tries:0});return er(r)}async fetchRootKey(){return this.#t=this.#t??(async()=>{const t=await this.status();return this.rootKey=t.root_key,this.rootKey})(),await this.#t.finally(()=>{this.#t=null})}async#y(t){await Promise.all([this.#S(),this.#x(t)])}async#S(){if(!this.rootKey)if(this.rootKey===null&&this.host.toString()!=="https://icp-api.io"&&this.#e)await this.fetchRootKey();else throw un.fromCode(new Ks(this.#e))}async#x(t){this.#w&&!this.hasSyncedTime()&&await this.syncTime(t)}invalidateIdentity(){this.#n=null}replaceIdentity(t){this.#n=Promise.resolve(t)}async fetchSubnetKeys(t){const n=Ke.from(t);await this.#y(n);const i=(await v0({canisterId:n,paths:["subnet"],agent:this})).get("subnet");if(i&&typeof i=="object"&&"nodeKeys"in i)return this.#h.set(n.toText(),i),i}_transform(t){let n=Promise.resolve(t);if(t.endpoint===Ui.Call)for(const r of this.#l)n=n.then(i=>r(i).then(s=>s||i));else for(const r of this.#f)n=n.then(i=>r(i).then(s=>s||i));return n}getTimeDiffMsecs(){return this.#i}hasSyncedTime(){return this.#g}}function df(e,t){const n=e*ll;return xs.fromDeltaInMilliseconds(n,t)}const A8=300*1e3;function v8(){return k8(O8(I8(),1e3),N8(1e3,1.2),B8(A8))}function I8(){let e=!0;return async()=>e?(e=!1,!0):!1}function O8(e,t){return async(n,r,i)=>{if(await e(n,r,i))return new Promise(s=>setTimeout(s,t))}}function B8(e){const t=Date.now()+e;return async(n,r,i)=>{if(Date.now()>t)throw yt.fromCode(new Co(`Request timed out after ${e} msec`,r,i))}}function N8(e,t){let n=e;return()=>new Promise(r=>setTimeout(()=>{n*=t,r()},n))}function k8(...e){return async(t,n,r)=>{for(const i of e)await i(t,n,r)}}const P8={preSignReadStateRequest:!1};function Lw(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function pf(e,t){return e!==null&&typeof e=="object"&&Lw(e,t)}function R8(e,t){return Lw(e,t)&&typeof e[t]=="function"}function V0(e){return pf(e,"body")&&pf(e.body,"content")&&e.body.content.request_type===Fo.ReadState&&pf(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&R8(e.body.content.ingress_expiry,"toHash")}async function $w(e,t,n,r={}){const i=[dt("request_status"),n];let s,o;if(r.preSignReadStateRequest??!1?(o=await U8({paths:[i],agent:e,pollingOptions:r}),s=await e.readState(t,{paths:[i]},void 0,o)):s=await e.readState(t,{paths:[i]}),e.rootKey==null)throw un.fromCode(new Ks);const a=await Vi.create({certificate:s.certificate,rootKey:e.rootKey,canisterId:t,blsVerify:r.blsVerify,agent:e}),u=_n(a.lookup_path([...i,dt("status")]));let f;switch(typeof u>"u"?f=mr.Unknown:f=new TextDecoder().decode(u),f){case mr.Replied:return{reply:_n(a.lookup_path([...i,"reply"])),certificate:a};case mr.Received:case mr.Unknown:case mr.Processing:{const l=r.strategy??v8();return await l(t,n,f),$w(e,t,n,{...r,strategy:l,request:o})}case mr.Rejected:{const l=new Uint8Array(_n(a.lookup_path([...i,"reject_code"])))[0],d=new TextDecoder().decode(_n(a.lookup_path([...i,"reject_message"]))),y=_n(a.lookup_path([...i,"error_code"])),g=y?new TextDecoder().decode(y):void 0;throw Es.fromCode(new du(n,l,d,g))}case mr.Done:throw fn.fromCode(new th(n))}throw Ss}async function U8(e){const{paths:t,agent:n,pollingOptions:r}=e;if(r.request&&V0(r.request))return r.request;const i=await n.createReadStateRequest?.({paths:t},void 0);if(!V0(i))throw et.fromCode(new ah(i));return i}const xn=Symbol.for("ic-agent-metadata");class Ha{static agentOf(t){return t[xn].config.agent}static interfaceOf(t){return t[xn].service}static canisterIdOf(t){return Ke.from(t[xn].config.canisterId)}static createActorClass(t,n){const r=t({IDL:SS});class i extends Ha{constructor(o){if(!o.canisterId)throw et.fromCode(new Ia(o.canisterId));const c=typeof o.canisterId=="string"?Ke.fromText(o.canisterId):o.canisterId;super({config:{...Dw,...o,canisterId:c},service:r});for(const[a,u]of r._fields)n?.httpDetails&&u.annotations.push(hl),n?.certificate&&u.annotations.push(jw),this[a]=C8(this,a,u,o.blsVerify)}}return i}static createActor(t,n){if(!n.canisterId)throw et.fromCode(new Ia(n.canisterId));return new(this.createActorClass(t))(n)}static createActorWithHttpDetails(t,n){return new(this.createActorClass(t,{httpDetails:!0}))(n)}static createActorWithExtendedDetails(t,n,r={httpDetails:!0,certificate:!0}){return new(this.createActorClass(t,r))(n)}constructor(t){this[xn]=Object.freeze(t)}}function os(e,t){const n=cm(e,t);switch(n.length){case 0:return;case 1:return n[0];default:return n}}const Dw={pollingOptions:P8},hl="http-details",jw="certificate";function C8(e,t,n,r){let i;n.annotations.includes("query")||n.annotations.includes("composite_query")?i=async(o,...c)=>{o={...o,...e[xn].config.queryTransform?.(t,c,{...e[xn].config,...o})};const a=o.agent||e[xn].config.agent||new Tr,u=Ke.from(o.canisterId||e[xn].config.canisterId),f=Xf(n.argTypes,c),l=await a.query(u,{methodName:t,arg:f,effectiveCanisterId:o.effectiveCanisterId}),d={...l.httpDetails,requestDetails:l.requestDetails};switch(l.status){case Us.Rejected:{const y=new Ql(l.requestId,l.reject_code,l.reject_message,l.error_code,l.signatures);throw y.callContext={canisterId:u,methodName:t,httpDetails:d},Es.fromCode(y)}case Us.Replied:return n.annotations.includes(hl)?{httpDetails:d,result:os(n.retTypes,l.reply.arg)}:os(n.retTypes,l.reply.arg)}}:i=async(o,...c)=>{o={...o,...e[xn].config.callTransform?.(t,c,{...e[xn].config,...o})};const a=o.agent||e[xn].config.agent||Tr.createSync(),{canisterId:u,effectiveCanisterId:f,pollingOptions:l}={...Dw,...e[xn].config,...o},d=Ke.from(u),y=f!==void 0?Ke.from(f):d,g=Xf(n.argTypes,c),{requestId:m,response:E,requestDetails:_}=await a.call(d,{methodName:t,arg:g,effectiveCanisterId:y,nonce:o.nonce});let S,w;if(tx(E.body)){if(a.rootKey==null)throw un.fromCode(new Ks);const R=E.body.certificate;w=await Vi.create({certificate:R,rootKey:a.rootKey,canisterId:y,blsVerify:r,agent:a});const M=[dt("request_status"),m];switch(new TextDecoder().decode(_n(w.lookup_path([...M,"status"])))){case"replied":S=_n(w.lookup_path([...M,"reply"]));break;case"rejected":{const U=new Uint8Array(_n(w.lookup_path([...M,"reject_code"])))[0],V=new TextDecoder().decode(_n(w.lookup_path([...M,"reject_message"]))),K=_n(w.lookup_path([...M,"error_code"])),H=K?new TextDecoder().decode(K):void 0,$=new du(m,U,V,H);throw $.callContext={canisterId:d,methodName:t,httpDetails:E},Es.fromCode($)}}}else if(ex(E.body)){const{reject_code:R,reject_message:M,error_code:v}=E.body,U=new eh(m,R,M,v);throw U.callContext={canisterId:d,methodName:t,httpDetails:E},Es.fromCode(U)}if(E.status===202){const R={...l,blsVerify:r},M=await $w(a,y,m,R);w=M.certificate,S=M.reply}const T=n.annotations.includes(hl),O=n.annotations.includes(jw),A={...E,requestDetails:_};if(S!==void 0)return T&&O?{httpDetails:A,certificate:w,result:os(n.retTypes,S)}:O?{certificate:w,result:os(n.retTypes,S)}:T?{httpDetails:A,result:os(n.retTypes,S)}:os(n.retTypes,S);{const R=new Vn(`Call was returned undefined. We cannot determine if the call was successful or not. Return types: [${n.retTypes.map(M=>M.display()).join(",")}].`);throw R.callContext={canisterId:d,methodName:t,httpDetails:A},fn.fromCode(R)}};const s=(...o)=>i({},...o);return s.withOptions=o=>(...c)=>i(o,...c),s}const Jt={P2PKH:{P2PKH:null},P2SH_P2WPKH:{P2SH_P2WPKH:null},P2WPKH:{P2WPKH:null},P2WSH:{P2WSH:null},P2SH:{P2SH:null},P2TR:{P2TR:null},UNKNOWN:{UNKNOWN:null}};var Ei={},Xe={},yf={},Yt={},ar={},L0;function Wn(){return L0||(L0=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.testnet=ar.regtest=ar.bitcoin=void 0,ar.bitcoin={messagePrefix:`Bitcoin Signed Message:
71
71
  `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},ar.regtest={messagePrefix:`Bitcoin Signed Message:
72
72
  `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},ar.testnet={messagePrefix:`Bitcoin Signed Message:
73
- `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239}),ar}var gf={},so={},mf={},ur={},$0;function Kw(){if($0)return ur;$0=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.encode=ur.decode=ur.check=void 0;function e(r){if(r.length<8||r.length>72||r[0]!==48||r[1]!==r.length-2||r[2]!==2)return!1;const i=r[3];if(i===0||5+i>=r.length||r[4+i]!==2)return!1;const s=r[5+i];return!(s===0||6+i+s!==r.length||r[4]&128||i>1&&r[4]===0&&!(r[5]&128)||r[i+6]&128||s>1&&r[i+6]===0&&!(r[i+7]&128))}ur.check=e;function t(r){if(r.length<8)throw new Error("DER sequence length is too short");if(r.length>72)throw new Error("DER sequence length is too long");if(r[0]!==48)throw new Error("Expected DER sequence");if(r[1]!==r.length-2)throw new Error("DER sequence length is invalid");if(r[2]!==2)throw new Error("Expected DER integer");const i=r[3];if(i===0)throw new Error("R length is zero");if(5+i>=r.length)throw new Error("R length is too long");if(r[4+i]!==2)throw new Error("Expected DER integer (2)");const s=r[5+i];if(s===0)throw new Error("S length is zero");if(6+i+s!==r.length)throw new Error("S length is invalid");if(r[4]&128)throw new Error("R value is negative");if(i>1&&r[4]===0&&!(r[5]&128))throw new Error("R value excessively padded");if(r[i+6]&128)throw new Error("S value is negative");if(s>1&&r[i+6]===0&&!(r[i+7]&128))throw new Error("S value excessively padded");return{r:r.slice(4,4+i),s:r.slice(6+i)}}ur.decode=t;function n(r,i){const s=r.length,o=i.length;if(s===0)throw new Error("R length is zero");if(o===0)throw new Error("S length is zero");if(s>33)throw new Error("R length is too long");if(o>33)throw new Error("S length is too long");if(r[0]&128)throw new Error("R value is negative");if(i[0]&128)throw new Error("S value is negative");if(s>1&&r[0]===0&&!(r[1]&128))throw new Error("R value excessively padded");if(o>1&&i[0]===0&&!(i[1]&128))throw new Error("S value excessively padded");const c=Buffer.allocUnsafe(6+s+o);return c[0]=48,c[1]=c.length-2,c[2]=2,c[3]=r.length,r.copy(c,4),c[4+s]=2,c[5+s]=i.length,i.copy(c,6+s),c}return ur.encode=n,ur}var _i={},D0;function bh(){if(D0)return _i;D0=1,Object.defineProperty(_i,"__esModule",{value:!0}),_i.REVERSE_OPS=_i.OPS=void 0;const e={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};_i.OPS=e;const t={};_i.REVERSE_OPS=t;for(const n of Object.keys(e)){const r=e[n];t[r]=n}return _i}var fr={},j0;function H8(){if(j0)return fr;j0=1,Object.defineProperty(fr,"__esModule",{value:!0}),fr.decode=fr.encode=fr.encodingLength=void 0;const e=bh();function t(i){return i<e.OPS.OP_PUSHDATA1?1:i<=255?2:i<=65535?3:5}fr.encodingLength=t;function n(i,s,o){const c=t(s);return c===1?i.writeUInt8(s,o):c===2?(i.writeUInt8(e.OPS.OP_PUSHDATA1,o),i.writeUInt8(s,o+1)):c===3?(i.writeUInt8(e.OPS.OP_PUSHDATA2,o),i.writeUInt16LE(s,o+1)):(i.writeUInt8(e.OPS.OP_PUSHDATA4,o),i.writeUInt32LE(s,o+1)),c}fr.encode=n;function r(i,s){const o=i.readUInt8(s);let c,a;if(o<e.OPS.OP_PUSHDATA1)c=o,a=1;else if(o===e.OPS.OP_PUSHDATA1){if(s+2>i.length)return null;c=i.readUInt8(s+1),a=2}else if(o===e.OPS.OP_PUSHDATA2){if(s+3>i.length)return null;c=i.readUInt16LE(s+1),a=3}else{if(s+5>i.length)return null;if(o!==e.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");c=i.readUInt32LE(s+1),a=5}return{opcode:o,number:c,size:a}}return fr.decode=r,fr}var Si={},K0;function F8(){if(K0)return Si;K0=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.encode=Si.decode=void 0;function e(r,i,s){i=i||4,s=s===void 0?!0:s;const o=r.length;if(o===0)return 0;if(o>i)throw new TypeError("Script number overflow");if(s&&(r[o-1]&127)===0&&(o<=1||(r[o-2]&128)===0))throw new Error("Non-minimally encoded script number");if(o===5){const a=r.readUInt32LE(0),u=r.readUInt8(4);return u&128?-((u&-129)*4294967296+a):u*4294967296+a}let c=0;for(let a=0;a<o;++a)c|=r[a]<<8*a;return r[o-1]&128?-(c&~(128<<8*(o-1))):c}Si.decode=e;function t(r){return r>2147483647?5:r>8388607?4:r>32767?3:r>127?2:r>0?1:0}function n(r){let i=Math.abs(r);const s=t(i),o=Buffer.allocUnsafe(s),c=r<0;for(let a=0;a<s;++a)o.writeUInt8(i&255,a),i>>=8;return o[s-1]&128?o.writeUInt8(c?128:0,s-1):c&&(o[s-1]|=128),o}return Si.encode=n,Si}var Ti={},wf={},bf,G0;function Eh(){if(G0)return bf;G0=1;var e={Array:function(n){return n!=null&&n.constructor===Array},Boolean:function(n){return typeof n=="boolean"},Function:function(n){return typeof n=="function"},Nil:function(n){return n==null},Number:function(n){return typeof n=="number"},Object:function(n){return typeof n=="object"},String:function(n){return typeof n=="string"},"":function(){return!0}};e.Null=e.Nil;for(var t in e)e[t].toJSON=(function(n){return n}).bind(null,t);return bf=e,bf}var Ef,W0;function Gw(){if(W0)return Ef;W0=1;var e=Eh();function t(d){return d.name||d.toString().match(/function (.*?)\s*\(/)[1]}function n(d){return e.Nil(d)?"":t(d.constructor)}function r(d){return e.Function(d)?"":e.String(d)?JSON.stringify(d):d&&e.Object(d)?"":d}function i(d,y){Error.captureStackTrace&&Error.captureStackTrace(d,y)}function s(d){return e.Function(d)?d.toJSON?d.toJSON():t(d):e.Array(d)?"Array":d&&e.Object(d)?"Object":d!==void 0?d:""}function o(d,y,g){var m=r(y);return"Expected "+s(d)+", got"+(g!==""?" "+g:"")+(m!==""?" "+m:"")}function c(d,y,g){g=g||n(y),this.message=o(d,y,g),i(this,c),this.__type=d,this.__value=y,this.__valueTypeName=g}c.prototype=Object.create(Error.prototype),c.prototype.constructor=c;function a(d,y,g,m,E){var _='" of type ';return y==="key"&&(_='" with key type '),o('property "'+s(g)+_+s(d),m,E)}function u(d,y,g,m,E){d?(E=E||n(m),this.message=a(d,g,y,m,E)):this.message='Unexpected property "'+y+'"',i(this,c),this.__label=g,this.__property=y,this.__type=d,this.__value=m,this.__valueTypeName=E}u.prototype=Object.create(Error.prototype),u.prototype.constructor=c;function f(d,y){return new c(d,{},y)}function l(d,y,g){return d instanceof u?(y=y+"."+d.__property,d=new u(d.__type,y,d.__label,d.__value,d.__valueTypeName)):d instanceof c&&(d=new u(d.__type,y,g,d.__value,d.__valueTypeName)),i(d),d}return Ef={TfTypeError:c,TfPropertyTypeError:u,tfCustomError:f,tfSubError:l,tfJSON:s,getValueTypeName:n},Ef}var _f,X0;function M8(){if(X0)return _f;X0=1;var e=Eh(),t=Gw();function n(A){return Buffer.isBuffer(A)}function r(A){return typeof A=="string"&&/^([0-9a-f]{2})+$/i.test(A)}function i(A,R){var M=A.toJSON();function v(U){if(!A(U))return!1;if(U.length===R)return!0;throw t.tfCustomError(M+"(Length: "+R+")",M+"(Length: "+U.length+")")}return v.toJSON=function(){return M},v}var s=i.bind(null,e.Array),o=i.bind(null,n),c=i.bind(null,r),a=i.bind(null,e.String);function u(A,R,M){M=M||e.Number;function v(U,V){return M(U,V)&&U>A&&U<R}return v.toJSON=function(){return`${M.toJSON()} between [${A}, ${R}]`},v}var f=Math.pow(2,53)-1;function l(A){return typeof A=="number"&&isFinite(A)}function d(A){return A<<24>>24===A}function y(A){return A<<16>>16===A}function g(A){return(A|0)===A}function m(A){return typeof A=="number"&&A>=-f&&A<=f&&Math.floor(A)===A}function E(A){return(A&255)===A}function _(A){return(A&65535)===A}function S(A){return A>>>0===A}function w(A){return typeof A=="number"&&A>=0&&A<=f&&Math.floor(A)===A}var T={ArrayN:s,Buffer:n,BufferN:o,Finite:l,Hex:r,HexN:c,Int8:d,Int16:y,Int32:g,Int53:m,Range:u,StringN:a,UInt8:E,UInt16:_,UInt32:S,UInt53:w};for(var O in T)T[O].toJSON=(function(A){return A}).bind(null,O);return _f=T,_f}var Sf,z0;function q8(){if(z0)return Sf;z0=1;var e=Gw(),t=Eh(),n=e.tfJSON,r=e.TfTypeError,i=e.TfPropertyTypeError,s=e.tfSubError,o=e.getValueTypeName,c={arrayOf:function(y,g){y=a(y),g=g||{};function m(E,_){return!t.Array(E)||t.Nil(E)||g.minLength!==void 0&&E.length<g.minLength||g.maxLength!==void 0&&E.length>g.maxLength||g.length!==void 0&&E.length!==g.length?!1:E.every(function(S,w){try{return u(y,S,_)}catch(T){throw s(T,w)}})}return m.toJSON=function(){var E="["+n(y)+"]";return g.length!==void 0?E+="{"+g.length+"}":(g.minLength!==void 0||g.maxLength!==void 0)&&(E+="{"+(g.minLength===void 0?0:g.minLength)+","+(g.maxLength===void 0?1/0:g.maxLength)+"}"),E},m},maybe:function d(y){y=a(y);function g(m,E){return t.Nil(m)||y(m,E,d)}return g.toJSON=function(){return"?"+n(y)},g},map:function(y,g){y=a(y),g&&(g=a(g));function m(E,_){if(!t.Object(E)||t.Nil(E))return!1;for(var S in E){try{g&&u(g,S,_)}catch(T){throw s(T,S,"key")}try{var w=E[S];u(y,w,_)}catch(T){throw s(T,S)}}return!0}return g?m.toJSON=function(){return"{"+n(g)+": "+n(y)+"}"}:m.toJSON=function(){return"{"+n(y)+"}"},m},object:function(y){var g={};for(var m in y)g[m]=a(y[m]);function E(_,S){if(!t.Object(_)||t.Nil(_))return!1;var w;try{for(w in g){var T=g[w],O=_[w];u(T,O,S)}}catch(A){throw s(A,w)}if(S){for(w in _)if(!g[w])throw new i(void 0,w)}return!0}return E.toJSON=function(){return n(g)},E},anyOf:function(){var y=[].slice.call(arguments).map(a);function g(m,E){return y.some(function(_){try{return u(_,m,E)}catch{return!1}})}return g.toJSON=function(){return y.map(n).join("|")},g},allOf:function(){var y=[].slice.call(arguments).map(a);function g(m,E){return y.every(function(_){try{return u(_,m,E)}catch{return!1}})}return g.toJSON=function(){return y.map(n).join(" & ")},g},quacksLike:function(y){function g(m){return y===o(m)}return g.toJSON=function(){return y},g},tuple:function(){var y=[].slice.call(arguments).map(a);function g(m,E){return t.Nil(m)||t.Nil(m.length)||E&&m.length!==y.length?!1:y.every(function(_,S){try{return u(_,m[S],E)}catch(w){throw s(w,S)}})}return g.toJSON=function(){return"("+y.map(n).join(", ")+")"},g},value:function(y){function g(m){return m===y}return g.toJSON=function(){return y},g}};c.oneOf=c.anyOf;function a(d){if(t.String(d))return d[0]==="?"?c.maybe(d.slice(1)):t[d]||c.quacksLike(d);if(d&&t.Object(d)){if(t.Array(d)){if(d.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return c.arrayOf(d[0])}return c.object(d)}else if(t.Function(d))return d;return c.value(d)}function u(d,y,g,m){if(t.Function(d)){if(d(y,g))return!0;throw new r(m||d,y)}return u(a(d),y,g)}for(var f in t)u[f]=t[f];for(f in c)u[f]=c[f];var l=M8();for(f in l)u[f]=l[f];return u.compile=a,u.TfTypeError=r,u.TfPropertyTypeError=i,Sf=u,Sf}var Y0;function Xt(){return Y0||(Y0=1,(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=tc();e.typeforce=q8();const n=t.Buffer.alloc(32,0),r=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(f,l){return f.length!==l.length?!1:f.every((d,y)=>d.equals(l[y]))}e.stacksEqual=i;function s(f){if(!t.Buffer.isBuffer(f)||f.length<33)return!1;const l=f[0],d=f.slice(1,33);if(d.compare(n)===0||d.compare(r)>=0)return!1;if((l===2||l===3)&&f.length===33)return!0;const y=f.slice(33);return y.compare(n)===0||y.compare(r)>=0?!1:l===4&&f.length===65}e.isPoint=s;const o=21*1e14;function c(f){return e.typeforce.UInt53(f)&&f<=o}e.Satoshi=c,e.TAPLEAF_VERSION_MASK=254;function a(f){return!f||!("output"in f)||!t.Buffer.isBuffer(f.output)?!1:f.version!==void 0?(f.version&e.TAPLEAF_VERSION_MASK)===f.version:!0}e.isTapleaf=a;function u(f){return(0,e.Array)(f)?f.length!==2?!1:f.every(l=>u(l)):a(f)}e.isTaptree=u,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})(wf)),wf}var Z0;function V8(){if(Z0)return Ti;Z0=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.encode=Ti.decode=void 0;const e=Kw(),t=nn(),n=Xt(),{typeforce:r}=n,i=Buffer.alloc(1,0);function s(u){let f=0;for(;u[f]===0;)++f;return f===u.length?i:(u=u.slice(f),u[0]&128?Buffer.concat([i,u],1+u.length):u)}function o(u){u[0]===0&&(u=u.slice(1));const f=Buffer.alloc(32,0),l=Math.max(0,32-u.length);return u.copy(f,l),f}function c(u){const f=u.readUInt8(u.length-1);if(!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=e.decode(u.slice(0,-1)),d=o(l.r),y=o(l.s);return{signature:Buffer.concat([d,y],64),hashType:f}}Ti.decode=c;function a(u,f){if(r({signature:n.BufferN(64),hashType:n.UInt8},{signature:u,hashType:f}),!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=Buffer.allocUnsafe(1);l.writeUInt8(f,0);const d=s(u.slice(0,32)),y=s(u.slice(32,64));return Buffer.concat([e.encode(d,y),l])}return Ti.encode=a,Ti}var J0;function nn(){return J0||(J0=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=Kw(),n=bh();Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return n.OPS}});const r=H8(),i=F8(),s=V8(),o=Xt(),{typeforce:c}=o,a=n.OPS.OP_RESERVED;function u(v){return o.Number(v)&&(v===n.OPS.OP_0||v>=n.OPS.OP_1&&v<=n.OPS.OP_16||v===n.OPS.OP_1NEGATE)}function f(v){return o.Buffer(v)||u(v)}function l(v){return o.Array(v)&&v.every(f)}e.isPushOnly=l;function d(v){return v.length-v.filter(f).length}e.countNonPushOnlyOPs=d;function y(v){if(v.length===0)return n.OPS.OP_0;if(v.length===1){if(v[0]>=1&&v[0]<=16)return a+v[0];if(v[0]===129)return n.OPS.OP_1NEGATE}}function g(v){return Buffer.isBuffer(v)}function m(v){return o.Array(v)}function E(v){return Buffer.isBuffer(v)}function _(v){if(g(v))return v;c(o.Array,v);const U=v.reduce((H,$)=>E($)?$.length===1&&y($)!==void 0?H+1:H+r.encodingLength($.length)+$.length:H+1,0),V=Buffer.allocUnsafe(U);let K=0;if(v.forEach(H=>{if(E(H)){const $=y(H);if($!==void 0){V.writeUInt8($,K),K+=1;return}K+=r.encode(V,H.length,K),H.copy(V,K),K+=H.length}else V.writeUInt8(H,K),K+=1}),K!==V.length)throw new Error("Could not decode chunks");return V}e.compile=_;function S(v){if(m(v))return v;c(o.Buffer,v);const U=[];let V=0;for(;V<v.length;){const K=v[V];if(K>n.OPS.OP_0&&K<=n.OPS.OP_PUSHDATA4){const H=r.decode(v,V);if(H===null||(V+=H.size,V+H.number>v.length))return null;const $=v.slice(V,V+H.number);V+=H.number;const P=y($);P!==void 0?U.push(P):U.push($)}else U.push(K),V+=1}return U}e.decompile=S;function w(v){if(g(v)&&(v=S(v)),!v)throw new Error("Could not convert invalid chunks to ASM");return v.map(U=>{if(E(U)){const V=y(U);if(V===void 0)return U.toString("hex");U=V}return n.REVERSE_OPS[U]}).join(" ")}e.toASM=w;function T(v){return c(o.String,v),_(v.split(" ").map(U=>n.OPS[U]!==void 0?n.OPS[U]:(c(o.Hex,U),Buffer.from(U,"hex"))))}e.fromASM=T;function O(v){return v=S(v),c(l,v),v.map(U=>E(U)?U:U===n.OPS.OP_0?Buffer.allocUnsafe(0):i.encode(U-a))}e.toStack=O;function A(v){return o.isPoint(v)}e.isCanonicalPubKey=A;function R(v){const U=v&-129;return U>0&&U<4}e.isDefinedHashType=R;function M(v){return!Buffer.isBuffer(v)||!R(v[v.length-1])?!1:t.check(v.slice(0,-1))}e.isCanonicalScriptSignature=M,e.number=i,e.signature=s})(mf)),mf}var xi={},Q0;function gi(){if(Q0)return xi;Q0=1,Object.defineProperty(xi,"__esModule",{value:!0}),xi.value=xi.prop=void 0;function e(n,r,i){Object.defineProperty(n,r,{configurable:!0,enumerable:!0,get(){const s=i.call(this);return this[r]=s,s},set(s){Object.defineProperty(this,r,{configurable:!0,enumerable:!0,value:s,writable:!0})}})}xi.prop=e;function t(n){let r;return()=>(r!==void 0||(r=n()),r)}return xi.value=t,xi}var ep;function L8(){if(ep)return so;ep=1,Object.defineProperty(so,"__esModule",{value:!0}),so.p2data=void 0;const e=Wn(),t=nn(),n=Xt(),r=gi(),i=t.OPS;function s(o,c){if(!o.data&&!o.output)throw new TypeError("Not enough data");c=Object.assign({validate:!0},c||{}),(0,n.typeforce)({network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.Buffer),data:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))},o);const u={name:"embed",network:o.network||e.bitcoin};if(r.prop(u,"output",()=>{if(o.data)return t.compile([i.OP_RETURN].concat(o.data))}),r.prop(u,"data",()=>{if(o.output)return t.decompile(o.output).slice(1)}),c.validate&&o.output){const f=t.decompile(o.output);if(f[0]!==i.OP_RETURN)throw new TypeError("Output is invalid");if(!f.slice(1).every(n.typeforce.Buffer))throw new TypeError("Output is invalid");if(o.data&&!(0,n.stacksEqual)(o.data,u.data))throw new TypeError("Data mismatch")}return Object.assign(u,o)}return so.p2data=s,so}var oo={},tp;function $8(){if(tp)return oo;tp=1,Object.defineProperty(oo,"__esModule",{value:!0}),oo.p2ms=void 0;const e=Wn(),t=nn(),n=Xt(),r=gi(),i=t.OPS,s=i.OP_RESERVED;function o(c,a){if(!c.input&&!c.output&&!(c.pubkeys&&c.m!==void 0)&&!c.signatures)throw new TypeError("Not enough data");a=Object.assign({validate:!0},a||{});function u(m){return t.isCanonicalScriptSignature(m)||(a.allowIncomplete&&m===i.OP_0)!==void 0}(0,n.typeforce)({network:n.typeforce.maybe(n.typeforce.Object),m:n.typeforce.maybe(n.typeforce.Number),n:n.typeforce.maybe(n.typeforce.Number),output:n.typeforce.maybe(n.typeforce.Buffer),pubkeys:n.typeforce.maybe(n.typeforce.arrayOf(n.isPoint)),signatures:n.typeforce.maybe(n.typeforce.arrayOf(u)),input:n.typeforce.maybe(n.typeforce.Buffer)},c);const l={network:c.network||e.bitcoin};let d=[],y=!1;function g(m){y||(y=!0,d=t.decompile(m),l.m=d[0]-s,l.n=d[d.length-2]-s,l.pubkeys=d.slice(1,-2))}if(r.prop(l,"output",()=>{if(c.m&&l.n&&c.pubkeys)return t.compile([].concat(s+c.m,c.pubkeys,s+l.n,i.OP_CHECKMULTISIG))}),r.prop(l,"m",()=>{if(l.output)return g(l.output),l.m}),r.prop(l,"n",()=>{if(l.pubkeys)return l.pubkeys.length}),r.prop(l,"pubkeys",()=>{if(c.output)return g(c.output),l.pubkeys}),r.prop(l,"signatures",()=>{if(c.input)return t.decompile(c.input).slice(1)}),r.prop(l,"input",()=>{if(c.signatures)return t.compile([i.OP_0].concat(c.signatures))}),r.prop(l,"witness",()=>{if(l.input)return[]}),r.prop(l,"name",()=>{if(!(!l.m||!l.n))return`p2ms(${l.m} of ${l.n})`}),a.validate){if(c.output){if(g(c.output),!n.typeforce.Number(d[0]))throw new TypeError("Output is invalid");if(!n.typeforce.Number(d[d.length-2]))throw new TypeError("Output is invalid");if(d[d.length-1]!==i.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(l.m<=0||l.n>16||l.m>l.n||l.n!==d.length-3)throw new TypeError("Output is invalid");if(!l.pubkeys.every(m=>(0,n.isPoint)(m)))throw new TypeError("Output is invalid");if(c.m!==void 0&&c.m!==l.m)throw new TypeError("m mismatch");if(c.n!==void 0&&c.n!==l.n)throw new TypeError("n mismatch");if(c.pubkeys&&!(0,n.stacksEqual)(c.pubkeys,l.pubkeys))throw new TypeError("Pubkeys mismatch")}if(c.pubkeys){if(c.n!==void 0&&c.n!==c.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(l.n=c.pubkeys.length,l.n<l.m)throw new TypeError("Pubkey count cannot be less than m")}if(c.signatures){if(c.signatures.length<l.m)throw new TypeError("Not enough signatures provided");if(c.signatures.length>l.m)throw new TypeError("Too many signatures provided")}if(c.input){if(c.input[0]!==i.OP_0)throw new TypeError("Input is invalid");if(l.signatures.length===0||!l.signatures.every(u))throw new TypeError("Input has invalid signature(s)");if(c.signatures&&!(0,n.stacksEqual)(c.signatures,l.signatures))throw new TypeError("Signature mismatch");if(c.m!==void 0&&c.m!==c.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(l,c)}return oo.p2ms=o,oo}var co={},np;function D8(){if(np)return co;np=1,Object.defineProperty(co,"__esModule",{value:!0}),co.p2pk=void 0;const e=Wn(),t=nn(),n=Xt(),r=gi(),i=t.OPS;function s(o,c){if(!o.input&&!o.output&&!o.pubkey&&!o.input&&!o.signature)throw new TypeError("Not enough data");c=Object.assign({validate:!0},c||{}),(0,n.typeforce)({network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.Buffer),pubkey:n.typeforce.maybe(n.isPoint),signature:n.typeforce.maybe(t.isCanonicalScriptSignature),input:n.typeforce.maybe(n.typeforce.Buffer)},o);const a=r.value(()=>t.decompile(o.input)),f={name:"p2pk",network:o.network||e.bitcoin};if(r.prop(f,"output",()=>{if(o.pubkey)return t.compile([o.pubkey,i.OP_CHECKSIG])}),r.prop(f,"pubkey",()=>{if(o.output)return o.output.slice(1,-1)}),r.prop(f,"signature",()=>{if(o.input)return a()[0]}),r.prop(f,"input",()=>{if(o.signature)return t.compile([o.signature])}),r.prop(f,"witness",()=>{if(f.input)return[]}),c.validate){if(o.output){if(o.output[o.output.length-1]!==i.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,n.isPoint)(f.pubkey))throw new TypeError("Output pubkey is invalid");if(o.pubkey&&!o.pubkey.equals(f.pubkey))throw new TypeError("Pubkey mismatch")}if(o.signature&&o.input&&!o.input.equals(f.input))throw new TypeError("Signature mismatch");if(o.input){if(a().length!==1)throw new TypeError("Input is invalid");if(!t.isCanonicalScriptSignature(f.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(f,o)}return co.p2pk=s,co}var ao={},Tf={},Ai={},Zt={},rp;function Ww(){if(rp)return Zt;rp=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.ripemd160=Zt.RIPEMD160=Zt.md5=Zt.MD5=Zt.sha1=Zt.SHA1=void 0;const e=Ry(),t=ui(),n=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),r=new Uint32Array(80);class i extends e.HashMD{constructor(){super(64,20,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0}get(){const{A:v,B:U,C:V,D:K,E:H}=this;return[v,U,V,K,H]}set(v,U,V,K,H){this.A=v|0,this.B=U|0,this.C=V|0,this.D=K|0,this.E=H|0}process(v,U){for(let D=0;D<16;D++,U+=4)r[D]=v.getUint32(U,!1);for(let D=16;D<80;D++)r[D]=(0,t.rotl)(r[D-3]^r[D-8]^r[D-14]^r[D-16],1);let{A:V,B:K,C:H,D:$,E:P}=this;for(let D=0;D<80;D++){let F,x;D<20?(F=(0,e.Chi)(K,H,$),x=1518500249):D<40?(F=K^H^$,x=1859775393):D<60?(F=(0,e.Maj)(K,H,$),x=2400959708):(F=K^H^$,x=3395469782);const B=(0,t.rotl)(V,5)+F+P+x+r[D]|0;P=$,$=H,H=(0,t.rotl)(K,30),K=V,V=B}V=V+this.A|0,K=K+this.B|0,H=H+this.C|0,$=$+this.D|0,P=P+this.E|0,this.set(V,K,H,$,P)}roundClean(){(0,t.clean)(r)}destroy(){this.set(0,0,0,0,0),(0,t.clean)(this.buffer)}}Zt.SHA1=i,Zt.sha1=(0,t.createHasher)(()=>new i);const s=Math.pow(2,32),o=Array.from({length:64},(M,v)=>Math.floor(s*Math.abs(Math.sin(v+1)))),c=n.slice(0,4),a=new Uint32Array(16);class u extends e.HashMD{constructor(){super(64,16,8,!0),this.A=c[0]|0,this.B=c[1]|0,this.C=c[2]|0,this.D=c[3]|0}get(){const{A:v,B:U,C:V,D:K}=this;return[v,U,V,K]}set(v,U,V,K){this.A=v|0,this.B=U|0,this.C=V|0,this.D=K|0}process(v,U){for(let P=0;P<16;P++,U+=4)a[P]=v.getUint32(U,!0);let{A:V,B:K,C:H,D:$}=this;for(let P=0;P<64;P++){let D,F,x;P<16?(D=(0,e.Chi)(K,H,$),F=P,x=[7,12,17,22]):P<32?(D=(0,e.Chi)($,K,H),F=(5*P+1)%16,x=[5,9,14,20]):P<48?(D=K^H^$,F=(3*P+5)%16,x=[4,11,16,23]):(D=H^(K|~$),F=7*P%16,x=[6,10,15,21]),D=D+V+o[P]+a[F],V=$,$=H,H=K,K=K+(0,t.rotl)(D,x[P%4])}V=V+this.A|0,K=K+this.B|0,H=H+this.C|0,$=$+this.D|0,this.set(V,K,H,$)}roundClean(){(0,t.clean)(a)}destroy(){this.set(0,0,0,0),(0,t.clean)(this.buffer)}}Zt.MD5=u,Zt.md5=(0,t.createHasher)(()=>new u);const f=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),l=Uint8Array.from(new Array(16).fill(0).map((M,v)=>v)),d=l.map(M=>(9*M+5)%16),y=(()=>{const U=[[l],[d]];for(let V=0;V<4;V++)for(let K of U)K.push(K[V].map(H=>f[H]));return U})(),g=y[0],m=y[1],E=[[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(M=>Uint8Array.from(M)),_=g.map((M,v)=>M.map(U=>E[v][U])),S=m.map((M,v)=>M.map(U=>E[v][U])),w=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),T=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function O(M,v,U,V){return M===0?v^U^V:M===1?v&U|~v&V:M===2?(v|~U)^V:M===3?v&V|U&~V:v^(U|~V)}const A=new Uint32Array(16);class R extends e.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:v,h1:U,h2:V,h3:K,h4:H}=this;return[v,U,V,K,H]}set(v,U,V,K,H){this.h0=v|0,this.h1=U|0,this.h2=V|0,this.h3=K|0,this.h4=H|0}process(v,U){for(let N=0;N<16;N++,U+=4)A[N]=v.getUint32(U,!0);let V=this.h0|0,K=V,H=this.h1|0,$=H,P=this.h2|0,D=P,F=this.h3|0,x=F,B=this.h4|0,q=B;for(let N=0;N<5;N++){const L=4-N,G=w[N],X=T[N],Y=g[N],ce=m[N],ue=_[N],te=S[N];for(let Z=0;Z<16;Z++){const ae=(0,t.rotl)(V+O(N,H,P,F)+A[Y[Z]]+G,ue[Z])+B|0;V=B,B=F,F=(0,t.rotl)(P,10)|0,P=H,H=ae}for(let Z=0;Z<16;Z++){const ae=(0,t.rotl)(K+O(L,$,D,x)+A[ce[Z]]+X,te[Z])+q|0;K=q,q=x,x=(0,t.rotl)(D,10)|0,D=$,$=ae}}this.set(this.h1+P+x|0,this.h2+F+q|0,this.h3+B+K|0,this.h4+V+$|0,this.h0+H+D|0)}roundClean(){(0,t.clean)(A)}destroy(){this.destroyed=!0,(0,t.clean)(this.buffer),this.set(0,0,0,0,0)}}return Zt.RIPEMD160=R,Zt.ripemd160=(0,t.createHasher)(()=>new R),Zt}var ip;function j8(){if(ip)return Ai;ip=1,Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.ripemd160=Ai.RIPEMD160=void 0;const e=Ww();return Ai.RIPEMD160=e.RIPEMD160,Ai.ripemd160=e.ripemd160,Ai}var vi={},sp;function K8(){if(sp)return vi;sp=1,Object.defineProperty(vi,"__esModule",{value:!0}),vi.sha1=vi.SHA1=void 0;const e=Ww();return vi.SHA1=e.SHA1,vi.sha1=e.sha1,vi}var Un={},op;function Xw(){if(op)return Un;op=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.sha224=Un.SHA224=Un.sha256=Un.SHA256=void 0;const e=Uy();return Un.SHA256=e.SHA256,Un.sha256=e.sha256,Un.SHA224=e.SHA224,Un.sha224=e.sha224,Un}var cp;function Pr(){return cp||(cp=1,(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=j8(),n=K8(),r=Xw();function i(f){return Buffer.from((0,t.ripemd160)(Uint8Array.from(f)))}e.ripemd160=i;function s(f){return Buffer.from((0,n.sha1)(Uint8Array.from(f)))}e.sha1=s;function o(f){return Buffer.from((0,r.sha256)(Uint8Array.from(f)))}e.sha256=o;function c(f){return Buffer.from((0,t.ripemd160)((0,r.sha256)(Uint8Array.from(f))))}e.hash160=c;function a(f){return Buffer.from((0,r.sha256)((0,r.sha256)(Uint8Array.from(f))))}e.hash256=a,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 u(f,l){return o(Buffer.concat([e.TAGGED_HASH_PREFIXES[f],l]))}e.taggedHash=u})(Tf)),Tf}var xf,ap;function G8(){if(ap)return xf;ap=1;function e(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),f=Math.log(256)/Math.log(c);function l(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,E=0,_=0,S=g.length;_!==S&&g[_]===0;)_++,m++;for(var w=(S-_)*f+1>>>0,T=new Uint8Array(w);_!==S;){for(var O=g[_],A=0,R=w-1;(O!==0||A<E)&&R!==-1;R--,A++)O+=256*T[R]>>>0,T[R]=O%c>>>0,O=O/c>>>0;if(O!==0)throw new Error("Non-zero carry");E=A,_++}for(var M=w-E;M!==w&&T[M]===0;)M++;for(var v=a.repeat(m);M<w;++M)v+=t.charAt(T[M]);return v}function d(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;for(var m=0,E=0,_=0;g[m]===a;)E++,m++;for(var S=(g.length-m)*u+1>>>0,w=new Uint8Array(S);g[m];){var T=g.charCodeAt(m);if(T>255)return;var O=n[T];if(O===255)return;for(var A=0,R=S-1;(O!==0||A<_)&&R!==-1;R--,A++)O+=c*w[R]>>>0,w[R]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");_=A,m++}for(var M=S-_;M!==S&&w[M]===0;)M++;for(var v=new Uint8Array(E+(S-M)),U=E;M!==S;)v[U++]=w[M++];return v}function y(g){var m=d(g);if(m)return m;throw new Error("Non-base"+c+" character")}return{encode:l,decodeUnsafe:d,decode:y}}return xf=e,xf}var Af,up;function W8(){return up||(up=1,Af=G8()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),Af}var vf,fp;function X8(){if(fp)return vf;fp=1;var e=W8();return vf=function(t){function n(o){var c=Uint8Array.from(o),a=t(c),u=c.length+4,f=new Uint8Array(u);return f.set(c,0),f.set(a.subarray(0,4),c.length),e.encode(f,u)}function r(o){var c=o.slice(0,-4),a=o.slice(-4),u=t(c);if(!(a[0]^u[0]|a[1]^u[1]|a[2]^u[2]|a[3]^u[3]))return c}function i(o){var c=e.decodeUnsafe(o);if(c)return r(c)}function s(o){var c=e.decode(o),a=r(c);if(!a)throw new Error("Invalid checksum");return a}return{encode:n,decode:s,decodeUnsafe:i}},vf}var If,lp;function _h(){if(lp)return If;lp=1;var{sha256:e}=Xw(),t=X8();function n(r){return e(e(r))}return If=t(n),If}var hp;function z8(){if(hp)return ao;hp=1,Object.defineProperty(ao,"__esModule",{value:!0}),ao.p2pkh=void 0;const e=Pr(),t=Wn(),n=nn(),r=Xt(),i=gi(),s=_h(),o=n.OPS;function c(a,u){if(!a.address&&!a.hash&&!a.output&&!a.pubkey&&!a.input)throw new TypeError("Not enough data");u=Object.assign({validate:!0},u||{}),(0,r.typeforce)({network:r.typeforce.maybe(r.typeforce.Object),address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(20)),output:r.typeforce.maybe(r.typeforce.BufferN(25)),pubkey:r.typeforce.maybe(r.isPoint),signature:r.typeforce.maybe(n.isCanonicalScriptSignature),input:r.typeforce.maybe(r.typeforce.Buffer)},a);const f=i.value(()=>{const g=Buffer.from(s.decode(a.address)),m=g.readUInt8(0),E=g.slice(1);return{version:m,hash:E}}),l=i.value(()=>n.decompile(a.input)),d=a.network||t.bitcoin,y={name:"p2pkh",network:d};if(i.prop(y,"address",()=>{if(!y.hash)return;const g=Buffer.allocUnsafe(21);return g.writeUInt8(d.pubKeyHash,0),y.hash.copy(g,1),s.encode(g)}),i.prop(y,"hash",()=>{if(a.output)return a.output.slice(3,23);if(a.address)return f().hash;if(a.pubkey||y.pubkey)return e.hash160(a.pubkey||y.pubkey)}),i.prop(y,"output",()=>{if(y.hash)return n.compile([o.OP_DUP,o.OP_HASH160,y.hash,o.OP_EQUALVERIFY,o.OP_CHECKSIG])}),i.prop(y,"pubkey",()=>{if(a.input)return l()[1]}),i.prop(y,"signature",()=>{if(a.input)return l()[0]}),i.prop(y,"input",()=>{if(a.pubkey&&a.signature)return n.compile([a.signature,a.pubkey])}),i.prop(y,"witness",()=>{if(y.input)return[]}),u.validate){let g=Buffer.from([]);if(a.address){if(f().version!==d.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(f().hash.length!==20)throw new TypeError("Invalid address");g=f().hash}if(a.hash){if(g.length>0&&!g.equals(a.hash))throw new TypeError("Hash mismatch");g=a.hash}if(a.output){if(a.output.length!==25||a.output[0]!==o.OP_DUP||a.output[1]!==o.OP_HASH160||a.output[2]!==20||a.output[23]!==o.OP_EQUALVERIFY||a.output[24]!==o.OP_CHECKSIG)throw new TypeError("Output is invalid");const m=a.output.slice(3,23);if(g.length>0&&!g.equals(m))throw new TypeError("Hash mismatch");g=m}if(a.pubkey){const m=e.hash160(a.pubkey);if(g.length>0&&!g.equals(m))throw new TypeError("Hash mismatch");g=m}if(a.input){const m=l();if(m.length!==2)throw new TypeError("Input is invalid");if(!n.isCanonicalScriptSignature(m[0]))throw new TypeError("Input has invalid signature");if(!(0,r.isPoint)(m[1]))throw new TypeError("Input has invalid pubkey");if(a.signature&&!a.signature.equals(m[0]))throw new TypeError("Signature mismatch");if(a.pubkey&&!a.pubkey.equals(m[1]))throw new TypeError("Pubkey mismatch");const E=e.hash160(m[1]);if(g.length>0&&!g.equals(E))throw new TypeError("Hash mismatch")}}return Object.assign(y,a)}return ao.p2pkh=c,ao}var uo={},dp;function Y8(){if(dp)return uo;dp=1,Object.defineProperty(uo,"__esModule",{value:!0}),uo.p2sh=void 0;const e=Pr(),t=Wn(),n=nn(),r=Xt(),i=gi(),s=_h(),o=n.OPS;function c(a,u){if(!a.address&&!a.hash&&!a.output&&!a.redeem&&!a.input)throw new TypeError("Not enough data");u=Object.assign({validate:!0},u||{}),(0,r.typeforce)({network:r.typeforce.maybe(r.typeforce.Object),address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(20)),output:r.typeforce.maybe(r.typeforce.BufferN(23)),redeem:r.typeforce.maybe({network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.Buffer),input:r.typeforce.maybe(r.typeforce.Buffer),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))}),input:r.typeforce.maybe(r.typeforce.Buffer),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))},a);let f=a.network;f||(f=a.redeem&&a.redeem.network||t.bitcoin);const l={network:f},d=i.value(()=>{const m=Buffer.from(s.decode(a.address)),E=m.readUInt8(0),_=m.slice(1);return{version:E,hash:_}}),y=i.value(()=>n.decompile(a.input)),g=i.value(()=>{const m=y(),E=m[m.length-1];return{network:f,output:E===o.OP_FALSE?Buffer.from([]):E,input:n.compile(m.slice(0,-1)),witness:a.witness||[]}});if(i.prop(l,"address",()=>{if(!l.hash)return;const m=Buffer.allocUnsafe(21);return m.writeUInt8(l.network.scriptHash,0),l.hash.copy(m,1),s.encode(m)}),i.prop(l,"hash",()=>{if(a.output)return a.output.slice(2,22);if(a.address)return d().hash;if(l.redeem&&l.redeem.output)return e.hash160(l.redeem.output)}),i.prop(l,"output",()=>{if(l.hash)return n.compile([o.OP_HASH160,l.hash,o.OP_EQUAL])}),i.prop(l,"redeem",()=>{if(a.input)return g()}),i.prop(l,"input",()=>{if(!(!a.redeem||!a.redeem.input||!a.redeem.output))return n.compile([].concat(n.decompile(a.redeem.input),a.redeem.output))}),i.prop(l,"witness",()=>{if(l.redeem&&l.redeem.witness)return l.redeem.witness;if(l.input)return[]}),i.prop(l,"name",()=>{const m=["p2sh"];return l.redeem!==void 0&&l.redeem.name!==void 0&&m.push(l.redeem.name),m.join("-")}),u.validate){let m=Buffer.from([]);if(a.address){if(d().version!==f.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(d().hash.length!==20)throw new TypeError("Invalid address");m=d().hash}if(a.hash){if(m.length>0&&!m.equals(a.hash))throw new TypeError("Hash mismatch");m=a.hash}if(a.output){if(a.output.length!==23||a.output[0]!==o.OP_HASH160||a.output[1]!==20||a.output[22]!==o.OP_EQUAL)throw new TypeError("Output is invalid");const _=a.output.slice(2,22);if(m.length>0&&!m.equals(_))throw new TypeError("Hash mismatch");m=_}const E=_=>{if(_.output){const S=n.decompile(_.output);if(!S||S.length<1)throw new TypeError("Redeem.output too short");if(_.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(n.countNonPushOnlyOPs(S)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const w=e.hash160(_.output);if(m.length>0&&!m.equals(w))throw new TypeError("Hash mismatch");m=w}if(_.input){const S=_.input.length>0,w=_.witness&&_.witness.length>0;if(!S&&!w)throw new TypeError("Empty input");if(S&&w)throw new TypeError("Input and witness provided");if(S){const T=n.decompile(_.input);if(!n.isPushOnly(T))throw new TypeError("Non push-only scriptSig")}}};if(a.input){const _=y();if(!_||_.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(g().output))throw new TypeError("Input is invalid");E(g())}if(a.redeem){if(a.redeem.network&&a.redeem.network!==f)throw new TypeError("Network mismatch");if(a.input){const _=g();if(a.redeem.output&&!a.redeem.output.equals(_.output))throw new TypeError("Redeem.output mismatch");if(a.redeem.input&&!a.redeem.input.equals(_.input))throw new TypeError("Redeem.input mismatch")}E(a.redeem)}if(a.witness&&a.redeem&&a.redeem.witness&&!(0,r.stacksEqual)(a.redeem.witness,a.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(l,a)}return uo.p2sh=c,uo}var fo={},pp;function Z8(){if(pp)return fo;pp=1,Object.defineProperty(fo,"__esModule",{value:!0}),fo.p2wpkh=void 0;const e=Pr(),t=Wn(),n=nn(),r=Xt(),i=gi(),s=ac(),o=n.OPS,c=Buffer.alloc(0);function a(u,f){if(!u.address&&!u.hash&&!u.output&&!u.pubkey&&!u.witness)throw new TypeError("Not enough data");f=Object.assign({validate:!0},f||{}),(0,r.typeforce)({address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(20)),input:r.typeforce.maybe(r.typeforce.BufferN(0)),network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.BufferN(22)),pubkey:r.typeforce.maybe(r.isPoint),signature:r.typeforce.maybe(n.isCanonicalScriptSignature),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))},u);const l=i.value(()=>{const g=s.bech32.decode(u.address),m=g.words.shift(),E=s.bech32.fromWords(g.words);return{version:m,prefix:g.prefix,data:Buffer.from(E)}}),d=u.network||t.bitcoin,y={name:"p2wpkh",network:d};if(i.prop(y,"address",()=>{if(!y.hash)return;const g=s.bech32.toWords(y.hash);return g.unshift(0),s.bech32.encode(d.bech32,g)}),i.prop(y,"hash",()=>{if(u.output)return u.output.slice(2,22);if(u.address)return l().data;if(u.pubkey||y.pubkey)return e.hash160(u.pubkey||y.pubkey)}),i.prop(y,"output",()=>{if(y.hash)return n.compile([o.OP_0,y.hash])}),i.prop(y,"pubkey",()=>{if(u.pubkey)return u.pubkey;if(u.witness)return u.witness[1]}),i.prop(y,"signature",()=>{if(u.witness)return u.witness[0]}),i.prop(y,"input",()=>{if(y.witness)return c}),i.prop(y,"witness",()=>{if(u.pubkey&&u.signature)return[u.signature,u.pubkey]}),f.validate){let g=Buffer.from([]);if(u.address){if(d&&d.bech32!==l().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(l().version!==0)throw new TypeError("Invalid address version");if(l().data.length!==20)throw new TypeError("Invalid address data");g=l().data}if(u.hash){if(g.length>0&&!g.equals(u.hash))throw new TypeError("Hash mismatch");g=u.hash}if(u.output){if(u.output.length!==22||u.output[0]!==o.OP_0||u.output[1]!==20)throw new TypeError("Output is invalid");if(g.length>0&&!g.equals(u.output.slice(2)))throw new TypeError("Hash mismatch");g=u.output.slice(2)}if(u.pubkey){const m=e.hash160(u.pubkey);if(g.length>0&&!g.equals(m))throw new TypeError("Hash mismatch");if(g=m,!(0,r.isPoint)(u.pubkey)||u.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(u.witness){if(u.witness.length!==2)throw new TypeError("Witness is invalid");if(!n.isCanonicalScriptSignature(u.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,r.isPoint)(u.witness[1])||u.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(u.signature&&!u.signature.equals(u.witness[0]))throw new TypeError("Signature mismatch");if(u.pubkey&&!u.pubkey.equals(u.witness[1]))throw new TypeError("Pubkey mismatch");const m=e.hash160(u.witness[1]);if(g.length>0&&!g.equals(m))throw new TypeError("Hash mismatch")}}return Object.assign(y,u)}return fo.p2wpkh=a,fo}var lo={},yp;function J8(){if(yp)return lo;yp=1,Object.defineProperty(lo,"__esModule",{value:!0}),lo.p2wsh=void 0;const e=Pr(),t=Wn(),n=nn(),r=Xt(),i=gi(),s=ac(),o=n.OPS,c=Buffer.alloc(0);function a(f){return!!(Buffer.isBuffer(f)&&f.length===65&&f[0]===4&&(0,r.isPoint)(f))}function u(f,l){if(!f.address&&!f.hash&&!f.output&&!f.redeem&&!f.witness)throw new TypeError("Not enough data");l=Object.assign({validate:!0},l||{}),(0,r.typeforce)({network:r.typeforce.maybe(r.typeforce.Object),address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(32)),output:r.typeforce.maybe(r.typeforce.BufferN(34)),redeem:r.typeforce.maybe({input:r.typeforce.maybe(r.typeforce.Buffer),network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.Buffer),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))}),input:r.typeforce.maybe(r.typeforce.BufferN(0)),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))},f);const d=i.value(()=>{const E=s.bech32.decode(f.address),_=E.words.shift(),S=s.bech32.fromWords(E.words);return{version:_,prefix:E.prefix,data:Buffer.from(S)}}),y=i.value(()=>n.decompile(f.redeem.input));let g=f.network;g||(g=f.redeem&&f.redeem.network||t.bitcoin);const m={network:g};if(i.prop(m,"address",()=>{if(!m.hash)return;const E=s.bech32.toWords(m.hash);return E.unshift(0),s.bech32.encode(g.bech32,E)}),i.prop(m,"hash",()=>{if(f.output)return f.output.slice(2);if(f.address)return d().data;if(m.redeem&&m.redeem.output)return e.sha256(m.redeem.output)}),i.prop(m,"output",()=>{if(m.hash)return n.compile([o.OP_0,m.hash])}),i.prop(m,"redeem",()=>{if(f.witness)return{output:f.witness[f.witness.length-1],input:c,witness:f.witness.slice(0,-1)}}),i.prop(m,"input",()=>{if(m.witness)return c}),i.prop(m,"witness",()=>{if(f.redeem&&f.redeem.input&&f.redeem.input.length>0&&f.redeem.output&&f.redeem.output.length>0){const E=n.toStack(y());return m.redeem=Object.assign({witness:E},f.redeem),m.redeem.input=c,[].concat(E,f.redeem.output)}if(f.redeem&&f.redeem.output&&f.redeem.witness)return[].concat(f.redeem.witness,f.redeem.output)}),i.prop(m,"name",()=>{const E=["p2wsh"];return m.redeem!==void 0&&m.redeem.name!==void 0&&E.push(m.redeem.name),E.join("-")}),l.validate){let E=Buffer.from([]);if(f.address){if(d().prefix!==g.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(d().version!==0)throw new TypeError("Invalid address version");if(d().data.length!==32)throw new TypeError("Invalid address data");E=d().data}if(f.hash){if(E.length>0&&!E.equals(f.hash))throw new TypeError("Hash mismatch");E=f.hash}if(f.output){if(f.output.length!==34||f.output[0]!==o.OP_0||f.output[1]!==32)throw new TypeError("Output is invalid");const _=f.output.slice(2);if(E.length>0&&!E.equals(_))throw new TypeError("Hash mismatch");E=_}if(f.redeem){if(f.redeem.network&&f.redeem.network!==g)throw new TypeError("Network mismatch");if(f.redeem.input&&f.redeem.input.length>0&&f.redeem.witness&&f.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(f.redeem.output){const _=n.decompile(f.redeem.output);if(!_||_.length<1)throw new TypeError("Redeem.output is invalid");if(f.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(n.countNonPushOnlyOPs(_)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const S=e.sha256(f.redeem.output);if(E.length>0&&!E.equals(S))throw new TypeError("Hash mismatch");E=S}if(f.redeem.input&&!n.isPushOnly(y()))throw new TypeError("Non push-only scriptSig");if(f.witness&&f.redeem.witness&&!(0,r.stacksEqual)(f.witness,f.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(f.redeem.input&&y().some(a)||f.redeem.output&&(n.decompile(f.redeem.output)||[]).some(a))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(f.witness&&f.witness.length>0){const _=f.witness[f.witness.length-1];if(f.redeem&&f.redeem.output&&!f.redeem.output.equals(_))throw new TypeError("Witness and redeem.output mismatch");if(f.witness.some(a)||(n.decompile(_)||[]).some(a))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(m,f)}return lo.p2wsh=u,lo}var ho={},Ii={},gp;function Sh(){if(gp)return Ii;gp=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.getEccLib=Ii.initEccLib=void 0;const e={};function t(c,a){c?c!==e.eccLib&&(a?.DANGER_DO_NOT_VERIFY_ECCLIB||i(c),e.eccLib=c):e.eccLib=c}Ii.initEccLib=t;function n(){if(!e.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return e.eccLib}Ii.getEccLib=n;const r=c=>Buffer.from(c,"hex");function i(c){s(typeof c.isXOnlyPoint=="function"),s(c.isXOnlyPoint(r("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),s(c.isXOnlyPoint(r("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),s(c.isXOnlyPoint(r("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),s(c.isXOnlyPoint(r("0000000000000000000000000000000000000000000000000000000000000001"))),s(!c.isXOnlyPoint(r("0000000000000000000000000000000000000000000000000000000000000000"))),s(!c.isXOnlyPoint(r("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),s(typeof c.xOnlyPointAddTweak=="function"),o.forEach(a=>{const u=c.xOnlyPointAddTweak(r(a.pubkey),r(a.tweak));a.result===null?s(u===null):(s(u!==null),s(u.parity===a.parity),s(Buffer.from(u.xOnlyPubkey).equals(r(a.result))))})}function s(c){if(!c)throw new Error("ecc library invalid")}const o=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];return Ii}var Of={},kt={},Fc={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var mp;function Q8(){return mp||(mp=1,(function(e,t){var n=tc(),r=n.Buffer;function i(o,c){for(var a in o)c[a]=o[a]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=s);function s(o,c,a){return r(o,c,a)}s.prototype=Object.create(r.prototype),i(r,s),s.from=function(o,c,a){if(typeof o=="number")throw new TypeError("Argument must not be a number");return r(o,c,a)},s.alloc=function(o,c,a){if(typeof o!="number")throw new TypeError("Argument must be a number");var u=r(o);return c!==void 0?typeof a=="string"?u.fill(c,a):u.fill(c):u.fill(0),u},s.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r(o)},s.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n.SlowBuffer(o)}})(Fc,Fc.exports)),Fc.exports}var Bf,wp;function eA(){if(wp)return Bf;wp=1;var e=Q8().Buffer,t=9007199254740991;function n(o){if(o<0||o>t||o%1!==0)throw new RangeError("value out of range")}function r(o,c,a){if(n(o),c||(c=e.allocUnsafe(s(o))),!e.isBuffer(c))throw new TypeError("buffer must be a Buffer instance");return a||(a=0),o<253?(c.writeUInt8(o,a),r.bytes=1):o<=65535?(c.writeUInt8(253,a),c.writeUInt16LE(o,a+1),r.bytes=3):o<=4294967295?(c.writeUInt8(254,a),c.writeUInt32LE(o,a+1),r.bytes=5):(c.writeUInt8(255,a),c.writeUInt32LE(o>>>0,a+1),c.writeUInt32LE(o/4294967296|0,a+5),r.bytes=9),c}function i(o,c){if(!e.isBuffer(o))throw new TypeError("buffer must be a Buffer instance");c||(c=0);var a=o.readUInt8(c);if(a<253)return i.bytes=1,a;if(a===253)return i.bytes=3,o.readUInt16LE(c+1);if(a===254)return i.bytes=5,o.readUInt32LE(c+1);i.bytes=9;var u=o.readUInt32LE(c+1),f=o.readUInt32LE(c+5),l=f*4294967296+u;return n(l),l}function s(o){return n(o),o<253?1:o<=65535?3:o<=4294967295?5:9}return Bf={encode:r,decode:i,encodingLength:s},Bf}var bp;function Eu(){if(bp)return kt;bp=1,Object.defineProperty(kt,"__esModule",{value:!0}),kt.BufferReader=kt.BufferWriter=kt.cloneBuffer=kt.reverseBuffer=kt.writeUInt64LE=kt.readUInt64LE=kt.varuint=void 0;const e=Xt(),{typeforce:t}=e,n=eA();kt.varuint=n;function r(f,l){if(typeof f!="number")throw new Error("cannot write a non-number as a number");if(f<0)throw new Error("specified a negative value for writing an unsigned value");if(f>l)throw new Error("RangeError: value out of range");if(Math.floor(f)!==f)throw new Error("value has a fractional component")}function i(f,l){const d=f.readUInt32LE(l);let y=f.readUInt32LE(l+4);return y*=4294967296,r(y+d,9007199254740991),y+d}kt.readUInt64LE=i;function s(f,l,d){return r(l,9007199254740991),f.writeInt32LE(l&-1,d),f.writeUInt32LE(Math.floor(l/4294967296),d+4),d+8}kt.writeUInt64LE=s;function o(f){if(f.length<1)return f;let l=f.length-1,d=0;for(let y=0;y<f.length/2;y++)d=f[y],f[y]=f[l],f[l]=d,l--;return f}kt.reverseBuffer=o;function c(f){const l=Buffer.allocUnsafe(f.length);return f.copy(l),l}kt.cloneBuffer=c;class a{static withCapacity(l){return new a(Buffer.alloc(l))}constructor(l,d=0){this.buffer=l,this.offset=d,t(e.tuple(e.Buffer,e.UInt32),[l,d])}writeUInt8(l){this.offset=this.buffer.writeUInt8(l,this.offset)}writeInt32(l){this.offset=this.buffer.writeInt32LE(l,this.offset)}writeUInt32(l){this.offset=this.buffer.writeUInt32LE(l,this.offset)}writeUInt64(l){this.offset=s(this.buffer,l,this.offset)}writeVarInt(l){n.encode(l,this.buffer,this.offset),this.offset+=n.encode.bytes}writeSlice(l){if(this.buffer.length<this.offset+l.length)throw new Error("Cannot write slice out of bounds");this.offset+=l.copy(this.buffer,this.offset)}writeVarSlice(l){this.writeVarInt(l.length),this.writeSlice(l)}writeVector(l){this.writeVarInt(l.length),l.forEach(d=>this.writeVarSlice(d))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}kt.BufferWriter=a;class u{constructor(l,d=0){this.buffer=l,this.offset=d,t(e.tuple(e.Buffer,e.UInt32),[l,d])}readUInt8(){const l=this.buffer.readUInt8(this.offset);return this.offset++,l}readInt32(){const l=this.buffer.readInt32LE(this.offset);return this.offset+=4,l}readUInt32(){const l=this.buffer.readUInt32LE(this.offset);return this.offset+=4,l}readUInt64(){const l=i(this.buffer,this.offset);return this.offset+=8,l}readVarInt(){const l=n.decode(this.buffer,this.offset);return this.offset+=n.decode.bytes,l}readSlice(l){if(this.buffer.length<this.offset+l)throw new Error("Cannot read slice out of bounds");const d=this.buffer.slice(this.offset,this.offset+l);return this.offset+=l,d}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const l=this.readVarInt(),d=[];for(let y=0;y<l;y++)d.push(this.readVarSlice());return d}}return kt.BufferReader=u,kt}var Ep;function Th(){return Ep||(Ep=1,(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=tc(),n=Sh(),r=Pr(),i=Eu(),s=Xt();e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const o=m=>"left"in m&&"right"in m;function c(m,E){if(m.length<33)throw new TypeError(`The control-block length is too small. Got ${m.length}, expected min 33.`);const _=(m.length-33)/32;let S=E;for(let w=0;w<_;w++){const T=m.slice(33+32*w,65+32*w);S.compare(T)<0?S=y(S,T):S=y(T,S)}return S}e.rootHashFromPath=c;function a(m){if((0,s.isTapleaf)(m))return{hash:f(m)};const E=[a(m[0]),a(m[1])];E.sort((w,T)=>w.hash.compare(T.hash));const[_,S]=E;return{hash:y(_.hash,S.hash),left:_,right:S}}e.toHashTree=a;function u(m,E){if(o(m)){const _=u(m.left,E);if(_!==void 0)return[..._,m.right.hash];const S=u(m.right,E);if(S!==void 0)return[...S,m.left.hash]}else if(m.hash.equals(E))return[]}e.findScriptPath=u;function f(m){const E=m.version||e.LEAF_VERSION_TAPSCRIPT;return r.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([E]),g(m.output)]))}e.tapleafHash=f;function l(m,E){return r.taggedHash("TapTweak",t.Buffer.concat(E?[m,E]:[m]))}e.tapTweakHash=l;function d(m,E){if(!t.Buffer.isBuffer(m)||m.length!==32||E&&E.length!==32)return null;const _=l(m,E),S=(0,n.getEccLib)().xOnlyPointAddTweak(m,_);return!S||S.xOnlyPubkey===null?null:{parity:S.parity,x:t.Buffer.from(S.xOnlyPubkey)}}e.tweakKey=d;function y(m,E){return r.taggedHash("TapBranch",t.Buffer.concat([m,E]))}function g(m){const E=i.varuint.encodingLength(m.length),_=t.Buffer.allocUnsafe(E);return i.varuint.encode(m.length,_),t.Buffer.concat([_,m])}})(Of)),Of}var _p;function tA(){if(_p)return ho;_p=1,Object.defineProperty(ho,"__esModule",{value:!0}),ho.p2tr=void 0;const e=tc(),t=Wn(),n=nn(),r=Xt(),i=Sh(),s=Th(),o=gi(),c=ac(),a=xh(),u=n.OPS,f=1,l=80;function d(y,g){if(!y.address&&!y.output&&!y.pubkey&&!y.internalPubkey&&!(y.witness&&y.witness.length>1))throw new TypeError("Not enough data");g=Object.assign({validate:!0},g||{}),(0,r.typeforce)({address:r.typeforce.maybe(r.typeforce.String),input:r.typeforce.maybe(r.typeforce.BufferN(0)),network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.BufferN(34)),internalPubkey:r.typeforce.maybe(r.typeforce.BufferN(32)),hash:r.typeforce.maybe(r.typeforce.BufferN(32)),pubkey:r.typeforce.maybe(r.typeforce.BufferN(32)),signature:r.typeforce.maybe(r.typeforce.anyOf(r.typeforce.BufferN(64),r.typeforce.BufferN(65))),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer)),scriptTree:r.typeforce.maybe(r.isTaptree),redeem:r.typeforce.maybe({output:r.typeforce.maybe(r.typeforce.Buffer),redeemVersion:r.typeforce.maybe(r.typeforce.Number),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))}),redeemVersion:r.typeforce.maybe(r.typeforce.Number)},y);const m=o.value(()=>(0,a.fromBech32)(y.address)),E=o.value(()=>{if(!(!y.witness||!y.witness.length))return y.witness.length>=2&&y.witness[y.witness.length-1][0]===l?y.witness.slice(0,-1):y.witness.slice()}),_=o.value(()=>{if(y.scriptTree)return(0,s.toHashTree)(y.scriptTree);if(y.hash)return{hash:y.hash}}),S=y.network||t.bitcoin,w={name:"p2tr",network:S};if(o.prop(w,"address",()=>{if(!w.pubkey)return;const T=c.bech32m.toWords(w.pubkey);return T.unshift(f),c.bech32m.encode(S.bech32,T)}),o.prop(w,"hash",()=>{const T=_();if(T)return T.hash;const O=E();if(O&&O.length>1){const A=O[O.length-1],R=A[0]&r.TAPLEAF_VERSION_MASK,M=O[O.length-2],v=(0,s.tapleafHash)({output:M,version:R});return(0,s.rootHashFromPath)(A,v)}return null}),o.prop(w,"output",()=>{if(w.pubkey)return n.compile([u.OP_1,w.pubkey])}),o.prop(w,"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(w,"redeem",()=>{const T=E();if(!(!T||T.length<2))return{output:T[T.length-2],witness:T.slice(0,-2),redeemVersion:T[T.length-1][0]&r.TAPLEAF_VERSION_MASK}}),o.prop(w,"pubkey",()=>{if(y.pubkey)return y.pubkey;if(y.output)return y.output.slice(2);if(y.address)return m().data;if(w.internalPubkey){const T=(0,s.tweakKey)(w.internalPubkey,w.hash);if(T)return T.x}}),o.prop(w,"internalPubkey",()=>{if(y.internalPubkey)return y.internalPubkey;const T=E();if(T&&T.length>1)return T[T.length-1].slice(1,33)}),o.prop(w,"signature",()=>{if(y.signature)return y.signature;const T=E();if(!(!T||T.length!==1))return T[0]}),o.prop(w,"witness",()=>{if(y.witness)return y.witness;const T=_();if(T&&y.redeem&&y.redeem.output&&y.internalPubkey){const O=(0,s.tapleafHash)({output:y.redeem.output,version:w.redeemVersion}),A=(0,s.findScriptPath)(T,O);if(!A)return;const R=(0,s.tweakKey)(y.internalPubkey,T.hash);if(!R)return;const M=e.Buffer.concat([e.Buffer.from([w.redeemVersion|R.parity]),y.internalPubkey].concat(A));return[y.redeem.output,M]}if(y.signature)return[y.signature]}),g.validate){let T=e.Buffer.from([]);if(y.address){if(S&&S.bech32!==m().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(m().version!==f)throw new TypeError("Invalid address version");if(m().data.length!==32)throw new TypeError("Invalid address data");T=m().data}if(y.pubkey){if(T.length>0&&!T.equals(y.pubkey))throw new TypeError("Pubkey mismatch");T=y.pubkey}if(y.output){if(y.output.length!==34||y.output[0]!==u.OP_1||y.output[1]!==32)throw new TypeError("Output is invalid");if(T.length>0&&!T.equals(y.output.slice(2)))throw new TypeError("Pubkey mismatch");T=y.output.slice(2)}if(y.internalPubkey){const R=(0,s.tweakKey)(y.internalPubkey,w.hash);if(T.length>0&&!T.equals(R.x))throw new TypeError("Pubkey mismatch");T=R.x}if(T&&T.length&&!(0,i.getEccLib)().isXOnlyPoint(T))throw new TypeError("Invalid pubkey for p2tr");const O=_();if(y.hash&&O&&!y.hash.equals(O.hash))throw new TypeError("Hash mismatch");if(y.redeem&&y.redeem.output&&O){const R=(0,s.tapleafHash)({output:y.redeem.output,version:w.redeemVersion});if(!(0,s.findScriptPath)(O,R))throw new TypeError("Redeem script not in tree")}const A=E();if(y.redeem&&w.redeem){if(y.redeem.redeemVersion&&y.redeem.redeemVersion!==w.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(y.redeem.output){if(n.decompile(y.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(w.redeem.output&&!y.redeem.output.equals(w.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(y.redeem.witness&&w.redeem.witness&&!(0,r.stacksEqual)(y.redeem.witness,w.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(A&&A.length)if(A.length===1){if(y.signature&&!y.signature.equals(A[0]))throw new TypeError("Signature mismatch")}else{const R=A[A.length-1];if(R.length<33)throw new TypeError(`The control-block length is too small. Got ${R.length}, expected min 33.`);if((R.length-33)%32!==0)throw new TypeError(`The control-block length of ${R.length} is incorrect!`);const M=(R.length-33)/32;if(M>128)throw new TypeError(`The script path is too long. Got ${M}, expected max 128.`);const v=R.slice(1,33);if(y.internalPubkey&&!y.internalPubkey.equals(v))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(v))throw new TypeError("Invalid internalPubkey for p2tr witness");const U=R[0]&r.TAPLEAF_VERSION_MASK,V=A[A.length-2],K=(0,s.tapleafHash)({output:V,version:U}),H=(0,s.rootHashFromPath)(R,K),$=(0,s.tweakKey)(v,H);if(!$)throw new TypeError("Invalid outputKey for p2tr witness");if(T.length&&!T.equals($.x))throw new TypeError("Pubkey mismatch for p2tr witness");if($.parity!==(R[0]&1))throw new Error("Incorrect parity")}}return Object.assign(w,y)}return ho.p2tr=d,ho}var Sp;function Ec(){return Sp||(Sp=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=L8();Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const n=$8();Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return n.p2ms}});const r=D8();Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return r.p2pk}});const i=z8();Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const s=Y8();Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return s.p2sh}});const o=Z8();Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const c=J8();Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return c.p2wsh}});const a=tA();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return a.p2tr}})})(gf)),gf}var Tp;function xh(){if(Tp)return Yt;Tp=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.toOutputScript=Yt.fromOutputScript=Yt.toBech32=Yt.toBase58Check=Yt.fromBech32=Yt.fromBase58Check=void 0;const e=Wn(),t=Ec(),n=nn(),r=Xt(),i=ac(),s=_h(),o=40,c=2,a=16,u=2,f=80,l="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 d(w,T){const O=w.slice(2);if(O.length<c||O.length>o)throw new TypeError("Invalid program length for segwit address");const A=w[0]-f;if(A<u||A>a)throw new TypeError("Invalid version for segwit address");if(w[1]!==O.length)throw new TypeError("Invalid script for segwit address");return console.warn(l),E(O,A,T.bech32)}function y(w){const T=Buffer.from(s.decode(w));if(T.length<21)throw new TypeError(w+" is too short");if(T.length>21)throw new TypeError(w+" is too long");const O=T.readUInt8(0),A=T.slice(1);return{version:O,hash:A}}Yt.fromBase58Check=y;function g(w){let T,O;try{T=i.bech32.decode(w)}catch{}if(T){if(O=T.words[0],O!==0)throw new TypeError(w+" uses wrong encoding")}else if(T=i.bech32m.decode(w),O=T.words[0],O===0)throw new TypeError(w+" uses wrong encoding");const A=i.bech32.fromWords(T.words.slice(1));return{version:O,prefix:T.prefix,data:Buffer.from(A)}}Yt.fromBech32=g;function m(w,T){(0,r.typeforce)((0,r.tuple)(r.Hash160bit,r.UInt8),arguments);const O=Buffer.allocUnsafe(21);return O.writeUInt8(T,0),w.copy(O,1),s.encode(O)}Yt.toBase58Check=m;function E(w,T,O){const A=i.bech32.toWords(w);return A.unshift(T),T===0?i.bech32.encode(O,A):i.bech32m.encode(O,A)}Yt.toBech32=E;function _(w,T){T=T||e.bitcoin;try{return t.p2pkh({output:w,network:T}).address}catch{}try{return t.p2sh({output:w,network:T}).address}catch{}try{return t.p2wpkh({output:w,network:T}).address}catch{}try{return t.p2wsh({output:w,network:T}).address}catch{}try{return t.p2tr({output:w,network:T}).address}catch{}try{return d(w,T)}catch{}throw new Error(n.toASM(w)+" has no matching Address")}Yt.fromOutputScript=_;function S(w,T){T=T||e.bitcoin;let O,A;try{O=y(w)}catch{}if(O){if(O.version===T.pubKeyHash)return t.p2pkh({hash:O.hash}).output;if(O.version===T.scriptHash)return t.p2sh({hash:O.hash}).output}else{try{A=g(w)}catch{}if(A){if(A.prefix!==T.bech32)throw new Error(w+" has an invalid prefix");if(A.version===0){if(A.data.length===20)return t.p2wpkh({hash:A.data}).output;if(A.data.length===32)return t.p2wsh({hash:A.data}).output}else if(A.version===1){if(A.data.length===32)return t.p2tr({pubkey:A.data}).output}else if(A.version>=u&&A.version<=a&&A.data.length>=c&&A.data.length<=o)return console.warn(l),n.compile([A.version+f,A.data])}}throw new Error(w+" has no matching Script")}return Yt.toOutputScript=S,Yt}var po={},yo={},xp;function nA(){if(xp)return yo;xp=1,Object.defineProperty(yo,"__esModule",{value:!0}),yo.fastMerkleRoot=void 0;function e(t,n){if(!Array.isArray(t))throw TypeError("Expected values Array");if(typeof n!="function")throw TypeError("Expected digest Function");let r=t.length;const i=t.concat();for(;r>1;){let s=0;for(let o=0;o<r;o+=2,++s){const c=i[o],a=o+1===r?c:i[o+1],u=Buffer.concat([c,a]);i[s]=n(u)}r=s}return i[0]}return yo.fastMerkleRoot=e,yo}var go={},Ap;function _c(){if(Ap)return go;Ap=1,Object.defineProperty(go,"__esModule",{value:!0}),go.Transaction=void 0;const e=Eu(),t=Pr(),n=nn(),r=nn(),i=Xt(),{typeforce:s}=i;function o(E){const _=E.length;return e.varuint.encodingLength(_)+_}function c(E){const _=E.length;return e.varuint.encodingLength(_)+E.reduce((S,w)=>S+o(w),0)}const a=Buffer.allocUnsafe(0),u=[],f=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),l=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),d=Buffer.from("ffffffffffffffff","hex"),y={script:a,valueBuffer:d};function g(E){return E.value!==void 0}class m{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(_,S){const w=new e.BufferReader(_),T=new m;T.version=w.readInt32();const O=w.readUInt8(),A=w.readUInt8();let R=!1;O===m.ADVANCED_TRANSACTION_MARKER&&A===m.ADVANCED_TRANSACTION_FLAG?R=!0:w.offset-=2;const M=w.readVarInt();for(let U=0;U<M;++U)T.ins.push({hash:w.readSlice(32),index:w.readUInt32(),script:w.readVarSlice(),sequence:w.readUInt32(),witness:u});const v=w.readVarInt();for(let U=0;U<v;++U)T.outs.push({value:w.readUInt64(),script:w.readVarSlice()});if(R){for(let U=0;U<M;++U)T.ins[U].witness=w.readVector();if(!T.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(T.locktime=w.readUInt32(),S)return T;if(w.offset!==_.length)throw new Error("Transaction has unexpected data");return T}static fromHex(_){return m.fromBuffer(Buffer.from(_,"hex"),!1)}static isCoinbaseHash(_){s(i.Hash256bit,_);for(let S=0;S<32;++S)if(_[S]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&m.isCoinbaseHash(this.ins[0].hash)}addInput(_,S,w,T){return s(i.tuple(i.Hash256bit,i.UInt32,i.maybe(i.UInt32),i.maybe(i.Buffer)),arguments),i.Null(w)&&(w=m.DEFAULT_SEQUENCE),this.ins.push({hash:_,index:S,script:T||a,sequence:w,witness:u})-1}addOutput(_,S){return s(i.tuple(i.Buffer,i.Satoshi),arguments),this.outs.push({script:_,value:S})-1}hasWitnesses(){return this.ins.some(_=>_.witness.length!==0)}stripWitnesses(){this.ins.forEach(_=>{_.witness=u})}weight(){const _=this.byteLength(!1),S=this.byteLength(!0);return _*3+S}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(_=!0){const S=_&&this.hasWitnesses();return(S?10:8)+e.varuint.encodingLength(this.ins.length)+e.varuint.encodingLength(this.outs.length)+this.ins.reduce((w,T)=>w+40+o(T.script),0)+this.outs.reduce((w,T)=>w+8+o(T.script),0)+(S?this.ins.reduce((w,T)=>w+c(T.witness),0):0)}clone(){const _=new m;return _.version=this.version,_.locktime=this.locktime,_.ins=this.ins.map(S=>({hash:S.hash,index:S.index,script:S.script,sequence:S.sequence,witness:S.witness})),_.outs=this.outs.map(S=>({script:S.script,value:S.value})),_}hashForSignature(_,S,w){if(s(i.tuple(i.UInt32,i.Buffer,i.Number),arguments),_>=this.ins.length)return l;const T=n.compile(n.decompile(S).filter(R=>R!==r.OPS.OP_CODESEPARATOR)),O=this.clone();if((w&31)===m.SIGHASH_NONE)O.outs=[],O.ins.forEach((R,M)=>{M!==_&&(R.sequence=0)});else if((w&31)===m.SIGHASH_SINGLE){if(_>=this.outs.length)return l;O.outs.length=_+1;for(let R=0;R<_;R++)O.outs[R]=y;O.ins.forEach((R,M)=>{M!==_&&(R.sequence=0)})}w&m.SIGHASH_ANYONECANPAY?(O.ins=[O.ins[_]],O.ins[0].script=T):(O.ins.forEach(R=>{R.script=a}),O.ins[_].script=T);const A=Buffer.allocUnsafe(O.byteLength(!1)+4);return A.writeInt32LE(w,A.length-4),O.__toBuffer(A,0,!1),t.hash256(A)}hashForWitnessV1(_,S,w,T,O,A){if(s(i.tuple(i.UInt32,s.arrayOf(i.Buffer),s.arrayOf(i.Satoshi),i.UInt32),arguments),w.length!==this.ins.length||S.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const R=T===m.SIGHASH_DEFAULT?m.SIGHASH_ALL:T&m.SIGHASH_OUTPUT_MASK,v=(T&m.SIGHASH_INPUT_MASK)===m.SIGHASH_ANYONECANPAY,U=R===m.SIGHASH_NONE,V=R===m.SIGHASH_SINGLE;let K=a,H=a,$=a,P=a,D=a;if(!v){let q=e.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(N=>{q.writeSlice(N.hash),q.writeUInt32(N.index)}),K=t.sha256(q.end()),q=e.BufferWriter.withCapacity(8*this.ins.length),w.forEach(N=>q.writeUInt64(N)),H=t.sha256(q.end()),q=e.BufferWriter.withCapacity(S.map(o).reduce((N,L)=>N+L)),S.forEach(N=>q.writeVarSlice(N)),$=t.sha256(q.end()),q=e.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(N=>q.writeUInt32(N.sequence)),P=t.sha256(q.end())}if(U||V){if(V&&_<this.outs.length){const q=this.outs[_],N=e.BufferWriter.withCapacity(8+o(q.script));N.writeUInt64(q.value),N.writeVarSlice(q.script),D=t.sha256(N.end())}}else{const q=this.outs.map(L=>8+o(L.script)).reduce((L,G)=>L+G),N=e.BufferWriter.withCapacity(q);this.outs.forEach(L=>{N.writeUInt64(L.value),N.writeVarSlice(L.script)}),D=t.sha256(N.end())}const F=(O?2:0)+(A?1:0),x=174-(v?49:0)-(U?32:0)+(A?32:0)+(O?37:0),B=e.BufferWriter.withCapacity(x);if(B.writeUInt8(T),B.writeInt32(this.version),B.writeUInt32(this.locktime),B.writeSlice(K),B.writeSlice(H),B.writeSlice($),B.writeSlice(P),U||V||B.writeSlice(D),B.writeUInt8(F),v){const q=this.ins[_];B.writeSlice(q.hash),B.writeUInt32(q.index),B.writeUInt64(w[_]),B.writeVarSlice(S[_]),B.writeUInt32(q.sequence)}else B.writeUInt32(_);if(A){const q=e.BufferWriter.withCapacity(o(A));q.writeVarSlice(A),B.writeSlice(t.sha256(q.end()))}return V&&B.writeSlice(D),O&&(B.writeSlice(O),B.writeUInt8(0),B.writeUInt32(4294967295)),t.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),B.end()]))}hashForWitnessV0(_,S,w,T){s(i.tuple(i.UInt32,i.Buffer,i.Satoshi,i.UInt32),arguments);let O=Buffer.from([]),A,R=f,M=f,v=f;if(T&m.SIGHASH_ANYONECANPAY||(O=Buffer.allocUnsafe(36*this.ins.length),A=new e.BufferWriter(O,0),this.ins.forEach(V=>{A.writeSlice(V.hash),A.writeUInt32(V.index)}),M=t.hash256(O)),!(T&m.SIGHASH_ANYONECANPAY)&&(T&31)!==m.SIGHASH_SINGLE&&(T&31)!==m.SIGHASH_NONE&&(O=Buffer.allocUnsafe(4*this.ins.length),A=new e.BufferWriter(O,0),this.ins.forEach(V=>{A.writeUInt32(V.sequence)}),v=t.hash256(O)),(T&31)!==m.SIGHASH_SINGLE&&(T&31)!==m.SIGHASH_NONE){const V=this.outs.reduce((K,H)=>K+8+o(H.script),0);O=Buffer.allocUnsafe(V),A=new e.BufferWriter(O,0),this.outs.forEach(K=>{A.writeUInt64(K.value),A.writeVarSlice(K.script)}),R=t.hash256(O)}else if((T&31)===m.SIGHASH_SINGLE&&_<this.outs.length){const V=this.outs[_];O=Buffer.allocUnsafe(8+o(V.script)),A=new e.BufferWriter(O,0),A.writeUInt64(V.value),A.writeVarSlice(V.script),R=t.hash256(O)}O=Buffer.allocUnsafe(156+o(S)),A=new e.BufferWriter(O,0);const U=this.ins[_];return A.writeInt32(this.version),A.writeSlice(M),A.writeSlice(v),A.writeSlice(U.hash),A.writeUInt32(U.index),A.writeVarSlice(S),A.writeUInt64(w),A.writeUInt32(U.sequence),A.writeSlice(R),A.writeUInt32(this.locktime),A.writeUInt32(T),t.hash256(O)}getHash(_){return _&&this.isCoinbase()?Buffer.alloc(32,0):t.hash256(this.__toBuffer(void 0,void 0,_))}getId(){return(0,e.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(_,S){return this.__toBuffer(_,S,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(_,S){s(i.tuple(i.Number,i.Buffer),arguments),this.ins[_].script=S}setWitness(_,S){s(i.tuple(i.Number,[i.Buffer]),arguments),this.ins[_].witness=S}__toBuffer(_,S,w=!1){_||(_=Buffer.allocUnsafe(this.byteLength(w)));const T=new e.BufferWriter(_,S||0);T.writeInt32(this.version);const O=w&&this.hasWitnesses();return O&&(T.writeUInt8(m.ADVANCED_TRANSACTION_MARKER),T.writeUInt8(m.ADVANCED_TRANSACTION_FLAG)),T.writeVarInt(this.ins.length),this.ins.forEach(A=>{T.writeSlice(A.hash),T.writeUInt32(A.index),T.writeVarSlice(A.script),T.writeUInt32(A.sequence)}),T.writeVarInt(this.outs.length),this.outs.forEach(A=>{g(A)?T.writeUInt64(A.value):T.writeSlice(A.valueBuffer),T.writeVarSlice(A.script)}),O&&this.ins.forEach(A=>{T.writeVector(A.witness)}),T.writeUInt32(this.locktime),S!==void 0?_.slice(S,T.offset):_}}return go.Transaction=m,m.DEFAULT_SEQUENCE=4294967295,m.SIGHASH_DEFAULT=0,m.SIGHASH_ALL=1,m.SIGHASH_NONE=2,m.SIGHASH_SINGLE=3,m.SIGHASH_ANYONECANPAY=128,m.SIGHASH_OUTPUT_MASK=3,m.SIGHASH_INPUT_MASK=128,m.ADVANCED_TRANSACTION_MARKER=0,m.ADVANCED_TRANSACTION_FLAG=1,go}var vp;function rA(){if(vp)return po;vp=1,Object.defineProperty(po,"__esModule",{value:!0}),po.Block=void 0;const e=Eu(),t=Pr(),n=nA(),r=_c(),i=Xt(),{typeforce:s}=i,o=new TypeError("Cannot compute merkle root for zero transactions"),c=new TypeError("Cannot compute witness commit for non-segwit block");class a{constructor(){this.version=1,this.prevHash=void 0,this.merkleRoot=void 0,this.timestamp=0,this.witnessCommit=void 0,this.bits=0,this.nonce=0,this.transactions=void 0}static fromBuffer(d){if(d.length<80)throw new Error("Buffer too small (< 80 bytes)");const y=new e.BufferReader(d),g=new a;if(g.version=y.readInt32(),g.prevHash=y.readSlice(32),g.merkleRoot=y.readSlice(32),g.timestamp=y.readUInt32(),g.bits=y.readUInt32(),g.nonce=y.readUInt32(),d.length===80)return g;const m=()=>{const S=r.Transaction.fromBuffer(y.buffer.slice(y.offset),!0);return y.offset+=S.byteLength(),S},E=y.readVarInt();g.transactions=[];for(let S=0;S<E;++S){const w=m();g.transactions.push(w)}const _=g.getWitnessCommit();return _&&(g.witnessCommit=_),g}static fromHex(d){return a.fromBuffer(Buffer.from(d,"hex"))}static calculateTarget(d){const y=((d&4278190080)>>24)-3,g=d&8388607,m=Buffer.alloc(32,0);return m.writeUIntBE(g,29-y,3),m}static calculateMerkleRoot(d,y){if(s([{getHash:i.Function}],d),d.length===0)throw o;if(y&&!u(d))throw c;const g=d.map(E=>E.getHash(y)),m=(0,n.fastMerkleRoot)(g,t.hash256);return y?t.hash256(Buffer.concat([m,d[0].ins[0].witness[0]])):m}getWitnessCommit(){if(!u(this.transactions))return null;const d=this.transactions[0].outs.filter(g=>g.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex"))).map(g=>g.script.slice(6,38));if(d.length===0)return null;const y=d[d.length-1];return y instanceof Buffer&&y.length===32?y:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&this.witnessCommit.length===32||this.getWitnessCommit()!==null}hasWitness(){return f(this.transactions)}weight(){const d=this.byteLength(!1,!1),y=this.byteLength(!1,!0);return d*3+y}byteLength(d,y=!0){return d||!this.transactions?80:80+e.varuint.encodingLength(this.transactions.length)+this.transactions.reduce((g,m)=>g+m.byteLength(y),0)}getHash(){return t.hash256(this.toBuffer(!0))}getId(){return(0,e.reverseBuffer)(this.getHash()).toString("hex")}getUTCDate(){const d=new Date(0);return d.setUTCSeconds(this.timestamp),d}toBuffer(d){const y=Buffer.allocUnsafe(this.byteLength(d)),g=new e.BufferWriter(y);return g.writeInt32(this.version),g.writeSlice(this.prevHash),g.writeSlice(this.merkleRoot),g.writeUInt32(this.timestamp),g.writeUInt32(this.bits),g.writeUInt32(this.nonce),d||!this.transactions||(e.varuint.encode(this.transactions.length,y,g.offset),g.offset+=e.varuint.encode.bytes,this.transactions.forEach(m=>{const E=m.byteLength();m.toBuffer(y,g.offset),g.offset+=E})),y}toHex(d){return this.toBuffer(d).toString("hex")}checkTxRoots(){const d=this.hasWitnessCommit();return!d&&this.hasWitness()?!1:this.__checkMerkleRoot()&&(d?this.__checkWitnessCommit():!0)}checkProofOfWork(){const d=(0,e.reverseBuffer)(this.getHash()),y=a.calculateTarget(this.bits);return d.compare(y)<=0}__checkMerkleRoot(){if(!this.transactions)throw o;const d=a.calculateMerkleRoot(this.transactions);return this.merkleRoot.compare(d)===0}__checkWitnessCommit(){if(!this.transactions)throw o;if(!this.hasWitnessCommit())throw c;const d=a.calculateMerkleRoot(this.transactions,!0);return this.witnessCommit.compare(d)===0}}po.Block=a;function u(l){return l instanceof Array&&l[0]&&l[0].ins&&l[0].ins instanceof Array&&l[0].ins[0]&&l[0].ins[0].witness&&l[0].ins[0].witness instanceof Array&&l[0].ins[0].witness.length>0}function f(l){return l instanceof Array&&l.some(d=>typeof d=="object"&&d.ins instanceof Array&&d.ins.some(y=>typeof y=="object"&&y.witness instanceof Array&&y.witness.length>0))}return po}var mo={},Mc={},qc={},Nf={},cs={},as={},kf={},Ip;function Mt(){return Ip||(Ip=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),(function(t){t[t.UNSIGNED_TX=0]="UNSIGNED_TX",t[t.GLOBAL_XPUB=1]="GLOBAL_XPUB"})(e.GlobalTypes||(e.GlobalTypes={})),e.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(function(t){t[t.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",t[t.WITNESS_UTXO=1]="WITNESS_UTXO",t[t.PARTIAL_SIG=2]="PARTIAL_SIG",t[t.SIGHASH_TYPE=3]="SIGHASH_TYPE",t[t.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",t[t.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",t[t.BIP32_DERIVATION=6]="BIP32_DERIVATION",t[t.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",t[t.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",t[t.POR_COMMITMENT=9]="POR_COMMITMENT",t[t.TAP_KEY_SIG=19]="TAP_KEY_SIG",t[t.TAP_SCRIPT_SIG=20]="TAP_SCRIPT_SIG",t[t.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",t[t.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",t[t.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",t[t.TAP_MERKLE_ROOT=24]="TAP_MERKLE_ROOT"})(e.InputTypes||(e.InputTypes={})),e.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment","tapKeySig","tapScriptSig","tapLeafScript","tapBip32Derivation","tapInternalKey","tapMerkleRoot"],(function(t){t[t.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",t[t.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",t[t.BIP32_DERIVATION=2]="BIP32_DERIVATION",t[t.TAP_INTERNAL_KEY=5]="TAP_INTERNAL_KEY",t[t.TAP_TREE=6]="TAP_TREE",t[t.TAP_BIP32_DERIVATION=7]="TAP_BIP32_DERIVATION"})(e.OutputTypes||(e.OutputTypes={})),e.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation","tapInternalKey","tapTree","tapBip32Derivation"]})(kf)),kf}var Vr={},Op;function iA(){if(Op)return Vr;Op=1,Object.defineProperty(Vr,"__esModule",{value:!0});const e=Mt(),t=o=>[...Array(o).keys()];function n(o){if(o.key[0]!==e.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+o.key.toString("hex"));if(o.key.length!==79||![2,3].includes(o.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+o.key.toString("hex"));if(o.value.length/4%1!==0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const c=o.key.slice(1),a={masterFingerprint:o.value.slice(0,4),extendedPubkey:c,path:"m"};for(const u of t(o.value.length/4-1)){const f=o.value.readUInt32LE(u*4+4),l=!!(f&2147483648),d=f&2147483647;a.path+="/"+d.toString(10)+(l?"'":"")}return a}Vr.decode=n;function r(o){const c=Buffer.from([e.GlobalTypes.GLOBAL_XPUB]),a=Buffer.concat([c,o.extendedPubkey]),u=o.path.split("/"),f=Buffer.allocUnsafe(u.length*4);o.masterFingerprint.copy(f,0);let l=4;return u.slice(1).forEach(d=>{const y=d.slice(-1)==="'";let g=2147483647&parseInt(y?d.slice(0,-1):d,10);y&&(g+=2147483648),f.writeUInt32LE(g,l),l+=4}),{key:a,value:f}}Vr.encode=r,Vr.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }";function i(o){const c=o.extendedPubkey,a=o.masterFingerprint,u=o.path;return Buffer.isBuffer(c)&&c.length===78&&[2,3].indexOf(c[45])>-1&&Buffer.isBuffer(a)&&a.length===4&&typeof u=="string"&&!!u.match(/^m(\/\d+'?)*$/)}Vr.check=i;function s(o,c,a){const u=c.extendedPubkey.toString("hex");return a.has(u)?!1:(a.add(u),o.filter(f=>f.extendedPubkey.equals(c.extendedPubkey)).length===0)}return Vr.canAddToArray=s,Vr}var Vc={},Bp;function sA(){if(Bp)return Vc;Bp=1,Object.defineProperty(Vc,"__esModule",{value:!0});const e=Mt();function t(n){return{key:Buffer.from([e.GlobalTypes.UNSIGNED_TX]),value:n.toBuffer()}}return Vc.encode=t,Vc}var Lr={},Np;function oA(){if(Np)return Lr;Np=1,Object.defineProperty(Lr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+s.key.toString("hex"));return s.value}Lr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.FINAL_SCRIPTSIG]),value:s}}Lr.encode=n,Lr.expected="Buffer";function r(s){return Buffer.isBuffer(s)}Lr.check=r;function i(s,o){return!!s&&!!o&&s.finalScriptSig===void 0}return Lr.canAdd=i,Lr}var $r={},kp;function cA(){if(kp)return $r;kp=1,Object.defineProperty($r,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+s.key.toString("hex"));return s.value}$r.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.FINAL_SCRIPTWITNESS]),value:s}}$r.encode=n,$r.expected="Buffer";function r(s){return Buffer.isBuffer(s)}$r.check=r;function i(s,o){return!!s&&!!o&&s.finalScriptWitness===void 0}return $r.canAdd=i,$r}var Dr={},Pp;function aA(){if(Pp)return Dr;Pp=1,Object.defineProperty(Dr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+s.key.toString("hex"));return s.value}Dr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.NON_WITNESS_UTXO]),value:s}}Dr.encode=n,Dr.expected="Buffer";function r(s){return Buffer.isBuffer(s)}Dr.check=r;function i(s,o){return!!s&&!!o&&s.nonWitnessUtxo===void 0}return Dr.canAdd=i,Dr}var jr={},Rp;function uA(){if(Rp)return jr;Rp=1,Object.defineProperty(jr,"__esModule",{value:!0});const e=Mt();function t(o){if(o.key[0]!==e.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+o.key.toString("hex"));if(!(o.key.length===34||o.key.length===66)||![2,3,4].includes(o.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+o.key.toString("hex"));return{pubkey:o.key.slice(1),signature:o.value}}jr.decode=t;function n(o){const c=Buffer.from([e.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([c,o.pubkey]),value:o.signature}}jr.encode=n,jr.expected="{ pubkey: Buffer; signature: Buffer; }";function r(o){return Buffer.isBuffer(o.pubkey)&&Buffer.isBuffer(o.signature)&&[33,65].includes(o.pubkey.length)&&[2,3,4].includes(o.pubkey[0])&&i(o.signature)}jr.check=r;function i(o){if(!Buffer.isBuffer(o)||o.length<9||o[0]!==48||o.length!==o[1]+3||o[2]!==2)return!1;const c=o[3];if(c>33||c<1||o[3+c+1]!==2)return!1;const a=o[3+c+2];return!(a>33||a<1||o.length!==3+c+2+a+2)}function s(o,c,a){const u=c.pubkey.toString("hex");return a.has(u)?!1:(a.add(u),o.filter(f=>f.pubkey.equals(c.pubkey)).length===0)}return jr.canAddToArray=s,jr}var Kr={},Up;function fA(){if(Up)return Kr;Up=1,Object.defineProperty(Kr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+s.key.toString("hex"));return s.value.toString("utf8")}Kr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.POR_COMMITMENT]),value:Buffer.from(s,"utf8")}}Kr.encode=n,Kr.expected="string";function r(s){return typeof s=="string"}Kr.check=r;function i(s,o){return!!s&&!!o&&s.porCommitment===void 0}return Kr.canAdd=i,Kr}var Gr={},Cp;function lA(){if(Cp)return Gr;Cp=1,Object.defineProperty(Gr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+s.key.toString("hex"));return s.value.readUInt32LE(0)}Gr.decode=t;function n(s){const o=Buffer.from([e.InputTypes.SIGHASH_TYPE]),c=Buffer.allocUnsafe(4);return c.writeUInt32LE(s,0),{key:o,value:c}}Gr.encode=n,Gr.expected="number";function r(s){return typeof s=="number"}Gr.check=r;function i(s,o){return!!s&&!!o&&s.sighashType===void 0}return Gr.canAdd=i,Gr}var Wr={},Hp;function hA(){if(Hp)return Wr;Hp=1,Object.defineProperty(Wr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.TAP_KEY_SIG||s.key.length!==1)throw new Error("Decode Error: could not decode tapKeySig with key 0x"+s.key.toString("hex"));if(!r(s.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return s.value}Wr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.TAP_KEY_SIG]),value:s}}Wr.encode=n,Wr.expected="Buffer";function r(s){return Buffer.isBuffer(s)&&(s.length===64||s.length===65)}Wr.check=r;function i(s,o){return!!s&&!!o&&s.tapKeySig===void 0}return Wr.canAdd=i,Wr}var Xr={},Fp;function dA(){if(Fp)return Xr;Fp=1,Object.defineProperty(Xr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.TAP_LEAF_SCRIPT)throw new Error("Decode Error: could not decode tapLeafScript with key 0x"+s.key.toString("hex"));if((s.key.length-2)%32!==0)throw new Error("Decode Error: tapLeafScript has invalid control block in key 0x"+s.key.toString("hex"));const o=s.value[s.value.length-1];if((s.key[1]&254)!==o)throw new Error("Decode Error: tapLeafScript bad leaf version in key 0x"+s.key.toString("hex"));const c=s.value.slice(0,-1);return{controlBlock:s.key.slice(1),script:c,leafVersion:o}}Xr.decode=t;function n(s){const o=Buffer.from([e.InputTypes.TAP_LEAF_SCRIPT]),c=Buffer.from([s.leafVersion]);return{key:Buffer.concat([o,s.controlBlock]),value:Buffer.concat([s.script,c])}}Xr.encode=n,Xr.expected="{ controlBlock: Buffer; leafVersion: number, script: Buffer; }";function r(s){return Buffer.isBuffer(s.controlBlock)&&(s.controlBlock.length-1)%32===0&&(s.controlBlock[0]&254)===s.leafVersion&&Buffer.isBuffer(s.script)}Xr.check=r;function i(s,o,c){const a=o.controlBlock.toString("hex");return c.has(a)?!1:(c.add(a),s.filter(u=>u.controlBlock.equals(o.controlBlock)).length===0)}return Xr.canAddToArray=i,Xr}var zr={},Mp;function pA(){if(Mp)return zr;Mp=1,Object.defineProperty(zr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.TAP_MERKLE_ROOT||s.key.length!==1)throw new Error("Decode Error: could not decode tapMerkleRoot with key 0x"+s.key.toString("hex"));if(!r(s.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return s.value}zr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.TAP_MERKLE_ROOT]),value:s}}zr.encode=n,zr.expected="Buffer";function r(s){return Buffer.isBuffer(s)&&s.length===32}zr.check=r;function i(s,o){return!!s&&!!o&&s.tapMerkleRoot===void 0}return zr.canAdd=i,zr}var Yr={},qp;function yA(){if(qp)return Yr;qp=1,Object.defineProperty(Yr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.TAP_SCRIPT_SIG)throw new Error("Decode Error: could not decode tapScriptSig with key 0x"+s.key.toString("hex"));if(s.key.length!==65)throw new Error("Decode Error: tapScriptSig has invalid key 0x"+s.key.toString("hex"));if(s.value.length!==64&&s.value.length!==65)throw new Error("Decode Error: tapScriptSig has invalid signature in key 0x"+s.key.toString("hex"));const o=s.key.slice(1,33),c=s.key.slice(33);return{pubkey:o,leafHash:c,signature:s.value}}Yr.decode=t;function n(s){const o=Buffer.from([e.InputTypes.TAP_SCRIPT_SIG]);return{key:Buffer.concat([o,s.pubkey,s.leafHash]),value:s.signature}}Yr.encode=n,Yr.expected="{ pubkey: Buffer; leafHash: Buffer; signature: Buffer; }";function r(s){return Buffer.isBuffer(s.pubkey)&&Buffer.isBuffer(s.leafHash)&&Buffer.isBuffer(s.signature)&&s.pubkey.length===32&&s.leafHash.length===32&&(s.signature.length===64||s.signature.length===65)}Yr.check=r;function i(s,o,c){const a=o.pubkey.toString("hex")+o.leafHash.toString("hex");return c.has(a)?!1:(c.add(a),s.filter(u=>u.pubkey.equals(o.pubkey)&&u.leafHash.equals(o.leafHash)).length===0)}return Yr.canAddToArray=i,Yr}var Zr={},lr={},us={},Vp;function ts(){if(Vp)return us;Vp=1,Object.defineProperty(us,"__esModule",{value:!0});const e=9007199254740991;function t(s){if(s<0||s>e||s%1!==0)throw new RangeError("value out of range")}function n(s,o,c){if(t(s),o||(o=Buffer.allocUnsafe(i(s))),!Buffer.isBuffer(o))throw new TypeError("buffer must be a Buffer instance");return c||(c=0),s<253?(o.writeUInt8(s,c),Object.assign(n,{bytes:1})):s<=65535?(o.writeUInt8(253,c),o.writeUInt16LE(s,c+1),Object.assign(n,{bytes:3})):s<=4294967295?(o.writeUInt8(254,c),o.writeUInt32LE(s,c+1),Object.assign(n,{bytes:5})):(o.writeUInt8(255,c),o.writeUInt32LE(s>>>0,c+1),o.writeUInt32LE(s/4294967296|0,c+5),Object.assign(n,{bytes:9})),o}us.encode=n;function r(s,o){if(!Buffer.isBuffer(s))throw new TypeError("buffer must be a Buffer instance");o||(o=0);const c=s.readUInt8(o);if(c<253)return Object.assign(r,{bytes:1}),c;if(c===253)return Object.assign(r,{bytes:3}),s.readUInt16LE(o+1);if(c===254)return Object.assign(r,{bytes:5}),s.readUInt32LE(o+1);{Object.assign(r,{bytes:9});const a=s.readUInt32LE(o+1),f=s.readUInt32LE(o+5)*4294967296+a;return t(f),f}}us.decode=r;function i(s){return t(s),s<253?1:s<=65535?3:s<=4294967295?5:9}return us.encodingLength=i,us}var Lp;function Ah(){if(Lp)return lr;Lp=1,Object.defineProperty(lr,"__esModule",{value:!0});const e=ts();lr.range=c=>[...Array(c).keys()];function t(c){if(c.length<1)return c;let a=c.length-1,u=0;for(let f=0;f<c.length/2;f++)u=c[f],c[f]=c[a],c[a]=u,a--;return c}lr.reverseBuffer=t;function n(c){const a=c.map(r);return a.push(Buffer.from([0])),Buffer.concat(a)}lr.keyValsToBuffer=n;function r(c){const a=c.key.length,u=c.value.length,f=e.encodingLength(a),l=e.encodingLength(u),d=Buffer.allocUnsafe(f+a+l+u);return e.encode(a,d,0),c.key.copy(d,f),e.encode(u,d,f+a),c.value.copy(d,f+a+l),d}lr.keyValToBuffer=r;function i(c,a){if(typeof c!="number")throw new Error("cannot write a non-number as a number");if(c<0)throw new Error("specified a negative value for writing an unsigned value");if(c>a)throw new Error("RangeError: value out of range");if(Math.floor(c)!==c)throw new Error("value has a fractional component")}function s(c,a){const u=c.readUInt32LE(a);let f=c.readUInt32LE(a+4);return f*=4294967296,i(f+u,9007199254740991),f+u}lr.readUInt64LE=s;function o(c,a,u){return i(a,9007199254740991),c.writeInt32LE(a&-1,u),c.writeUInt32LE(Math.floor(a/4294967296),u+4),u+8}return lr.writeUInt64LE=o,lr}var $p;function gA(){if($p)return Zr;$p=1,Object.defineProperty(Zr,"__esModule",{value:!0});const e=Mt(),t=Ah(),n=ts();function r(c){if(c.key[0]!==e.InputTypes.WITNESS_UTXO)throw new Error("Decode Error: could not decode witnessUtxo with key 0x"+c.key.toString("hex"));const a=t.readUInt64LE(c.value,0);let u=8;const f=n.decode(c.value,u);u+=n.encodingLength(f);const l=c.value.slice(u);if(l.length!==f)throw new Error("Decode Error: WITNESS_UTXO script is not proper length");return{script:l,value:a}}Zr.decode=r;function i(c){const{script:a,value:u}=c,f=n.encodingLength(a.length),l=Buffer.allocUnsafe(8+f+a.length);return t.writeUInt64LE(l,u,0),n.encode(a.length,l,8),a.copy(l,8+f),{key:Buffer.from([e.InputTypes.WITNESS_UTXO]),value:l}}Zr.encode=i,Zr.expected="{ script: Buffer; value: number; }";function s(c){return Buffer.isBuffer(c.script)&&typeof c.value=="number"}Zr.check=s;function o(c,a){return!!c&&!!a&&c.witnessUtxo===void 0}return Zr.canAdd=o,Zr}var Jr={},Dp;function mA(){if(Dp)return Jr;Dp=1,Object.defineProperty(Jr,"__esModule",{value:!0});const e=Mt(),t=ts();function n(o){if(o.key[0]!==e.OutputTypes.TAP_TREE||o.key.length!==1)throw new Error("Decode Error: could not decode tapTree with key 0x"+o.key.toString("hex"));let c=0;const a=[];for(;c<o.value.length;){const u=o.value[c++],f=o.value[c++],l=t.decode(o.value,c);c+=t.encodingLength(l),a.push({depth:u,leafVersion:f,script:o.value.slice(c,c+l)}),c+=l}return{leaves:a}}Jr.decode=n;function r(o){const c=Buffer.from([e.OutputTypes.TAP_TREE]),a=[].concat(...o.leaves.map(u=>[Buffer.of(u.depth,u.leafVersion),t.encode(u.script.length),u.script]));return{key:c,value:Buffer.concat(a)}}Jr.encode=r,Jr.expected="{ leaves: [{ depth: number; leafVersion: number, script: Buffer; }] }";function i(o){return Array.isArray(o.leaves)&&o.leaves.every(c=>c.depth>=0&&c.depth<=128&&(c.leafVersion&254)===c.leafVersion&&Buffer.isBuffer(c.script))}Jr.check=i;function s(o,c){return!!o&&!!c&&o.tapTree===void 0}return Jr.canAdd=s,Jr}var Lc={},jp;function zw(){if(jp)return Lc;jp=1,Object.defineProperty(Lc,"__esModule",{value:!0});const e=r=>[...Array(r).keys()],t=r=>r.length===33&&[2,3].includes(r[0])||r.length===65&&r[0]===4;function n(r,i=t){function s(f){if(f.key[0]!==r)throw new Error("Decode Error: could not decode bip32Derivation with key 0x"+f.key.toString("hex"));const l=f.key.slice(1);if(!i(l))throw new Error("Decode Error: bip32Derivation has invalid pubkey in key 0x"+f.key.toString("hex"));if(f.value.length/4%1!==0)throw new Error("Decode Error: Input BIP32_DERIVATION value length should be multiple of 4");const d={masterFingerprint:f.value.slice(0,4),pubkey:l,path:"m"};for(const y of e(f.value.length/4-1)){const g=f.value.readUInt32LE(y*4+4),m=!!(g&2147483648),E=g&2147483647;d.path+="/"+E.toString(10)+(m?"'":"")}return d}function o(f){const l=Buffer.from([r]),d=Buffer.concat([l,f.pubkey]),y=f.path.split("/"),g=Buffer.allocUnsafe(y.length*4);f.masterFingerprint.copy(g,0);let m=4;return y.slice(1).forEach(E=>{const _=E.slice(-1)==="'";let S=2147483647&parseInt(_?E.slice(0,-1):E,10);_&&(S+=2147483648),g.writeUInt32LE(S,m),m+=4}),{key:d,value:g}}const c="{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }";function a(f){return Buffer.isBuffer(f.pubkey)&&Buffer.isBuffer(f.masterFingerprint)&&typeof f.path=="string"&&i(f.pubkey)&&f.masterFingerprint.length===4}function u(f,l,d){const y=l.pubkey.toString("hex");return d.has(y)?!1:(d.add(y),f.filter(g=>g.pubkey.equals(l.pubkey)).length===0)}return{decode:s,encode:o,check:a,expected:c,canAddToArray:u}}return Lc.makeConverter=n,Lc}var $c={},Kp;function wA(){if(Kp)return $c;Kp=1,Object.defineProperty($c,"__esModule",{value:!0});function e(t){return n;function n(r){let i;if(t.includes(r.key[0])&&(i=r.key.slice(1),!(i.length===33||i.length===65)||![2,3,4].includes(i[0])))throw new Error("Format Error: invalid pubkey in key 0x"+r.key.toString("hex"));return i}}return $c.makeChecker=e,$c}var Dc={},Gp;function bA(){if(Gp)return Dc;Gp=1,Object.defineProperty(Dc,"__esModule",{value:!0});function e(t){function n(c){if(c.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+c.key.toString("hex"));return c.value}function r(c){return{key:Buffer.from([t]),value:c}}const i="Buffer";function s(c){return Buffer.isBuffer(c)}function o(c,a){return!!c&&!!a&&c.redeemScript===void 0}return{decode:n,encode:r,check:s,expected:i,canAdd:o}}return Dc.makeConverter=e,Dc}var jc={},Wp;function EA(){if(Wp)return jc;Wp=1,Object.defineProperty(jc,"__esModule",{value:!0});const e=ts(),t=zw(),n=i=>i.length===32;function r(i){const s=t.makeConverter(i,n);function o(f){const l=e.decode(f.value),d=e.encodingLength(l),y=s.decode({key:f.key,value:f.value.slice(d+l*32)}),g=new Array(l);for(let m=0,E=d;m<l;m++,E+=32)g[m]=f.value.slice(E,E+32);return Object.assign({},y,{leafHashes:g})}function c(f){const l=s.encode(f),d=e.encodingLength(f.leafHashes.length),y=Buffer.allocUnsafe(d);e.encode(f.leafHashes.length,y);const g=Buffer.concat([y,...f.leafHashes,l.value]);return Object.assign({},l,{value:g})}const a="{ masterFingerprint: Buffer; pubkey: Buffer; path: string; leafHashes: Buffer[]; }";function u(f){return Array.isArray(f.leafHashes)&&f.leafHashes.every(l=>Buffer.isBuffer(l)&&l.length===32)&&s.check(f)}return{decode:o,encode:c,check:u,expected:a,canAddToArray:s.canAddToArray}}return jc.makeConverter=r,jc}var Kc={},Xp;function _A(){if(Xp)return Kc;Xp=1,Object.defineProperty(Kc,"__esModule",{value:!0});function e(t){function n(c){if(c.key[0]!==t||c.key.length!==1)throw new Error("Decode Error: could not decode tapInternalKey with key 0x"+c.key.toString("hex"));if(c.value.length!==32)throw new Error("Decode Error: tapInternalKey not a 32-byte x-only pubkey");return c.value}function r(c){return{key:Buffer.from([t]),value:c}}const i="Buffer";function s(c){return Buffer.isBuffer(c)&&c.length===32}function o(c,a){return!!c&&!!a&&c.tapInternalKey===void 0}return{decode:n,encode:r,check:s,expected:i,canAdd:o}}return Kc.makeConverter=e,Kc}var Gc={},zp;function SA(){if(zp)return Gc;zp=1,Object.defineProperty(Gc,"__esModule",{value:!0});function e(t){function n(c){if(c.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+c.key.toString("hex"));return c.value}function r(c){return{key:Buffer.from([t]),value:c}}const i="Buffer";function s(c){return Buffer.isBuffer(c)}function o(c,a){return!!c&&!!a&&c.witnessScript===void 0}return{decode:n,encode:r,check:s,expected:i,canAdd:o}}return Gc.makeConverter=e,Gc}var Yp;function vh(){if(Yp)return as;Yp=1,Object.defineProperty(as,"__esModule",{value:!0});const e=Mt(),t=iA(),n=sA(),r=oA(),i=cA(),s=aA(),o=uA(),c=fA(),a=lA(),u=hA(),f=dA(),l=pA(),d=yA(),y=gA(),g=mA(),m=zw(),E=wA(),_=bA(),S=EA(),w=_A(),T=SA(),O={unsignedTx:n,globalXpub:t,checkPubkey:E.makeChecker([])};as.globals=O;const A={nonWitnessUtxo:s,partialSig:o,sighashType:a,finalScriptSig:r,finalScriptWitness:i,porCommitment:c,witnessUtxo:y,bip32Derivation:m.makeConverter(e.InputTypes.BIP32_DERIVATION),redeemScript:_.makeConverter(e.InputTypes.REDEEM_SCRIPT),witnessScript:T.makeConverter(e.InputTypes.WITNESS_SCRIPT),checkPubkey:E.makeChecker([e.InputTypes.PARTIAL_SIG,e.InputTypes.BIP32_DERIVATION]),tapKeySig:u,tapScriptSig:d,tapLeafScript:f,tapBip32Derivation:S.makeConverter(e.InputTypes.TAP_BIP32_DERIVATION),tapInternalKey:w.makeConverter(e.InputTypes.TAP_INTERNAL_KEY),tapMerkleRoot:l};as.inputs=A;const R={bip32Derivation:m.makeConverter(e.OutputTypes.BIP32_DERIVATION),redeemScript:_.makeConverter(e.OutputTypes.REDEEM_SCRIPT),witnessScript:T.makeConverter(e.OutputTypes.WITNESS_SCRIPT),checkPubkey:E.makeChecker([e.OutputTypes.BIP32_DERIVATION]),tapBip32Derivation:S.makeConverter(e.OutputTypes.TAP_BIP32_DERIVATION),tapTree:g,tapInternalKey:w.makeConverter(e.OutputTypes.TAP_INTERNAL_KEY)};return as.outputs=R,as}var Zp;function TA(){if(Zp)return cs;Zp=1,Object.defineProperty(cs,"__esModule",{value:!0});const e=vh(),t=Ah(),n=ts(),r=Mt();function i(c,a){let u=0;function f(){const R=n.decode(c,u);u+=n.encodingLength(R);const M=c.slice(u,u+R);return u+=R,M}function l(){const R=c.readUInt32BE(u);return u+=4,R}function d(){const R=c.readUInt8(u);return u+=1,R}function y(){const R=f(),M=f();return{key:R,value:M}}function g(){if(u>=c.length)throw new Error("Format Error: Unexpected End of PSBT");const R=c.readUInt8(u)===0;return R&&u++,R}if(l()!==1886610036)throw new Error("Format Error: Invalid Magic Number");if(d()!==255)throw new Error("Format Error: Magic Number must be followed by 0xff separator");const m=[],E={};for(;!g();){const R=y(),M=R.key.toString("hex");if(E[M])throw new Error("Format Error: Keys must be unique for global keymap: key "+M);E[M]=1,m.push(R)}const _=m.filter(R=>R.key[0]===r.GlobalTypes.UNSIGNED_TX);if(_.length!==1)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const S=a(_[0].value),{inputCount:w,outputCount:T}=S.getInputOutputCounts(),O=[],A=[];for(const R of t.range(w)){const M={},v=[];for(;!g();){const U=y(),V=U.key.toString("hex");if(M[V])throw new Error("Format Error: Keys must be unique for each input: input index "+R+" key "+V);M[V]=1,v.push(U)}O.push(v)}for(const R of t.range(T)){const M={},v=[];for(;!g();){const U=y(),V=U.key.toString("hex");if(M[V])throw new Error("Format Error: Keys must be unique for each output: output index "+R+" key "+V);M[V]=1,v.push(U)}A.push(v)}return o(S,{globalMapKeyVals:m,inputKeyVals:O,outputKeyVals:A})}cs.psbtFromBuffer=i;function s(c,a,u){if(!a.equals(Buffer.from([u])))throw new Error(`Format Error: Invalid ${c} key: ${a.toString("hex")}`)}cs.checkKeyBuffer=s;function o(c,{globalMapKeyVals:a,inputKeyVals:u,outputKeyVals:f}){const l={unsignedTx:c};let d=0;for(const _ of a)switch(_.key[0]){case r.GlobalTypes.UNSIGNED_TX:if(s("global",_.key,r.GlobalTypes.UNSIGNED_TX),d>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");d++;break;case r.GlobalTypes.GLOBAL_XPUB:l.globalXpub===void 0&&(l.globalXpub=[]),l.globalXpub.push(e.globals.globalXpub.decode(_));break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(_)}const y=u.length,g=f.length,m=[],E=[];for(const _ of t.range(y)){const S={};for(const w of u[_])switch(e.inputs.checkPubkey(w),w.key[0]){case r.InputTypes.NON_WITNESS_UTXO:if(s("input",w.key,r.InputTypes.NON_WITNESS_UTXO),S.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");S.nonWitnessUtxo=e.inputs.nonWitnessUtxo.decode(w);break;case r.InputTypes.WITNESS_UTXO:if(s("input",w.key,r.InputTypes.WITNESS_UTXO),S.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");S.witnessUtxo=e.inputs.witnessUtxo.decode(w);break;case r.InputTypes.PARTIAL_SIG:S.partialSig===void 0&&(S.partialSig=[]),S.partialSig.push(e.inputs.partialSig.decode(w));break;case r.InputTypes.SIGHASH_TYPE:if(s("input",w.key,r.InputTypes.SIGHASH_TYPE),S.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");S.sighashType=e.inputs.sighashType.decode(w);break;case r.InputTypes.REDEEM_SCRIPT:if(s("input",w.key,r.InputTypes.REDEEM_SCRIPT),S.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");S.redeemScript=e.inputs.redeemScript.decode(w);break;case r.InputTypes.WITNESS_SCRIPT:if(s("input",w.key,r.InputTypes.WITNESS_SCRIPT),S.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");S.witnessScript=e.inputs.witnessScript.decode(w);break;case r.InputTypes.BIP32_DERIVATION:S.bip32Derivation===void 0&&(S.bip32Derivation=[]),S.bip32Derivation.push(e.inputs.bip32Derivation.decode(w));break;case r.InputTypes.FINAL_SCRIPTSIG:s("input",w.key,r.InputTypes.FINAL_SCRIPTSIG),S.finalScriptSig=e.inputs.finalScriptSig.decode(w);break;case r.InputTypes.FINAL_SCRIPTWITNESS:s("input",w.key,r.InputTypes.FINAL_SCRIPTWITNESS),S.finalScriptWitness=e.inputs.finalScriptWitness.decode(w);break;case r.InputTypes.POR_COMMITMENT:s("input",w.key,r.InputTypes.POR_COMMITMENT),S.porCommitment=e.inputs.porCommitment.decode(w);break;case r.InputTypes.TAP_KEY_SIG:s("input",w.key,r.InputTypes.TAP_KEY_SIG),S.tapKeySig=e.inputs.tapKeySig.decode(w);break;case r.InputTypes.TAP_SCRIPT_SIG:S.tapScriptSig===void 0&&(S.tapScriptSig=[]),S.tapScriptSig.push(e.inputs.tapScriptSig.decode(w));break;case r.InputTypes.TAP_LEAF_SCRIPT:S.tapLeafScript===void 0&&(S.tapLeafScript=[]),S.tapLeafScript.push(e.inputs.tapLeafScript.decode(w));break;case r.InputTypes.TAP_BIP32_DERIVATION:S.tapBip32Derivation===void 0&&(S.tapBip32Derivation=[]),S.tapBip32Derivation.push(e.inputs.tapBip32Derivation.decode(w));break;case r.InputTypes.TAP_INTERNAL_KEY:s("input",w.key,r.InputTypes.TAP_INTERNAL_KEY),S.tapInternalKey=e.inputs.tapInternalKey.decode(w);break;case r.InputTypes.TAP_MERKLE_ROOT:s("input",w.key,r.InputTypes.TAP_MERKLE_ROOT),S.tapMerkleRoot=e.inputs.tapMerkleRoot.decode(w);break;default:S.unknownKeyVals||(S.unknownKeyVals=[]),S.unknownKeyVals.push(w)}m.push(S)}for(const _ of t.range(g)){const S={};for(const w of f[_])switch(e.outputs.checkPubkey(w),w.key[0]){case r.OutputTypes.REDEEM_SCRIPT:if(s("output",w.key,r.OutputTypes.REDEEM_SCRIPT),S.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");S.redeemScript=e.outputs.redeemScript.decode(w);break;case r.OutputTypes.WITNESS_SCRIPT:if(s("output",w.key,r.OutputTypes.WITNESS_SCRIPT),S.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");S.witnessScript=e.outputs.witnessScript.decode(w);break;case r.OutputTypes.BIP32_DERIVATION:S.bip32Derivation===void 0&&(S.bip32Derivation=[]),S.bip32Derivation.push(e.outputs.bip32Derivation.decode(w));break;case r.OutputTypes.TAP_INTERNAL_KEY:s("output",w.key,r.OutputTypes.TAP_INTERNAL_KEY),S.tapInternalKey=e.outputs.tapInternalKey.decode(w);break;case r.OutputTypes.TAP_TREE:s("output",w.key,r.OutputTypes.TAP_TREE),S.tapTree=e.outputs.tapTree.decode(w);break;case r.OutputTypes.TAP_BIP32_DERIVATION:S.tapBip32Derivation===void 0&&(S.tapBip32Derivation=[]),S.tapBip32Derivation.push(e.outputs.tapBip32Derivation.decode(w));break;default:S.unknownKeyVals||(S.unknownKeyVals=[]),S.unknownKeyVals.push(w)}E.push(S)}return{globalMap:l,inputs:m,outputs:E}}return cs.psbtFromKeyVals=o,cs}var wo={},Jp;function xA(){if(Jp)return wo;Jp=1,Object.defineProperty(wo,"__esModule",{value:!0});const e=vh(),t=Ah();function n({globalMap:o,inputs:c,outputs:a}){const{globalKeyVals:u,inputKeyVals:f,outputKeyVals:l}=s({globalMap:o,inputs:c,outputs:a}),d=t.keyValsToBuffer(u),y=_=>_.length===0?[Buffer.from([0])]:_.map(t.keyValsToBuffer),g=y(f),m=y(l),E=Buffer.allocUnsafe(5);return E.writeUIntBE(482972169471,0,5),Buffer.concat([E,d].concat(g,m))}wo.psbtToBuffer=n;const r=(o,c)=>o.key.compare(c.key);function i(o,c){const a=new Set,u=Object.entries(o).reduce((l,[d,y])=>{if(d==="unknownKeyVals")return l;const g=c[d];if(g===void 0)return l;const m=(Array.isArray(y)?y:[y]).map(g.encode);return m.map(_=>_.key.toString("hex")).forEach(_=>{if(a.has(_))throw new Error("Serialize Error: Duplicate key: "+_);a.add(_)}),l.concat(m)},[]),f=o.unknownKeyVals?o.unknownKeyVals.filter(l=>!a.has(l.key.toString("hex"))):[];return u.concat(f).sort(r)}function s({globalMap:o,inputs:c,outputs:a}){return{globalKeyVals:i(o,e.globals),inputKeyVals:c.map(u=>i(u,e.inputs)),outputKeyVals:a.map(u=>i(u,e.outputs))}}return wo.psbtToKeyVals=s,wo}var Qp;function Yw(){return Qp||(Qp=1,(function(e){function t(n){for(var r in n)e.hasOwnProperty(r)||(e[r]=n[r])}Object.defineProperty(e,"__esModule",{value:!0}),t(TA()),t(xA())})(Nf)),Nf}var ey;function AA(){if(ey)return qc;ey=1,Object.defineProperty(qc,"__esModule",{value:!0});const e=Yw();function t(s){const o=s[0],c=e.psbtToKeyVals(o),a=s.slice(1);if(a.length===0)throw new Error("Combine: Nothing to combine");const u=r(o);if(u===void 0)throw new Error("Combine: Self missing transaction");const f=i(c.globalKeyVals),l=c.inputKeyVals.map(i),d=c.outputKeyVals.map(i);for(const y of a){const g=r(y);if(g===void 0||!g.toBuffer().equals(u.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const m=e.psbtToKeyVals(y);i(m.globalKeyVals).forEach(n(f,c.globalKeyVals,m.globalKeyVals)),m.inputKeyVals.map(i).forEach((w,T)=>w.forEach(n(l[T],c.inputKeyVals[T],m.inputKeyVals[T]))),m.outputKeyVals.map(i).forEach((w,T)=>w.forEach(n(d[T],c.outputKeyVals[T],m.outputKeyVals[T])))}return e.psbtFromKeyVals(u,{globalMapKeyVals:c.globalKeyVals,inputKeyVals:c.inputKeyVals,outputKeyVals:c.outputKeyVals})}qc.combine=t;function n(s,o,c){return a=>{if(s.has(a))return;const u=c.filter(f=>f.key.toString("hex")===a)[0];o.push(u),s.add(a)}}function r(s){return s.globalMap.unsignedTx}function i(s){const o=new Set;return s.forEach(c=>{const a=c.key.toString("hex");if(o.has(a))throw new Error("Combine: KeyValue Map keys should be unique");o.add(a)}),o}return qc}var Pf={},ty;function Zw(){return ty||(ty=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=vh();function n(y,g){const m=y[g];if(m===void 0)throw new Error(`No input #${g}`);return m}e.checkForInput=n;function r(y,g){const m=y[g];if(m===void 0)throw new Error(`No output #${g}`);return m}e.checkForOutput=r;function i(y,g,m){if(y.key[0]<m)throw new Error("Use the method for your specific key instead of addUnknownKeyVal*");if(g&&g.filter(E=>E.key.equals(y.key)).length!==0)throw new Error(`Duplicate Key: ${y.key.toString("hex")}`)}e.checkHasKey=i;function s(y){let g=0;return Object.keys(y).forEach(m=>{Number(isNaN(Number(m)))&&g++}),g}e.getEnumLength=s;function o(y,g){let m=!1;if(g.nonWitnessUtxo||g.witnessUtxo){const E=!!g.redeemScript,_=!!g.witnessScript,S=!E||!!g.finalScriptSig,w=!_||!!g.finalScriptWitness,T=!!g.finalScriptSig||!!g.finalScriptWitness;m=S&&w&&T}if(m===!1)throw new Error(`Input #${y} has too much or too little data to clean`)}e.inputCheckUncleanFinalized=o;function c(y,g,m,E){throw new Error(`Data for ${y} key ${g} is incorrect: Expected ${m} and got ${JSON.stringify(E)}`)}function a(y){return(g,m)=>{for(const E of Object.keys(g)){const _=g[E],{canAdd:S,canAddToArray:w,check:T,expected:O}=t[y+"s"][E]||{},A=!!w;if(T)if(A){if(!Array.isArray(_)||m[E]&&!Array.isArray(m[E]))throw new Error(`Key type ${E} must be an array`);_.every(T)||c(y,E,O,_);const R=m[E]||[],M=new Set;if(!_.every(v=>w(R,v,M)))throw new Error("Can not add duplicate data to array");m[E]=R.concat(_)}else{if(T(_)||c(y,E,O,_),!S(m,_))throw new Error(`Can not add duplicate data to ${y}`);m[E]=_}}}}e.updateGlobal=a("global"),e.updateInput=a("input"),e.updateOutput=a("output");function u(y,g){const m=y.length-1,E=n(y,m);e.updateInput(g,E)}e.addInputAttributes=u;function f(y,g){const m=y.length-1,E=r(y,m);e.updateOutput(g,E)}e.addOutputAttributes=f;function l(y,g){if(!Buffer.isBuffer(g)||g.length<4)throw new Error("Set Version: Invalid Transaction");return g.writeUInt32LE(y,0),g}e.defaultVersionSetter=l;function d(y,g){if(!Buffer.isBuffer(g)||g.length<4)throw new Error("Set Locktime: Invalid Transaction");return g.writeUInt32LE(y,g.length-4),g}e.defaultLocktimeSetter=d})(Pf)),Pf}var ny;function vA(){if(ny)return Mc;ny=1,Object.defineProperty(Mc,"__esModule",{value:!0});const e=AA(),t=Yw(),n=Mt(),r=Zw();class i{constructor(o){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:o}}static fromBase64(o,c){const a=Buffer.from(o,"base64");return this.fromBuffer(a,c)}static fromHex(o,c){const a=Buffer.from(o,"hex");return this.fromBuffer(a,c)}static fromBuffer(o,c){const a=t.psbtFromBuffer(o,c),u=new this(a.globalMap.unsignedTx);return Object.assign(u,a),u}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return t.psbtToBuffer(this)}updateGlobal(o){return r.updateGlobal(o,this.globalMap),this}updateInput(o,c){const a=r.checkForInput(this.inputs,o);return r.updateInput(c,a),this}updateOutput(o,c){const a=r.checkForOutput(this.outputs,o);return r.updateOutput(c,a),this}addUnknownKeyValToGlobal(o){return r.checkHasKey(o,this.globalMap.unknownKeyVals,r.getEnumLength(n.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(o),this}addUnknownKeyValToInput(o,c){const a=r.checkForInput(this.inputs,o);return r.checkHasKey(c,a.unknownKeyVals,r.getEnumLength(n.InputTypes)),a.unknownKeyVals||(a.unknownKeyVals=[]),a.unknownKeyVals.push(c),this}addUnknownKeyValToOutput(o,c){const a=r.checkForOutput(this.outputs,o);return r.checkHasKey(c,a.unknownKeyVals,r.getEnumLength(n.OutputTypes)),a.unknownKeyVals||(a.unknownKeyVals=[]),a.unknownKeyVals.push(c),this}addInput(o){this.globalMap.unsignedTx.addInput(o),this.inputs.push({unknownKeyVals:[]});const c=o.unknownKeyVals||[],a=this.inputs.length-1;if(!Array.isArray(c))throw new Error("unknownKeyVals must be an Array");return c.forEach(u=>this.addUnknownKeyValToInput(a,u)),r.addInputAttributes(this.inputs,o),this}addOutput(o){this.globalMap.unsignedTx.addOutput(o),this.outputs.push({unknownKeyVals:[]});const c=o.unknownKeyVals||[],a=this.outputs.length-1;if(!Array.isArray(c))throw new Error("unknownKeyVals must be an Array");return c.forEach(u=>this.addUnknownKeyValToOutput(a,u)),r.addOutputAttributes(this.outputs,o),this}clearFinalizedInput(o){const c=r.checkForInput(this.inputs,o);r.inputCheckUncleanFinalized(o,c);for(const a of Object.keys(c))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(a)||delete c[a];return this}combine(...o){const c=e.combine([this].concat(o));return Object.assign(this,c),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}}return Mc.Psbt=i,Mc}var Qe={},ze={},ry;function dl(){if(ry)return ze;ry=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.signatureBlocksAction=ze.checkInputForSig=ze.pubkeyInScript=ze.pubkeyPositionInScript=ze.witnessStackToScriptWitness=ze.isP2TR=ze.isP2SHScript=ze.isP2WSHScript=ze.isP2WPKH=ze.isP2PKH=ze.isP2PK=ze.isP2MS=void 0;const e=ts(),t=nn(),n=_c(),r=Pr(),i=Ec();function s(y){return g=>{try{return y({output:g}),!0}catch{return!1}}}ze.isP2MS=s(i.p2ms),ze.isP2PK=s(i.p2pk),ze.isP2PKH=s(i.p2pkh),ze.isP2WPKH=s(i.p2wpkh),ze.isP2WSHScript=s(i.p2wsh),ze.isP2SHScript=s(i.p2sh),ze.isP2TR=s(i.p2tr);function o(y){let g=Buffer.allocUnsafe(0);function m(w){g=Buffer.concat([g,Buffer.from(w)])}function E(w){const T=g.length,O=e.encodingLength(w);g=Buffer.concat([g,Buffer.allocUnsafe(O)]),e.encode(w,g,T)}function _(w){E(w.length),m(w)}function S(w){E(w.length),w.forEach(_)}return S(y),g}ze.witnessStackToScriptWitness=o;function c(y,g){const m=(0,r.hash160)(y),E=y.slice(1,33),_=t.decompile(g);if(_===null)throw new Error("Unknown script error");return _.findIndex(S=>typeof S=="number"?!1:S.equals(y)||S.equals(m)||S.equals(E))}ze.pubkeyPositionInScript=c;function a(y,g){return c(y,g)!==-1}ze.pubkeyInScript=a;function u(y,g){return l(y).some(E=>f(E,t.signature.decode,g))}ze.checkInputForSig=u;function f(y,g,m){const{hashType:E}=g(y),_=[];switch(E&n.Transaction.SIGHASH_ANYONECANPAY&&_.push("addInput"),E&31){case n.Transaction.SIGHASH_ALL:break;case n.Transaction.SIGHASH_SINGLE:case n.Transaction.SIGHASH_NONE:_.push("addOutput"),_.push("setInputSequence");break}return _.indexOf(m)===-1}ze.signatureBlocksAction=f;function l(y){let g=[];if((y.partialSig||[]).length===0){if(!y.finalScriptSig&&!y.finalScriptWitness)return[];g=d(y)}else g=y.partialSig;return g.map(m=>m.signature)}function d(y){const g=y.finalScriptSig?t.decompile(y.finalScriptSig)||[]:[],m=y.finalScriptWitness?t.decompile(y.finalScriptWitness)||[]:[];return g.concat(m).filter(E=>Buffer.isBuffer(E)&&t.isCanonicalScriptSignature(E)).map(E=>({signature:E}))}return ze}var iy;function IA(){if(iy)return Qe;iy=1,Object.defineProperty(Qe,"__esModule",{value:!0}),Qe.checkTaprootInputForSigs=Qe.tapTreeFromList=Qe.tapTreeToList=Qe.tweakInternalPubKey=Qe.checkTaprootOutputFields=Qe.checkTaprootInputFields=Qe.isTaprootOutput=Qe.isTaprootInput=Qe.serializeTaprootSignature=Qe.tapScriptFinalizer=Qe.toXOnly=void 0;const e=Xt(),t=_c(),n=dl(),r=Th(),i=Ec(),s=dl(),o=x=>x.length===32?x:x.slice(1,33);Qe.toXOnly=o;function c(x,B,q){const N=P(B,x,q);try{const G=H(B,N).concat(N.script).concat(N.controlBlock);return{finalScriptWitness:(0,n.witnessStackToScriptWitness)(G)}}catch(L){throw new Error(`Can not finalize taproot input #${x}: ${L}`)}}Qe.tapScriptFinalizer=c;function a(x,B){const q=B?Buffer.from([B]):Buffer.from([]);return Buffer.concat([x,q])}Qe.serializeTaprootSignature=a;function u(x){return x&&!!(x.tapInternalKey||x.tapMerkleRoot||x.tapLeafScript&&x.tapLeafScript.length||x.tapBip32Derivation&&x.tapBip32Derivation.length||x.witnessUtxo&&(0,n.isP2TR)(x.witnessUtxo.script))}Qe.isTaprootInput=u;function f(x,B){return x&&!!(x.tapInternalKey||x.tapTree||x.tapBip32Derivation&&x.tapBip32Derivation.length||B&&(0,n.isP2TR)(B))}Qe.isTaprootOutput=f;function l(x,B,q){v(x,B,q),V(x,B,q)}Qe.checkTaprootInputFields=l;function d(x,B,q){U(x,B,q),y(x,B)}Qe.checkTaprootOutputFields=d;function y(x,B){if(!B.tapTree&&!B.tapInternalKey)return;const q=B.tapInternalKey||x.tapInternalKey,N=B.tapTree||x.tapTree;if(q){const{script:L}=x,G=g(q,N);if(L&&!L.equals(G))throw new Error("Error adding output. Script or address missmatch.")}}function g(x,B){const q=B&&_(B.leaves),{output:N}=(0,i.p2tr)({internalPubkey:x,scriptTree:q});return N}function m(x,B){const q=B.tapInternalKey,N=q&&(0,r.tweakKey)(q,B.tapMerkleRoot);if(!N)throw new Error(`Cannot tweak tap internal key for input #${x}. Public key: ${q&&q.toString("hex")}`);return N.x}Qe.tweakInternalPubKey=m;function E(x){if(!(0,e.isTaptree)(x))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return A(x)}Qe.tapTreeToList=E;function _(x=[]){return x.length===1&&x[0].depth===0?{output:x[0].script,version:x[0].leafVersion}:R(x)}Qe.tapTreeFromList=_;function S(x,B){return T(x).some(N=>(0,s.signatureBlocksAction)(N,w,B))}Qe.checkTaprootInputForSigs=S;function w(x){return{signature:x.slice(0,64),hashType:x.slice(64)[0]||t.Transaction.SIGHASH_DEFAULT}}function T(x){const B=[];if(x.tapKeySig&&B.push(x.tapKeySig),x.tapScriptSig&&B.push(...x.tapScriptSig.map(q=>q.signature)),!B.length){const q=O(x.finalScriptWitness);q&&B.push(q)}return B}function O(x){if(!x)return;const B=x.slice(2);if(B.length===64||B.length===65)return B}function A(x,B=[],q=0){if(q>r.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return x?(0,e.isTapleaf)(x)?(B.push({depth:q,leafVersion:x.version||r.LEAF_VERSION_TAPSCRIPT,script:x.output}),B):(x[0]&&A(x[0],B,q+1),x[1]&&A(x[1],B,q+1),B):[]}function R(x){let B;for(const q of x)if(B=M(q,B),!B)throw new Error("No room left to insert tapleaf in tree");return B}function M(x,B,q=0){if(q>r.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(x.depth===q)return B?void 0:{output:x.script,version:x.leafVersion};if((0,e.isTapleaf)(B))return;const N=M(x,B&&B[0],q+1);if(N)return[N,B&&B[1]];const L=M(x,B&&B[1],q+1);if(L)return[B&&B[0],L]}function v(x,B,q){const N=u(x)&&F(B),L=F(x)&&u(B),G=x===B&&u(B)&&F(B);if(N||L||G)throw new Error(`Invalid arguments for Psbt.${q}. Cannot use both taproot and non-taproot fields.`)}function U(x,B,q){const N=f(x)&&F(B),L=F(x)&&f(B),G=x===B&&f(B)&&F(B);if(N||L||G)throw new Error(`Invalid arguments for Psbt.${q}. Cannot use both taproot and non-taproot fields.`)}function V(x,B,q){if(B.tapMerkleRoot){const N=(B.tapLeafScript||[]).every(G=>K(G,B.tapMerkleRoot)),L=(x.tapLeafScript||[]).every(G=>K(G,B.tapMerkleRoot));if(!N||!L)throw new Error(`Invalid arguments for Psbt.${q}. Tapleaf not part of taptree.`)}else if(x.tapMerkleRoot&&!(B.tapLeafScript||[]).every(L=>K(L,x.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${q}. Tapleaf not part of taptree.`)}function K(x,B){if(!B)return!0;const q=(0,r.tapleafHash)({output:x.script,version:x.leafVersion});return(0,r.rootHashFromPath)(x.controlBlock,q).equals(B)}function H(x,B){const q=(0,r.tapleafHash)({output:B.script,version:B.leafVersion});return(x.tapScriptSig||[]).filter(N=>N.leafHash.equals(q)).map(N=>$(B.script,N)).sort((N,L)=>L.positionInScript-N.positionInScript).map(N=>N.signature)}function $(x,B){return Object.assign({positionInScript:(0,n.pubkeyPositionInScript)(B.pubkey,x)},B)}function P(x,B,q){if(!x.tapScriptSig||!x.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${B}. No tapleaf script signature provided.`);const N=(x.tapLeafScript||[]).sort((L,G)=>L.controlBlock.length-G.controlBlock.length).find(L=>D(L,x.tapScriptSig,q));if(!N)throw new Error(`Can not finalize taproot input #${B}. Signature for tapleaf script not found.`);return N}function D(x,B,q){const N=(0,r.tapleafHash)({output:x.script,version:x.leafVersion});return(!q||q.equals(N))&&B.find(G=>G.leafHash.equals(N))!==void 0}function F(x){return x&&!!(x.redeemScript||x.witnessScript||x.bip32Derivation&&x.bip32Derivation.length)}return Qe}var sy;function OA(){if(sy)return mo;sy=1,Object.defineProperty(mo,"__esModule",{value:!0}),mo.Psbt=void 0;const e=vA(),t=ts(),n=Zw(),r=xh(),i=Eu(),s=Wn(),o=Ec(),c=Th(),a=nn(),u=_c(),f=IA(),l=dl(),d={network:s.bitcoin,maximumFeeRate:5e3};class y{static fromBase64(h,b={}){const I=Buffer.from(h,"base64");return this.fromBuffer(I,b)}static fromHex(h,b={}){const I=Buffer.from(h,"hex");return this.fromBuffer(I,b)}static fromBuffer(h,b={}){const I=e.Psbt.fromBuffer(h,g),C=new y(b,I);return V(C.__CACHE.__TX,C.__CACHE),C}constructor(h={},b=new e.Psbt(new m)){this.data=b,this.opts=Object.assign({},d,h),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},this.data.inputs.length===0&&this.setVersion(2);const I=(C,j,W,ie)=>Object.defineProperty(C,j,{enumerable:W,writable:ie});I(this,"__CACHE",!1,!0),I(this,"opts",!1,!0)}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(h){this.setVersion(h)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(h){this.setLocktime(h)}get txInputs(){return this.__CACHE.__TX.ins.map(h=>({hash:(0,i.cloneBuffer)(h.hash),index:h.index,sequence:h.sequence}))}get txOutputs(){return this.__CACHE.__TX.outs.map(h=>{let b;try{b=(0,r.fromOutputScript)(h.script,this.opts.network)}catch{}return{script:(0,i.cloneBuffer)(h.script),value:h.value,address:b}})}combine(...h){return this.data.combine(...h.map(b=>b.data)),this}clone(){const h=y.fromBuffer(this.data.toBuffer());return h.opts=JSON.parse(JSON.stringify(this.opts)),h}setMaximumFeeRate(h){O(h),this.opts.maximumFeeRate=h}setVersion(h){O(h),R(this.data.inputs,"setVersion");const b=this.__CACHE;return b.__TX.version=h,b.__EXTRACTED_TX=void 0,this}setLocktime(h){O(h),R(this.data.inputs,"setLocktime");const b=this.__CACHE;return b.__TX.locktime=h,b.__EXTRACTED_TX=void 0,this}setInputSequence(h,b){O(b),R(this.data.inputs,"setInputSequence");const I=this.__CACHE;if(I.__TX.ins.length<=h)throw new Error("Input index too high");return I.__TX.ins[h].sequence=b,I.__EXTRACTED_TX=void 0,this}addInputs(h){return h.forEach(b=>this.addInput(b)),this}addInput(h){if(arguments.length>1||!h||h.hash===void 0||h.index===void 0)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");(0,f.checkTaprootInputFields)(h,h,"addInput"),R(this.data.inputs,"addInput"),h.witnessScript&&ne(h.witnessScript);const b=this.__CACHE;this.data.addInput(h);const I=b.__TX.ins[b.__TX.ins.length-1];K(b,I);const C=this.data.inputs.length-1,j=this.data.inputs[C];return j.nonWitnessUtxo&&ye(this.__CACHE,j,C),b.__FEE=void 0,b.__FEE_RATE=void 0,b.__EXTRACTED_TX=void 0,this}addOutputs(h){return h.forEach(b=>this.addOutput(b)),this}addOutput(h){if(arguments.length>1||!h||h.value===void 0||h.address===void 0&&h.script===void 0)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");R(this.data.inputs,"addOutput");const{address:b}=h;if(typeof b=="string"){const{network:C}=this.opts,j=(0,r.toOutputScript)(b,C);h=Object.assign({},h,{script:j})}(0,f.checkTaprootOutputFields)(h,h,"addOutput");const I=this.__CACHE;return this.data.addOutput(h),I.__FEE=void 0,I.__FEE_RATE=void 0,I.__EXTRACTED_TX=void 0,this}extractTransaction(h){if(!this.data.inputs.every(w))throw new Error("Not finalized");const b=this.__CACHE;if(h||A(this,b,this.opts),b.__EXTRACTED_TX)return b.__EXTRACTED_TX;const I=b.__TX.clone();return J(this.data.inputs,I,b,!0),I}getFeeRate(){return D("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return D("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return(0,n.checkForInput)(this.data.inputs,0),k(this.data.inputs.length).forEach(h=>this.finalizeInput(h)),this}finalizeInput(h,b){const I=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(I)?this._finalizeTaprootInput(h,I,void 0,b):this._finalizeInput(h,I,b)}finalizeTaprootInput(h,b,I=f.tapScriptFinalizer){const C=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(C))return this._finalizeTaprootInput(h,C,b,I);throw new Error(`Cannot finalize input #${h}. Not Taproot.`)}_finalizeInput(h,b,I=F){const{script:C,isP2SH:j,isP2WSH:W,isSegwit:ie}=ue(h,b,this.__CACHE);if(!C)throw new Error(`No script found for input #${h}`);M(b);const{finalScriptSig:Q,finalScriptWitness:fe}=I(h,b,C,ie,j,W);if(Q&&this.data.updateInput(h,{finalScriptSig:Q}),fe&&this.data.updateInput(h,{finalScriptWitness:fe}),!Q&&!fe)throw new Error(`Unknown error finalizing input #${h}`);return this.data.clearFinalizedInput(h),this}_finalizeTaprootInput(h,b,I,C=f.tapScriptFinalizer){if(!b.witnessUtxo)throw new Error(`Cannot finalize input #${h}. Missing withness utxo.`);if(b.tapKeySig){const j=o.p2tr({output:b.witnessUtxo.script,signature:b.tapKeySig}),W=(0,l.witnessStackToScriptWitness)(j.witness);this.data.updateInput(h,{finalScriptWitness:W})}else{const{finalScriptWitness:j}=C(h,b,I);this.data.updateInput(h,{finalScriptWitness:j})}return this.data.clearFinalizedInput(h),this}getInputType(h){const b=(0,n.checkForInput)(this.data.inputs,h),I=Ae(h,b,this.__CACHE),C=oe(I,h,"input",b.redeemScript||It(b.finalScriptSig),b.witnessScript||Oe(b.finalScriptWitness)),j=C.type==="raw"?"":C.type+"-",W=re(C.meaningfulScript);return j+W}inputHasPubkey(h,b){const I=(0,n.checkForInput)(this.data.inputs,h);return tt(b,I,h,this.__CACHE)}inputHasHDKey(h,b){const I=(0,n.checkForInput)(this.data.inputs,h),C=T(b);return!!I.bip32Derivation&&I.bip32Derivation.some(C)}outputHasPubkey(h,b){const I=(0,n.checkForOutput)(this.data.outputs,h);return ut(b,I,h,this.__CACHE)}outputHasHDKey(h,b){const I=(0,n.checkForOutput)(this.data.outputs,h),C=T(b);return!!I.bip32Derivation&&I.bip32Derivation.some(C)}validateSignaturesOfAllInputs(h){return(0,n.checkForInput)(this.data.inputs,0),k(this.data.inputs.length).map(I=>this.validateSignaturesOfInput(I,h)).reduce((I,C)=>C===!0&&I,!0)}validateSignaturesOfInput(h,b,I){const C=this.data.inputs[h];return(0,f.isTaprootInput)(C)?this.validateSignaturesOfTaprootInput(h,b,I):this._validateSignaturesOfInput(h,b,I)}_validateSignaturesOfInput(h,b,I){const C=this.data.inputs[h],j=(C||{}).partialSig;if(!C||!j||j.length<1)throw new Error("No signatures to validate");if(typeof b!="function")throw new Error("Need validator function to validate signatures");const W=I?j.filter(Ne=>Ne.pubkey.equals(I)):j;if(W.length<1)throw new Error("No signatures for this pubkey");const ie=[];let Q,fe,he;for(const Ne of W){const Pe=a.signature.decode(Ne.signature),{hash:nt,script:je}=he!==Pe.hashType?q(h,Object.assign({},C,{sighashType:Pe.hashType}),this.__CACHE,!0):{hash:Q,script:fe};he=Pe.hashType,Q=nt,fe=je,v(Ne.pubkey,je,"verify"),ie.push(b(Ne.pubkey,nt,Pe.signature))}return ie.every(Ne=>Ne===!0)}validateSignaturesOfTaprootInput(h,b,I){const C=this.data.inputs[h],j=(C||{}).tapKeySig,W=(C||{}).tapScriptSig;if(!C&&!j&&!(W&&!W.length))throw new Error("No signatures to validate");if(typeof b!="function")throw new Error("Need validator function to validate signatures");I=I&&(0,f.toXOnly)(I);const ie=I?X(h,C,this.data.inputs,I,this.__CACHE):N(h,C,this.data.inputs,this.__CACHE);if(!ie.length)throw new Error("No signatures for this pubkey");const Q=ie.find(he=>!he.leafHash);let fe=0;if(j&&Q){if(!b(Q.pubkey,Q.hash,G(j)))return!1;fe++}if(W)for(const he of W){const Ne=ie.find(Pe=>he.pubkey.equals(Pe.pubkey));if(Ne){if(!b(he.pubkey,Ne.hash,G(he.signature)))return!1;fe++}}return fe>0}signAllInputsHD(h,b=[u.Transaction.SIGHASH_ALL]){if(!h||!h.publicKey||!h.fingerprint)throw new Error("Need HDSigner to sign input");const I=[];for(const C of k(this.data.inputs.length))try{this.signInputHD(C,h,b),I.push(!0)}catch{I.push(!1)}if(I.every(C=>C===!1))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(h,b=[u.Transaction.SIGHASH_ALL]){return new Promise((I,C)=>{if(!h||!h.publicKey||!h.fingerprint)return C(new Error("Need HDSigner to sign input"));const j=[],W=[];for(const ie of k(this.data.inputs.length))W.push(this.signInputHDAsync(ie,h,b).then(()=>{j.push(!0)},()=>{j.push(!1)}));return Promise.all(W).then(()=>{if(j.every(ie=>ie===!1))return C(new Error("No inputs were signed"));I()})})}signInputHD(h,b,I=[u.Transaction.SIGHASH_ALL]){if(!b||!b.publicKey||!b.fingerprint)throw new Error("Need HDSigner to sign input");return te(h,this.data.inputs,b).forEach(j=>this.signInput(h,j,I)),this}signInputHDAsync(h,b,I=[u.Transaction.SIGHASH_ALL]){return new Promise((C,j)=>{if(!b||!b.publicKey||!b.fingerprint)return j(new Error("Need HDSigner to sign input"));const ie=te(h,this.data.inputs,b).map(Q=>this.signInputAsync(h,Q,I));return Promise.all(ie).then(()=>{C()}).catch(j)})}signAllInputs(h,b){if(!h||!h.publicKey)throw new Error("Need Signer to sign input");const I=[];for(const C of k(this.data.inputs.length))try{this.signInput(C,h,b),I.push(!0)}catch{I.push(!1)}if(I.every(C=>C===!1))throw new Error("No inputs were signed");return this}signAllInputsAsync(h,b){return new Promise((I,C)=>{if(!h||!h.publicKey)return C(new Error("Need Signer to sign input"));const j=[],W=[];for(const[ie]of this.data.inputs.entries())W.push(this.signInputAsync(ie,h,b).then(()=>{j.push(!0)},()=>{j.push(!1)}));return Promise.all(W).then(()=>{if(j.every(ie=>ie===!1))return C(new Error("No inputs were signed"));I()})})}signInput(h,b,I){if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const C=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(C)?this._signTaprootInput(h,C,b,void 0,I):this._signInput(h,b,I)}signTaprootInput(h,b,I,C){if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const j=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(j))return this._signTaprootInput(h,j,b,I,C);throw new Error(`Input #${h} is not of type Taproot.`)}_signInput(h,b,I=[u.Transaction.SIGHASH_ALL]){const{hash:C,sighashType:j}=B(this.data.inputs,h,b.publicKey,this.__CACHE,I),W=[{pubkey:b.publicKey,signature:a.signature.encode(b.sign(C),j)}];return this.data.updateInput(h,{partialSig:W}),this}_signTaprootInput(h,b,I,C,j=[u.Transaction.SIGHASH_DEFAULT]){const W=this.checkTaprootHashesForSig(h,b,I,C,j),ie=W.filter(fe=>!fe.leafHash).map(fe=>(0,f.serializeTaprootSignature)(I.signSchnorr(fe.hash),b.sighashType))[0],Q=W.filter(fe=>!!fe.leafHash).map(fe=>({pubkey:(0,f.toXOnly)(I.publicKey),signature:(0,f.serializeTaprootSignature)(I.signSchnorr(fe.hash),b.sighashType),leafHash:fe.leafHash}));return ie&&this.data.updateInput(h,{tapKeySig:ie}),Q.length&&this.data.updateInput(h,{tapScriptSig:Q}),this}signInputAsync(h,b,I){return Promise.resolve().then(()=>{if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const C=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(C)?this._signTaprootInputAsync(h,C,b,void 0,I):this._signInputAsync(h,b,I)})}signTaprootInputAsync(h,b,I,C){return Promise.resolve().then(()=>{if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const j=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(j))return this._signTaprootInputAsync(h,j,b,I,C);throw new Error(`Input #${h} is not of type Taproot.`)})}_signInputAsync(h,b,I=[u.Transaction.SIGHASH_ALL]){const{hash:C,sighashType:j}=B(this.data.inputs,h,b.publicKey,this.__CACHE,I);return Promise.resolve(b.sign(C)).then(W=>{const ie=[{pubkey:b.publicKey,signature:a.signature.encode(W,j)}];this.data.updateInput(h,{partialSig:ie})})}async _signTaprootInputAsync(h,b,I,C,j=[u.Transaction.SIGHASH_DEFAULT]){const W=this.checkTaprootHashesForSig(h,b,I,C,j),ie=[],Q=W.filter(he=>!he.leafHash)[0];if(Q){const he=Promise.resolve(I.signSchnorr(Q.hash)).then(Ne=>({tapKeySig:(0,f.serializeTaprootSignature)(Ne,b.sighashType)}));ie.push(he)}const fe=W.filter(he=>!!he.leafHash);if(fe.length){const he=fe.map(Ne=>Promise.resolve(I.signSchnorr(Ne.hash)).then(Pe=>({tapScriptSig:[{pubkey:(0,f.toXOnly)(I.publicKey),signature:(0,f.serializeTaprootSignature)(Pe,b.sighashType),leafHash:Ne.leafHash}]})));ie.push(...he)}return Promise.all(ie).then(he=>{he.forEach(Ne=>this.data.updateInput(h,Ne))})}checkTaprootHashesForSig(h,b,I,C,j){if(typeof I.signSchnorr!="function")throw new Error(`Need Schnorr Signer to sign taproot input #${h}.`);const W=X(h,b,this.data.inputs,I.publicKey,this.__CACHE,C,j);if(!W||!W.length)throw new Error(`Can not sign for input #${h} with the key ${I.publicKey.toString("hex")}`);return W}toBuffer(){return _(this.__CACHE),this.data.toBuffer()}toHex(){return _(this.__CACHE),this.data.toHex()}toBase64(){return _(this.__CACHE),this.data.toBase64()}updateGlobal(h){return this.data.updateGlobal(h),this}updateInput(h,b){return b.witnessScript&&ne(b.witnessScript),(0,f.checkTaprootInputFields)(this.data.inputs[h],b,"updateInput"),this.data.updateInput(h,b),b.nonWitnessUtxo&&ye(this.__CACHE,this.data.inputs[h],h),this}updateOutput(h,b){const I=this.data.outputs[h];return(0,f.checkTaprootOutputFields)(I,b,"updateOutput"),this.data.updateOutput(h,b),this}addUnknownKeyValToGlobal(h){return this.data.addUnknownKeyValToGlobal(h),this}addUnknownKeyValToInput(h,b){return this.data.addUnknownKeyValToInput(h,b),this}addUnknownKeyValToOutput(h,b){return this.data.addUnknownKeyValToOutput(h,b),this}clearFinalizedInput(h){return this.data.clearFinalizedInput(h),this}}mo.Psbt=y;const g=p=>new m(p);class m{constructor(h=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=u.Transaction.fromBuffer(h),U(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(h){if(h.hash===void 0||h.index===void 0||!Buffer.isBuffer(h.hash)&&typeof h.hash!="string"||typeof h.index!="number")throw new Error("Error adding input.");const b=typeof h.hash=="string"?(0,i.reverseBuffer)(Buffer.from(h.hash,"hex")):h.hash;this.tx.addInput(b,h.index,h.sequence)}addOutput(h){if(h.script===void 0||h.value===void 0||!Buffer.isBuffer(h.script)||typeof h.value!="number")throw new Error("Error adding output.");this.tx.addOutput(h.script,h.value)}toBuffer(){return this.tx.toBuffer()}}function E(p,h,b){switch(b){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return S(1,p.partialSig);case"multisig":const I=o.p2ms({output:h});return S(I.m,p.partialSig,I.pubkeys);default:return!1}}function _(p){if(p.__UNSAFE_SIGN_NONSEGWIT!==!1)throw new Error("Not BIP174 compliant, can not export")}function S(p,h,b){if(!h)return!1;let I;if(b?I=b.map(C=>{const j=mn(C);return h.find(W=>W.pubkey.equals(j))}).filter(C=>!!C):I=h,I.length>p)throw new Error("Too many signatures");return I.length===p}function w(p){return!!p.finalScriptSig||!!p.finalScriptWitness}function T(p){return h=>!(!h.masterFingerprint.equals(p.fingerprint)||!p.derivePath(h.path).publicKey.equals(h.pubkey))}function O(p){if(typeof p!="number"||p!==Math.floor(p)||p>4294967295||p<0)throw new Error("Invalid 32 bit integer")}function A(p,h,b){const I=h.__FEE_RATE||p.getFeeRate(),C=h.__EXTRACTED_TX.virtualSize(),j=I*C;if(I>=b.maximumFeeRate)throw new Error(`Warning: You are paying around ${(j/1e8).toFixed(8)} in fees, which is ${I} satoshi per byte for a transaction with a VSize of ${C} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}function R(p,h){p.forEach(b=>{if((0,f.isTaprootInput)(b)?(0,f.checkTaprootInputForSigs)(b,h):(0,l.checkInputForSig)(b,h))throw new Error("Can not modify transaction, signatures exist.")})}function M(p){if(!p.sighashType||!p.partialSig)return;const{partialSig:h,sighashType:b}=p;h.forEach(I=>{const{hashType:C}=a.signature.decode(I.signature);if(b!==C)throw new Error("Signature sighash does not match input sighash type")})}function v(p,h,b){if(!(0,l.pubkeyInScript)(p,h))throw new Error(`Can not ${b} for this input with the key ${p.toString("hex")}`)}function U(p){if(!p.ins.every(b=>b.script&&b.script.length===0&&b.witness&&b.witness.length===0))throw new Error("Format Error: Transaction ScriptSigs are not empty")}function V(p,h){p.ins.forEach(b=>{K(h,b)})}function K(p,h){const b=(0,i.reverseBuffer)(Buffer.from(h.hash)).toString("hex")+":"+h.index;if(p.__TX_IN_CACHE[b])throw new Error("Duplicate input detected.");p.__TX_IN_CACHE[b]=1}function H(p,h){return(b,I,C,j)=>{const W=p({redeem:{output:C}}).output;if(!I.equals(W))throw new Error(`${h} for ${j} #${b} doesn't match the scriptPubKey in the prevout`)}}const $=H(o.p2sh,"Redeem script"),P=H(o.p2wsh,"Witness script");function D(p,h,b,I){if(!b.every(w))throw new Error(`PSBT must be finalized to calculate ${h}`);if(p==="__FEE_RATE"&&I.__FEE_RATE)return I.__FEE_RATE;if(p==="__FEE"&&I.__FEE)return I.__FEE;let C,j=!0;if(I.__EXTRACTED_TX?(C=I.__EXTRACTED_TX,j=!1):C=I.__TX.clone(),J(b,C,I,j),p==="__FEE_RATE")return I.__FEE_RATE;if(p==="__FEE")return I.__FEE}function F(p,h,b,I,C,j){const W=re(b);if(!E(h,b,W))throw new Error(`Can not finalize input #${p}`);return x(b,W,h.partialSig,I,C,j)}function x(p,h,b,I,C,j){let W,ie;const Q=ce(p,h,b),fe=j?o.p2wsh({redeem:Q}):null,he=C?o.p2sh({redeem:fe||Q}):null;return I?(fe?ie=(0,l.witnessStackToScriptWitness)(fe.witness):ie=(0,l.witnessStackToScriptWitness)(Q.witness),he&&(W=he.input)):he?W=he.input:W=Q.input,{finalScriptSig:W,finalScriptWitness:ie}}function B(p,h,b,I,C){const j=(0,n.checkForInput)(p,h),{hash:W,sighashType:ie,script:Q}=q(h,j,I,!1,C);return v(b,Q,"sign"),{hash:W,sighashType:ie}}function q(p,h,b,I,C){const j=b.__TX,W=h.sighashType||u.Transaction.SIGHASH_ALL;Y(W,C);let ie,Q;if(h.nonWitnessUtxo){const Ne=le(b,h,p),Pe=j.ins[p].hash,nt=Ne.getHash();if(!Pe.equals(nt))throw new Error(`Non-witness UTXO hash for input #${p} doesn't match the hash specified in the prevout`);const je=j.ins[p].index;Q=Ne.outs[je]}else if(h.witnessUtxo)Q=h.witnessUtxo;else throw new Error("Need a Utxo input item for signing");const{meaningfulScript:fe,type:he}=oe(Q.script,p,"input",h.redeemScript,h.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(he)>=0)ie=j.hashForWitnessV0(p,fe,Q.value,W);else if((0,l.isP2WPKH)(fe)){const Ne=o.p2pkh({hash:fe.slice(2)}).output;ie=j.hashForWitnessV0(p,Ne,Q.value,W)}else{if(h.nonWitnessUtxo===void 0&&b.__UNSAFE_SIGN_NONSEGWIT===!1)throw new Error(`Input #${p} has witnessUtxo but non-segwit script: ${fe.toString("hex")}`);!I&&b.__UNSAFE_SIGN_NONSEGWIT!==!1&&console.warn(`Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as Psbt's predecessor (TransactionBuilder - now removed) when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.
73
+ `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239}),ar}var gf={},so={},mf={},ur={},$0;function Kw(){if($0)return ur;$0=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.encode=ur.decode=ur.check=void 0;function e(r){if(r.length<8||r.length>72||r[0]!==48||r[1]!==r.length-2||r[2]!==2)return!1;const i=r[3];if(i===0||5+i>=r.length||r[4+i]!==2)return!1;const s=r[5+i];return!(s===0||6+i+s!==r.length||r[4]&128||i>1&&r[4]===0&&!(r[5]&128)||r[i+6]&128||s>1&&r[i+6]===0&&!(r[i+7]&128))}ur.check=e;function t(r){if(r.length<8)throw new Error("DER sequence length is too short");if(r.length>72)throw new Error("DER sequence length is too long");if(r[0]!==48)throw new Error("Expected DER sequence");if(r[1]!==r.length-2)throw new Error("DER sequence length is invalid");if(r[2]!==2)throw new Error("Expected DER integer");const i=r[3];if(i===0)throw new Error("R length is zero");if(5+i>=r.length)throw new Error("R length is too long");if(r[4+i]!==2)throw new Error("Expected DER integer (2)");const s=r[5+i];if(s===0)throw new Error("S length is zero");if(6+i+s!==r.length)throw new Error("S length is invalid");if(r[4]&128)throw new Error("R value is negative");if(i>1&&r[4]===0&&!(r[5]&128))throw new Error("R value excessively padded");if(r[i+6]&128)throw new Error("S value is negative");if(s>1&&r[i+6]===0&&!(r[i+7]&128))throw new Error("S value excessively padded");return{r:r.slice(4,4+i),s:r.slice(6+i)}}ur.decode=t;function n(r,i){const s=r.length,o=i.length;if(s===0)throw new Error("R length is zero");if(o===0)throw new Error("S length is zero");if(s>33)throw new Error("R length is too long");if(o>33)throw new Error("S length is too long");if(r[0]&128)throw new Error("R value is negative");if(i[0]&128)throw new Error("S value is negative");if(s>1&&r[0]===0&&!(r[1]&128))throw new Error("R value excessively padded");if(o>1&&i[0]===0&&!(i[1]&128))throw new Error("S value excessively padded");const c=Buffer.allocUnsafe(6+s+o);return c[0]=48,c[1]=c.length-2,c[2]=2,c[3]=r.length,r.copy(c,4),c[4+s]=2,c[5+s]=i.length,i.copy(c,6+s),c}return ur.encode=n,ur}var _i={},D0;function bh(){if(D0)return _i;D0=1,Object.defineProperty(_i,"__esModule",{value:!0}),_i.REVERSE_OPS=_i.OPS=void 0;const e={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};_i.OPS=e;const t={};_i.REVERSE_OPS=t;for(const n of Object.keys(e)){const r=e[n];t[r]=n}return _i}var fr={},j0;function H8(){if(j0)return fr;j0=1,Object.defineProperty(fr,"__esModule",{value:!0}),fr.decode=fr.encode=fr.encodingLength=void 0;const e=bh();function t(i){return i<e.OPS.OP_PUSHDATA1?1:i<=255?2:i<=65535?3:5}fr.encodingLength=t;function n(i,s,o){const c=t(s);return c===1?i.writeUInt8(s,o):c===2?(i.writeUInt8(e.OPS.OP_PUSHDATA1,o),i.writeUInt8(s,o+1)):c===3?(i.writeUInt8(e.OPS.OP_PUSHDATA2,o),i.writeUInt16LE(s,o+1)):(i.writeUInt8(e.OPS.OP_PUSHDATA4,o),i.writeUInt32LE(s,o+1)),c}fr.encode=n;function r(i,s){const o=i.readUInt8(s);let c,a;if(o<e.OPS.OP_PUSHDATA1)c=o,a=1;else if(o===e.OPS.OP_PUSHDATA1){if(s+2>i.length)return null;c=i.readUInt8(s+1),a=2}else if(o===e.OPS.OP_PUSHDATA2){if(s+3>i.length)return null;c=i.readUInt16LE(s+1),a=3}else{if(s+5>i.length)return null;if(o!==e.OPS.OP_PUSHDATA4)throw new Error("Unexpected opcode");c=i.readUInt32LE(s+1),a=5}return{opcode:o,number:c,size:a}}return fr.decode=r,fr}var Si={},K0;function F8(){if(K0)return Si;K0=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.encode=Si.decode=void 0;function e(r,i,s){i=i||4,s=s===void 0?!0:s;const o=r.length;if(o===0)return 0;if(o>i)throw new TypeError("Script number overflow");if(s&&(r[o-1]&127)===0&&(o<=1||(r[o-2]&128)===0))throw new Error("Non-minimally encoded script number");if(o===5){const a=r.readUInt32LE(0),u=r.readUInt8(4);return u&128?-((u&-129)*4294967296+a):u*4294967296+a}let c=0;for(let a=0;a<o;++a)c|=r[a]<<8*a;return r[o-1]&128?-(c&~(128<<8*(o-1))):c}Si.decode=e;function t(r){return r>2147483647?5:r>8388607?4:r>32767?3:r>127?2:r>0?1:0}function n(r){let i=Math.abs(r);const s=t(i),o=Buffer.allocUnsafe(s),c=r<0;for(let a=0;a<s;++a)o.writeUInt8(i&255,a),i>>=8;return o[s-1]&128?o.writeUInt8(c?128:0,s-1):c&&(o[s-1]|=128),o}return Si.encode=n,Si}var Ti={},wf={},bf,G0;function Eh(){if(G0)return bf;G0=1;var e={Array:function(n){return n!=null&&n.constructor===Array},Boolean:function(n){return typeof n=="boolean"},Function:function(n){return typeof n=="function"},Nil:function(n){return n==null},Number:function(n){return typeof n=="number"},Object:function(n){return typeof n=="object"},String:function(n){return typeof n=="string"},"":function(){return!0}};e.Null=e.Nil;for(var t in e)e[t].toJSON=(function(n){return n}).bind(null,t);return bf=e,bf}var Ef,W0;function Gw(){if(W0)return Ef;W0=1;var e=Eh();function t(d){return d.name||d.toString().match(/function (.*?)\s*\(/)[1]}function n(d){return e.Nil(d)?"":t(d.constructor)}function r(d){return e.Function(d)?"":e.String(d)?JSON.stringify(d):d&&e.Object(d)?"":d}function i(d,y){Error.captureStackTrace&&Error.captureStackTrace(d,y)}function s(d){return e.Function(d)?d.toJSON?d.toJSON():t(d):e.Array(d)?"Array":d&&e.Object(d)?"Object":d!==void 0?d:""}function o(d,y,g){var m=r(y);return"Expected "+s(d)+", got"+(g!==""?" "+g:"")+(m!==""?" "+m:"")}function c(d,y,g){g=g||n(y),this.message=o(d,y,g),i(this,c),this.__type=d,this.__value=y,this.__valueTypeName=g}c.prototype=Object.create(Error.prototype),c.prototype.constructor=c;function a(d,y,g,m,E){var _='" of type ';return y==="key"&&(_='" with key type '),o('property "'+s(g)+_+s(d),m,E)}function u(d,y,g,m,E){d?(E=E||n(m),this.message=a(d,g,y,m,E)):this.message='Unexpected property "'+y+'"',i(this,c),this.__label=g,this.__property=y,this.__type=d,this.__value=m,this.__valueTypeName=E}u.prototype=Object.create(Error.prototype),u.prototype.constructor=c;function f(d,y){return new c(d,{},y)}function l(d,y,g){return d instanceof u?(y=y+"."+d.__property,d=new u(d.__type,y,d.__label,d.__value,d.__valueTypeName)):d instanceof c&&(d=new u(d.__type,y,g,d.__value,d.__valueTypeName)),i(d),d}return Ef={TfTypeError:c,TfPropertyTypeError:u,tfCustomError:f,tfSubError:l,tfJSON:s,getValueTypeName:n},Ef}var _f,X0;function M8(){if(X0)return _f;X0=1;var e=Eh(),t=Gw();function n(A){return Buffer.isBuffer(A)}function r(A){return typeof A=="string"&&/^([0-9a-f]{2})+$/i.test(A)}function i(A,R){var M=A.toJSON();function v(U){if(!A(U))return!1;if(U.length===R)return!0;throw t.tfCustomError(M+"(Length: "+R+")",M+"(Length: "+U.length+")")}return v.toJSON=function(){return M},v}var s=i.bind(null,e.Array),o=i.bind(null,n),c=i.bind(null,r),a=i.bind(null,e.String);function u(A,R,M){M=M||e.Number;function v(U,V){return M(U,V)&&U>A&&U<R}return v.toJSON=function(){return`${M.toJSON()} between [${A}, ${R}]`},v}var f=Math.pow(2,53)-1;function l(A){return typeof A=="number"&&isFinite(A)}function d(A){return A<<24>>24===A}function y(A){return A<<16>>16===A}function g(A){return(A|0)===A}function m(A){return typeof A=="number"&&A>=-f&&A<=f&&Math.floor(A)===A}function E(A){return(A&255)===A}function _(A){return(A&65535)===A}function S(A){return A>>>0===A}function w(A){return typeof A=="number"&&A>=0&&A<=f&&Math.floor(A)===A}var T={ArrayN:s,Buffer:n,BufferN:o,Finite:l,Hex:r,HexN:c,Int8:d,Int16:y,Int32:g,Int53:m,Range:u,StringN:a,UInt8:E,UInt16:_,UInt32:S,UInt53:w};for(var O in T)T[O].toJSON=(function(A){return A}).bind(null,O);return _f=T,_f}var Sf,z0;function q8(){if(z0)return Sf;z0=1;var e=Gw(),t=Eh(),n=e.tfJSON,r=e.TfTypeError,i=e.TfPropertyTypeError,s=e.tfSubError,o=e.getValueTypeName,c={arrayOf:function(y,g){y=a(y),g=g||{};function m(E,_){return!t.Array(E)||t.Nil(E)||g.minLength!==void 0&&E.length<g.minLength||g.maxLength!==void 0&&E.length>g.maxLength||g.length!==void 0&&E.length!==g.length?!1:E.every(function(S,w){try{return u(y,S,_)}catch(T){throw s(T,w)}})}return m.toJSON=function(){var E="["+n(y)+"]";return g.length!==void 0?E+="{"+g.length+"}":(g.minLength!==void 0||g.maxLength!==void 0)&&(E+="{"+(g.minLength===void 0?0:g.minLength)+","+(g.maxLength===void 0?1/0:g.maxLength)+"}"),E},m},maybe:function d(y){y=a(y);function g(m,E){return t.Nil(m)||y(m,E,d)}return g.toJSON=function(){return"?"+n(y)},g},map:function(y,g){y=a(y),g&&(g=a(g));function m(E,_){if(!t.Object(E)||t.Nil(E))return!1;for(var S in E){try{g&&u(g,S,_)}catch(T){throw s(T,S,"key")}try{var w=E[S];u(y,w,_)}catch(T){throw s(T,S)}}return!0}return g?m.toJSON=function(){return"{"+n(g)+": "+n(y)+"}"}:m.toJSON=function(){return"{"+n(y)+"}"},m},object:function(y){var g={};for(var m in y)g[m]=a(y[m]);function E(_,S){if(!t.Object(_)||t.Nil(_))return!1;var w;try{for(w in g){var T=g[w],O=_[w];u(T,O,S)}}catch(A){throw s(A,w)}if(S){for(w in _)if(!g[w])throw new i(void 0,w)}return!0}return E.toJSON=function(){return n(g)},E},anyOf:function(){var y=[].slice.call(arguments).map(a);function g(m,E){return y.some(function(_){try{return u(_,m,E)}catch{return!1}})}return g.toJSON=function(){return y.map(n).join("|")},g},allOf:function(){var y=[].slice.call(arguments).map(a);function g(m,E){return y.every(function(_){try{return u(_,m,E)}catch{return!1}})}return g.toJSON=function(){return y.map(n).join(" & ")},g},quacksLike:function(y){function g(m){return y===o(m)}return g.toJSON=function(){return y},g},tuple:function(){var y=[].slice.call(arguments).map(a);function g(m,E){return t.Nil(m)||t.Nil(m.length)||E&&m.length!==y.length?!1:y.every(function(_,S){try{return u(_,m[S],E)}catch(w){throw s(w,S)}})}return g.toJSON=function(){return"("+y.map(n).join(", ")+")"},g},value:function(y){function g(m){return m===y}return g.toJSON=function(){return y},g}};c.oneOf=c.anyOf;function a(d){if(t.String(d))return d[0]==="?"?c.maybe(d.slice(1)):t[d]||c.quacksLike(d);if(d&&t.Object(d)){if(t.Array(d)){if(d.length!==1)throw new TypeError("Expected compile() parameter of type Array of length 1");return c.arrayOf(d[0])}return c.object(d)}else if(t.Function(d))return d;return c.value(d)}function u(d,y,g,m){if(t.Function(d)){if(d(y,g))return!0;throw new r(m||d,y)}return u(a(d),y,g)}for(var f in t)u[f]=t[f];for(f in c)u[f]=c[f];var l=M8();for(f in l)u[f]=l[f];return u.compile=a,u.TfTypeError=r,u.TfPropertyTypeError=i,Sf=u,Sf}var Y0;function Xt(){return Y0||(Y0=1,(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=tc();e.typeforce=q8();const n=t.Buffer.alloc(32,0),r=t.Buffer.from("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f","hex");function i(f,l){return f.length!==l.length?!1:f.every((d,y)=>d.equals(l[y]))}e.stacksEqual=i;function s(f){if(!t.Buffer.isBuffer(f)||f.length<33)return!1;const l=f[0],d=f.slice(1,33);if(d.compare(n)===0||d.compare(r)>=0)return!1;if((l===2||l===3)&&f.length===33)return!0;const y=f.slice(33);return y.compare(n)===0||y.compare(r)>=0?!1:l===4&&f.length===65}e.isPoint=s;const o=21*1e14;function c(f){return e.typeforce.UInt53(f)&&f<=o}e.Satoshi=c,e.TAPLEAF_VERSION_MASK=254;function a(f){return!f||!("output"in f)||!t.Buffer.isBuffer(f.output)?!1:f.version!==void 0?(f.version&e.TAPLEAF_VERSION_MASK)===f.version:!0}e.isTapleaf=a;function u(f){return(0,e.Array)(f)?f.length!==2?!1:f.every(l=>u(l)):a(f)}e.isTaptree=u,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})(wf)),wf}var Z0;function V8(){if(Z0)return Ti;Z0=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.encode=Ti.decode=void 0;const e=Kw(),t=rn(),n=Xt(),{typeforce:r}=n,i=Buffer.alloc(1,0);function s(u){let f=0;for(;u[f]===0;)++f;return f===u.length?i:(u=u.slice(f),u[0]&128?Buffer.concat([i,u],1+u.length):u)}function o(u){u[0]===0&&(u=u.slice(1));const f=Buffer.alloc(32,0),l=Math.max(0,32-u.length);return u.copy(f,l),f}function c(u){const f=u.readUInt8(u.length-1);if(!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=e.decode(u.slice(0,-1)),d=o(l.r),y=o(l.s);return{signature:Buffer.concat([d,y],64),hashType:f}}Ti.decode=c;function a(u,f){if(r({signature:n.BufferN(64),hashType:n.UInt8},{signature:u,hashType:f}),!(0,t.isDefinedHashType)(f))throw new Error("Invalid hashType "+f);const l=Buffer.allocUnsafe(1);l.writeUInt8(f,0);const d=s(u.slice(0,32)),y=s(u.slice(32,64));return Buffer.concat([e.encode(d,y),l])}return Ti.encode=a,Ti}var J0;function rn(){return J0||(J0=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=Kw(),n=bh();Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return n.OPS}});const r=H8(),i=F8(),s=V8(),o=Xt(),{typeforce:c}=o,a=n.OPS.OP_RESERVED;function u(v){return o.Number(v)&&(v===n.OPS.OP_0||v>=n.OPS.OP_1&&v<=n.OPS.OP_16||v===n.OPS.OP_1NEGATE)}function f(v){return o.Buffer(v)||u(v)}function l(v){return o.Array(v)&&v.every(f)}e.isPushOnly=l;function d(v){return v.length-v.filter(f).length}e.countNonPushOnlyOPs=d;function y(v){if(v.length===0)return n.OPS.OP_0;if(v.length===1){if(v[0]>=1&&v[0]<=16)return a+v[0];if(v[0]===129)return n.OPS.OP_1NEGATE}}function g(v){return Buffer.isBuffer(v)}function m(v){return o.Array(v)}function E(v){return Buffer.isBuffer(v)}function _(v){if(g(v))return v;c(o.Array,v);const U=v.reduce((H,$)=>E($)?$.length===1&&y($)!==void 0?H+1:H+r.encodingLength($.length)+$.length:H+1,0),V=Buffer.allocUnsafe(U);let K=0;if(v.forEach(H=>{if(E(H)){const $=y(H);if($!==void 0){V.writeUInt8($,K),K+=1;return}K+=r.encode(V,H.length,K),H.copy(V,K),K+=H.length}else V.writeUInt8(H,K),K+=1}),K!==V.length)throw new Error("Could not decode chunks");return V}e.compile=_;function S(v){if(m(v))return v;c(o.Buffer,v);const U=[];let V=0;for(;V<v.length;){const K=v[V];if(K>n.OPS.OP_0&&K<=n.OPS.OP_PUSHDATA4){const H=r.decode(v,V);if(H===null||(V+=H.size,V+H.number>v.length))return null;const $=v.slice(V,V+H.number);V+=H.number;const P=y($);P!==void 0?U.push(P):U.push($)}else U.push(K),V+=1}return U}e.decompile=S;function w(v){if(g(v)&&(v=S(v)),!v)throw new Error("Could not convert invalid chunks to ASM");return v.map(U=>{if(E(U)){const V=y(U);if(V===void 0)return U.toString("hex");U=V}return n.REVERSE_OPS[U]}).join(" ")}e.toASM=w;function T(v){return c(o.String,v),_(v.split(" ").map(U=>n.OPS[U]!==void 0?n.OPS[U]:(c(o.Hex,U),Buffer.from(U,"hex"))))}e.fromASM=T;function O(v){return v=S(v),c(l,v),v.map(U=>E(U)?U:U===n.OPS.OP_0?Buffer.allocUnsafe(0):i.encode(U-a))}e.toStack=O;function A(v){return o.isPoint(v)}e.isCanonicalPubKey=A;function R(v){const U=v&-129;return U>0&&U<4}e.isDefinedHashType=R;function M(v){return!Buffer.isBuffer(v)||!R(v[v.length-1])?!1:t.check(v.slice(0,-1))}e.isCanonicalScriptSignature=M,e.number=i,e.signature=s})(mf)),mf}var xi={},Q0;function gi(){if(Q0)return xi;Q0=1,Object.defineProperty(xi,"__esModule",{value:!0}),xi.value=xi.prop=void 0;function e(n,r,i){Object.defineProperty(n,r,{configurable:!0,enumerable:!0,get(){const s=i.call(this);return this[r]=s,s},set(s){Object.defineProperty(this,r,{configurable:!0,enumerable:!0,value:s,writable:!0})}})}xi.prop=e;function t(n){let r;return()=>(r!==void 0||(r=n()),r)}return xi.value=t,xi}var ep;function L8(){if(ep)return so;ep=1,Object.defineProperty(so,"__esModule",{value:!0}),so.p2data=void 0;const e=Wn(),t=rn(),n=Xt(),r=gi(),i=t.OPS;function s(o,c){if(!o.data&&!o.output)throw new TypeError("Not enough data");c=Object.assign({validate:!0},c||{}),(0,n.typeforce)({network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.Buffer),data:n.typeforce.maybe(n.typeforce.arrayOf(n.typeforce.Buffer))},o);const u={name:"embed",network:o.network||e.bitcoin};if(r.prop(u,"output",()=>{if(o.data)return t.compile([i.OP_RETURN].concat(o.data))}),r.prop(u,"data",()=>{if(o.output)return t.decompile(o.output).slice(1)}),c.validate&&o.output){const f=t.decompile(o.output);if(f[0]!==i.OP_RETURN)throw new TypeError("Output is invalid");if(!f.slice(1).every(n.typeforce.Buffer))throw new TypeError("Output is invalid");if(o.data&&!(0,n.stacksEqual)(o.data,u.data))throw new TypeError("Data mismatch")}return Object.assign(u,o)}return so.p2data=s,so}var oo={},tp;function $8(){if(tp)return oo;tp=1,Object.defineProperty(oo,"__esModule",{value:!0}),oo.p2ms=void 0;const e=Wn(),t=rn(),n=Xt(),r=gi(),i=t.OPS,s=i.OP_RESERVED;function o(c,a){if(!c.input&&!c.output&&!(c.pubkeys&&c.m!==void 0)&&!c.signatures)throw new TypeError("Not enough data");a=Object.assign({validate:!0},a||{});function u(m){return t.isCanonicalScriptSignature(m)||(a.allowIncomplete&&m===i.OP_0)!==void 0}(0,n.typeforce)({network:n.typeforce.maybe(n.typeforce.Object),m:n.typeforce.maybe(n.typeforce.Number),n:n.typeforce.maybe(n.typeforce.Number),output:n.typeforce.maybe(n.typeforce.Buffer),pubkeys:n.typeforce.maybe(n.typeforce.arrayOf(n.isPoint)),signatures:n.typeforce.maybe(n.typeforce.arrayOf(u)),input:n.typeforce.maybe(n.typeforce.Buffer)},c);const l={network:c.network||e.bitcoin};let d=[],y=!1;function g(m){y||(y=!0,d=t.decompile(m),l.m=d[0]-s,l.n=d[d.length-2]-s,l.pubkeys=d.slice(1,-2))}if(r.prop(l,"output",()=>{if(c.m&&l.n&&c.pubkeys)return t.compile([].concat(s+c.m,c.pubkeys,s+l.n,i.OP_CHECKMULTISIG))}),r.prop(l,"m",()=>{if(l.output)return g(l.output),l.m}),r.prop(l,"n",()=>{if(l.pubkeys)return l.pubkeys.length}),r.prop(l,"pubkeys",()=>{if(c.output)return g(c.output),l.pubkeys}),r.prop(l,"signatures",()=>{if(c.input)return t.decompile(c.input).slice(1)}),r.prop(l,"input",()=>{if(c.signatures)return t.compile([i.OP_0].concat(c.signatures))}),r.prop(l,"witness",()=>{if(l.input)return[]}),r.prop(l,"name",()=>{if(!(!l.m||!l.n))return`p2ms(${l.m} of ${l.n})`}),a.validate){if(c.output){if(g(c.output),!n.typeforce.Number(d[0]))throw new TypeError("Output is invalid");if(!n.typeforce.Number(d[d.length-2]))throw new TypeError("Output is invalid");if(d[d.length-1]!==i.OP_CHECKMULTISIG)throw new TypeError("Output is invalid");if(l.m<=0||l.n>16||l.m>l.n||l.n!==d.length-3)throw new TypeError("Output is invalid");if(!l.pubkeys.every(m=>(0,n.isPoint)(m)))throw new TypeError("Output is invalid");if(c.m!==void 0&&c.m!==l.m)throw new TypeError("m mismatch");if(c.n!==void 0&&c.n!==l.n)throw new TypeError("n mismatch");if(c.pubkeys&&!(0,n.stacksEqual)(c.pubkeys,l.pubkeys))throw new TypeError("Pubkeys mismatch")}if(c.pubkeys){if(c.n!==void 0&&c.n!==c.pubkeys.length)throw new TypeError("Pubkey count mismatch");if(l.n=c.pubkeys.length,l.n<l.m)throw new TypeError("Pubkey count cannot be less than m")}if(c.signatures){if(c.signatures.length<l.m)throw new TypeError("Not enough signatures provided");if(c.signatures.length>l.m)throw new TypeError("Too many signatures provided")}if(c.input){if(c.input[0]!==i.OP_0)throw new TypeError("Input is invalid");if(l.signatures.length===0||!l.signatures.every(u))throw new TypeError("Input has invalid signature(s)");if(c.signatures&&!(0,n.stacksEqual)(c.signatures,l.signatures))throw new TypeError("Signature mismatch");if(c.m!==void 0&&c.m!==c.signatures.length)throw new TypeError("Signature count mismatch")}}return Object.assign(l,c)}return oo.p2ms=o,oo}var co={},np;function D8(){if(np)return co;np=1,Object.defineProperty(co,"__esModule",{value:!0}),co.p2pk=void 0;const e=Wn(),t=rn(),n=Xt(),r=gi(),i=t.OPS;function s(o,c){if(!o.input&&!o.output&&!o.pubkey&&!o.input&&!o.signature)throw new TypeError("Not enough data");c=Object.assign({validate:!0},c||{}),(0,n.typeforce)({network:n.typeforce.maybe(n.typeforce.Object),output:n.typeforce.maybe(n.typeforce.Buffer),pubkey:n.typeforce.maybe(n.isPoint),signature:n.typeforce.maybe(t.isCanonicalScriptSignature),input:n.typeforce.maybe(n.typeforce.Buffer)},o);const a=r.value(()=>t.decompile(o.input)),f={name:"p2pk",network:o.network||e.bitcoin};if(r.prop(f,"output",()=>{if(o.pubkey)return t.compile([o.pubkey,i.OP_CHECKSIG])}),r.prop(f,"pubkey",()=>{if(o.output)return o.output.slice(1,-1)}),r.prop(f,"signature",()=>{if(o.input)return a()[0]}),r.prop(f,"input",()=>{if(o.signature)return t.compile([o.signature])}),r.prop(f,"witness",()=>{if(f.input)return[]}),c.validate){if(o.output){if(o.output[o.output.length-1]!==i.OP_CHECKSIG)throw new TypeError("Output is invalid");if(!(0,n.isPoint)(f.pubkey))throw new TypeError("Output pubkey is invalid");if(o.pubkey&&!o.pubkey.equals(f.pubkey))throw new TypeError("Pubkey mismatch")}if(o.signature&&o.input&&!o.input.equals(f.input))throw new TypeError("Signature mismatch");if(o.input){if(a().length!==1)throw new TypeError("Input is invalid");if(!t.isCanonicalScriptSignature(f.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(f,o)}return co.p2pk=s,co}var ao={},Tf={},Ai={},Zt={},rp;function Ww(){if(rp)return Zt;rp=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.ripemd160=Zt.RIPEMD160=Zt.md5=Zt.MD5=Zt.sha1=Zt.SHA1=void 0;const e=Ry(),t=ui(),n=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),r=new Uint32Array(80);class i extends e.HashMD{constructor(){super(64,20,8,!1),this.A=n[0]|0,this.B=n[1]|0,this.C=n[2]|0,this.D=n[3]|0,this.E=n[4]|0}get(){const{A:v,B:U,C:V,D:K,E:H}=this;return[v,U,V,K,H]}set(v,U,V,K,H){this.A=v|0,this.B=U|0,this.C=V|0,this.D=K|0,this.E=H|0}process(v,U){for(let D=0;D<16;D++,U+=4)r[D]=v.getUint32(U,!1);for(let D=16;D<80;D++)r[D]=(0,t.rotl)(r[D-3]^r[D-8]^r[D-14]^r[D-16],1);let{A:V,B:K,C:H,D:$,E:P}=this;for(let D=0;D<80;D++){let F,x;D<20?(F=(0,e.Chi)(K,H,$),x=1518500249):D<40?(F=K^H^$,x=1859775393):D<60?(F=(0,e.Maj)(K,H,$),x=2400959708):(F=K^H^$,x=3395469782);const B=(0,t.rotl)(V,5)+F+P+x+r[D]|0;P=$,$=H,H=(0,t.rotl)(K,30),K=V,V=B}V=V+this.A|0,K=K+this.B|0,H=H+this.C|0,$=$+this.D|0,P=P+this.E|0,this.set(V,K,H,$,P)}roundClean(){(0,t.clean)(r)}destroy(){this.set(0,0,0,0,0),(0,t.clean)(this.buffer)}}Zt.SHA1=i,Zt.sha1=(0,t.createHasher)(()=>new i);const s=Math.pow(2,32),o=Array.from({length:64},(M,v)=>Math.floor(s*Math.abs(Math.sin(v+1)))),c=n.slice(0,4),a=new Uint32Array(16);class u extends e.HashMD{constructor(){super(64,16,8,!0),this.A=c[0]|0,this.B=c[1]|0,this.C=c[2]|0,this.D=c[3]|0}get(){const{A:v,B:U,C:V,D:K}=this;return[v,U,V,K]}set(v,U,V,K){this.A=v|0,this.B=U|0,this.C=V|0,this.D=K|0}process(v,U){for(let P=0;P<16;P++,U+=4)a[P]=v.getUint32(U,!0);let{A:V,B:K,C:H,D:$}=this;for(let P=0;P<64;P++){let D,F,x;P<16?(D=(0,e.Chi)(K,H,$),F=P,x=[7,12,17,22]):P<32?(D=(0,e.Chi)($,K,H),F=(5*P+1)%16,x=[5,9,14,20]):P<48?(D=K^H^$,F=(3*P+5)%16,x=[4,11,16,23]):(D=H^(K|~$),F=7*P%16,x=[6,10,15,21]),D=D+V+o[P]+a[F],V=$,$=H,H=K,K=K+(0,t.rotl)(D,x[P%4])}V=V+this.A|0,K=K+this.B|0,H=H+this.C|0,$=$+this.D|0,this.set(V,K,H,$)}roundClean(){(0,t.clean)(a)}destroy(){this.set(0,0,0,0),(0,t.clean)(this.buffer)}}Zt.MD5=u,Zt.md5=(0,t.createHasher)(()=>new u);const f=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),l=Uint8Array.from(new Array(16).fill(0).map((M,v)=>v)),d=l.map(M=>(9*M+5)%16),y=(()=>{const U=[[l],[d]];for(let V=0;V<4;V++)for(let K of U)K.push(K[V].map(H=>f[H]));return U})(),g=y[0],m=y[1],E=[[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(M=>Uint8Array.from(M)),_=g.map((M,v)=>M.map(U=>E[v][U])),S=m.map((M,v)=>M.map(U=>E[v][U])),w=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),T=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function O(M,v,U,V){return M===0?v^U^V:M===1?v&U|~v&V:M===2?(v|~U)^V:M===3?v&V|U&~V:v^(U|~V)}const A=new Uint32Array(16);class R extends e.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:v,h1:U,h2:V,h3:K,h4:H}=this;return[v,U,V,K,H]}set(v,U,V,K,H){this.h0=v|0,this.h1=U|0,this.h2=V|0,this.h3=K|0,this.h4=H|0}process(v,U){for(let N=0;N<16;N++,U+=4)A[N]=v.getUint32(U,!0);let V=this.h0|0,K=V,H=this.h1|0,$=H,P=this.h2|0,D=P,F=this.h3|0,x=F,B=this.h4|0,q=B;for(let N=0;N<5;N++){const L=4-N,G=w[N],X=T[N],Y=g[N],ce=m[N],ue=_[N],te=S[N];for(let Z=0;Z<16;Z++){const ae=(0,t.rotl)(V+O(N,H,P,F)+A[Y[Z]]+G,ue[Z])+B|0;V=B,B=F,F=(0,t.rotl)(P,10)|0,P=H,H=ae}for(let Z=0;Z<16;Z++){const ae=(0,t.rotl)(K+O(L,$,D,x)+A[ce[Z]]+X,te[Z])+q|0;K=q,q=x,x=(0,t.rotl)(D,10)|0,D=$,$=ae}}this.set(this.h1+P+x|0,this.h2+F+q|0,this.h3+B+K|0,this.h4+V+$|0,this.h0+H+D|0)}roundClean(){(0,t.clean)(A)}destroy(){this.destroyed=!0,(0,t.clean)(this.buffer),this.set(0,0,0,0,0)}}return Zt.RIPEMD160=R,Zt.ripemd160=(0,t.createHasher)(()=>new R),Zt}var ip;function j8(){if(ip)return Ai;ip=1,Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.ripemd160=Ai.RIPEMD160=void 0;const e=Ww();return Ai.RIPEMD160=e.RIPEMD160,Ai.ripemd160=e.ripemd160,Ai}var vi={},sp;function K8(){if(sp)return vi;sp=1,Object.defineProperty(vi,"__esModule",{value:!0}),vi.sha1=vi.SHA1=void 0;const e=Ww();return vi.SHA1=e.SHA1,vi.sha1=e.sha1,vi}var Un={},op;function Xw(){if(op)return Un;op=1,Object.defineProperty(Un,"__esModule",{value:!0}),Un.sha224=Un.SHA224=Un.sha256=Un.SHA256=void 0;const e=Uy();return Un.SHA256=e.SHA256,Un.sha256=e.sha256,Un.SHA224=e.SHA224,Un.sha224=e.sha224,Un}var cp;function Pr(){return cp||(cp=1,(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=j8(),n=K8(),r=Xw();function i(f){return Buffer.from((0,t.ripemd160)(Uint8Array.from(f)))}e.ripemd160=i;function s(f){return Buffer.from((0,n.sha1)(Uint8Array.from(f)))}e.sha1=s;function o(f){return Buffer.from((0,r.sha256)(Uint8Array.from(f)))}e.sha256=o;function c(f){return Buffer.from((0,t.ripemd160)((0,r.sha256)(Uint8Array.from(f))))}e.hash160=c;function a(f){return Buffer.from((0,r.sha256)((0,r.sha256)(Uint8Array.from(f))))}e.hash256=a,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 u(f,l){return o(Buffer.concat([e.TAGGED_HASH_PREFIXES[f],l]))}e.taggedHash=u})(Tf)),Tf}var xf,ap;function G8(){if(ap)return xf;ap=1;function e(t){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var c=t.length,a=t.charAt(0),u=Math.log(c)/Math.log(256),f=Math.log(256)/Math.log(c);function l(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var m=0,E=0,_=0,S=g.length;_!==S&&g[_]===0;)_++,m++;for(var w=(S-_)*f+1>>>0,T=new Uint8Array(w);_!==S;){for(var O=g[_],A=0,R=w-1;(O!==0||A<E)&&R!==-1;R--,A++)O+=256*T[R]>>>0,T[R]=O%c>>>0,O=O/c>>>0;if(O!==0)throw new Error("Non-zero carry");E=A,_++}for(var M=w-E;M!==w&&T[M]===0;)M++;for(var v=a.repeat(m);M<w;++M)v+=t.charAt(T[M]);return v}function d(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;for(var m=0,E=0,_=0;g[m]===a;)E++,m++;for(var S=(g.length-m)*u+1>>>0,w=new Uint8Array(S);g[m];){var T=g.charCodeAt(m);if(T>255)return;var O=n[T];if(O===255)return;for(var A=0,R=S-1;(O!==0||A<_)&&R!==-1;R--,A++)O+=c*w[R]>>>0,w[R]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");_=A,m++}for(var M=S-_;M!==S&&w[M]===0;)M++;for(var v=new Uint8Array(E+(S-M)),U=E;M!==S;)v[U++]=w[M++];return v}function y(g){var m=d(g);if(m)return m;throw new Error("Non-base"+c+" character")}return{encode:l,decodeUnsafe:d,decode:y}}return xf=e,xf}var Af,up;function W8(){return up||(up=1,Af=G8()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),Af}var vf,fp;function X8(){if(fp)return vf;fp=1;var e=W8();return vf=function(t){function n(o){var c=Uint8Array.from(o),a=t(c),u=c.length+4,f=new Uint8Array(u);return f.set(c,0),f.set(a.subarray(0,4),c.length),e.encode(f,u)}function r(o){var c=o.slice(0,-4),a=o.slice(-4),u=t(c);if(!(a[0]^u[0]|a[1]^u[1]|a[2]^u[2]|a[3]^u[3]))return c}function i(o){var c=e.decodeUnsafe(o);if(c)return r(c)}function s(o){var c=e.decode(o),a=r(c);if(!a)throw new Error("Invalid checksum");return a}return{encode:n,decode:s,decodeUnsafe:i}},vf}var If,lp;function _h(){if(lp)return If;lp=1;var{sha256:e}=Xw(),t=X8();function n(r){return e(e(r))}return If=t(n),If}var hp;function z8(){if(hp)return ao;hp=1,Object.defineProperty(ao,"__esModule",{value:!0}),ao.p2pkh=void 0;const e=Pr(),t=Wn(),n=rn(),r=Xt(),i=gi(),s=_h(),o=n.OPS;function c(a,u){if(!a.address&&!a.hash&&!a.output&&!a.pubkey&&!a.input)throw new TypeError("Not enough data");u=Object.assign({validate:!0},u||{}),(0,r.typeforce)({network:r.typeforce.maybe(r.typeforce.Object),address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(20)),output:r.typeforce.maybe(r.typeforce.BufferN(25)),pubkey:r.typeforce.maybe(r.isPoint),signature:r.typeforce.maybe(n.isCanonicalScriptSignature),input:r.typeforce.maybe(r.typeforce.Buffer)},a);const f=i.value(()=>{const g=Buffer.from(s.decode(a.address)),m=g.readUInt8(0),E=g.slice(1);return{version:m,hash:E}}),l=i.value(()=>n.decompile(a.input)),d=a.network||t.bitcoin,y={name:"p2pkh",network:d};if(i.prop(y,"address",()=>{if(!y.hash)return;const g=Buffer.allocUnsafe(21);return g.writeUInt8(d.pubKeyHash,0),y.hash.copy(g,1),s.encode(g)}),i.prop(y,"hash",()=>{if(a.output)return a.output.slice(3,23);if(a.address)return f().hash;if(a.pubkey||y.pubkey)return e.hash160(a.pubkey||y.pubkey)}),i.prop(y,"output",()=>{if(y.hash)return n.compile([o.OP_DUP,o.OP_HASH160,y.hash,o.OP_EQUALVERIFY,o.OP_CHECKSIG])}),i.prop(y,"pubkey",()=>{if(a.input)return l()[1]}),i.prop(y,"signature",()=>{if(a.input)return l()[0]}),i.prop(y,"input",()=>{if(a.pubkey&&a.signature)return n.compile([a.signature,a.pubkey])}),i.prop(y,"witness",()=>{if(y.input)return[]}),u.validate){let g=Buffer.from([]);if(a.address){if(f().version!==d.pubKeyHash)throw new TypeError("Invalid version or Network mismatch");if(f().hash.length!==20)throw new TypeError("Invalid address");g=f().hash}if(a.hash){if(g.length>0&&!g.equals(a.hash))throw new TypeError("Hash mismatch");g=a.hash}if(a.output){if(a.output.length!==25||a.output[0]!==o.OP_DUP||a.output[1]!==o.OP_HASH160||a.output[2]!==20||a.output[23]!==o.OP_EQUALVERIFY||a.output[24]!==o.OP_CHECKSIG)throw new TypeError("Output is invalid");const m=a.output.slice(3,23);if(g.length>0&&!g.equals(m))throw new TypeError("Hash mismatch");g=m}if(a.pubkey){const m=e.hash160(a.pubkey);if(g.length>0&&!g.equals(m))throw new TypeError("Hash mismatch");g=m}if(a.input){const m=l();if(m.length!==2)throw new TypeError("Input is invalid");if(!n.isCanonicalScriptSignature(m[0]))throw new TypeError("Input has invalid signature");if(!(0,r.isPoint)(m[1]))throw new TypeError("Input has invalid pubkey");if(a.signature&&!a.signature.equals(m[0]))throw new TypeError("Signature mismatch");if(a.pubkey&&!a.pubkey.equals(m[1]))throw new TypeError("Pubkey mismatch");const E=e.hash160(m[1]);if(g.length>0&&!g.equals(E))throw new TypeError("Hash mismatch")}}return Object.assign(y,a)}return ao.p2pkh=c,ao}var uo={},dp;function Y8(){if(dp)return uo;dp=1,Object.defineProperty(uo,"__esModule",{value:!0}),uo.p2sh=void 0;const e=Pr(),t=Wn(),n=rn(),r=Xt(),i=gi(),s=_h(),o=n.OPS;function c(a,u){if(!a.address&&!a.hash&&!a.output&&!a.redeem&&!a.input)throw new TypeError("Not enough data");u=Object.assign({validate:!0},u||{}),(0,r.typeforce)({network:r.typeforce.maybe(r.typeforce.Object),address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(20)),output:r.typeforce.maybe(r.typeforce.BufferN(23)),redeem:r.typeforce.maybe({network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.Buffer),input:r.typeforce.maybe(r.typeforce.Buffer),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))}),input:r.typeforce.maybe(r.typeforce.Buffer),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))},a);let f=a.network;f||(f=a.redeem&&a.redeem.network||t.bitcoin);const l={network:f},d=i.value(()=>{const m=Buffer.from(s.decode(a.address)),E=m.readUInt8(0),_=m.slice(1);return{version:E,hash:_}}),y=i.value(()=>n.decompile(a.input)),g=i.value(()=>{const m=y(),E=m[m.length-1];return{network:f,output:E===o.OP_FALSE?Buffer.from([]):E,input:n.compile(m.slice(0,-1)),witness:a.witness||[]}});if(i.prop(l,"address",()=>{if(!l.hash)return;const m=Buffer.allocUnsafe(21);return m.writeUInt8(l.network.scriptHash,0),l.hash.copy(m,1),s.encode(m)}),i.prop(l,"hash",()=>{if(a.output)return a.output.slice(2,22);if(a.address)return d().hash;if(l.redeem&&l.redeem.output)return e.hash160(l.redeem.output)}),i.prop(l,"output",()=>{if(l.hash)return n.compile([o.OP_HASH160,l.hash,o.OP_EQUAL])}),i.prop(l,"redeem",()=>{if(a.input)return g()}),i.prop(l,"input",()=>{if(!(!a.redeem||!a.redeem.input||!a.redeem.output))return n.compile([].concat(n.decompile(a.redeem.input),a.redeem.output))}),i.prop(l,"witness",()=>{if(l.redeem&&l.redeem.witness)return l.redeem.witness;if(l.input)return[]}),i.prop(l,"name",()=>{const m=["p2sh"];return l.redeem!==void 0&&l.redeem.name!==void 0&&m.push(l.redeem.name),m.join("-")}),u.validate){let m=Buffer.from([]);if(a.address){if(d().version!==f.scriptHash)throw new TypeError("Invalid version or Network mismatch");if(d().hash.length!==20)throw new TypeError("Invalid address");m=d().hash}if(a.hash){if(m.length>0&&!m.equals(a.hash))throw new TypeError("Hash mismatch");m=a.hash}if(a.output){if(a.output.length!==23||a.output[0]!==o.OP_HASH160||a.output[1]!==20||a.output[22]!==o.OP_EQUAL)throw new TypeError("Output is invalid");const _=a.output.slice(2,22);if(m.length>0&&!m.equals(_))throw new TypeError("Hash mismatch");m=_}const E=_=>{if(_.output){const S=n.decompile(_.output);if(!S||S.length<1)throw new TypeError("Redeem.output too short");if(_.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(n.countNonPushOnlyOPs(S)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const w=e.hash160(_.output);if(m.length>0&&!m.equals(w))throw new TypeError("Hash mismatch");m=w}if(_.input){const S=_.input.length>0,w=_.witness&&_.witness.length>0;if(!S&&!w)throw new TypeError("Empty input");if(S&&w)throw new TypeError("Input and witness provided");if(S){const T=n.decompile(_.input);if(!n.isPushOnly(T))throw new TypeError("Non push-only scriptSig")}}};if(a.input){const _=y();if(!_||_.length<1)throw new TypeError("Input too short");if(!Buffer.isBuffer(g().output))throw new TypeError("Input is invalid");E(g())}if(a.redeem){if(a.redeem.network&&a.redeem.network!==f)throw new TypeError("Network mismatch");if(a.input){const _=g();if(a.redeem.output&&!a.redeem.output.equals(_.output))throw new TypeError("Redeem.output mismatch");if(a.redeem.input&&!a.redeem.input.equals(_.input))throw new TypeError("Redeem.input mismatch")}E(a.redeem)}if(a.witness&&a.redeem&&a.redeem.witness&&!(0,r.stacksEqual)(a.redeem.witness,a.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(l,a)}return uo.p2sh=c,uo}var fo={},pp;function Z8(){if(pp)return fo;pp=1,Object.defineProperty(fo,"__esModule",{value:!0}),fo.p2wpkh=void 0;const e=Pr(),t=Wn(),n=rn(),r=Xt(),i=gi(),s=ac(),o=n.OPS,c=Buffer.alloc(0);function a(u,f){if(!u.address&&!u.hash&&!u.output&&!u.pubkey&&!u.witness)throw new TypeError("Not enough data");f=Object.assign({validate:!0},f||{}),(0,r.typeforce)({address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(20)),input:r.typeforce.maybe(r.typeforce.BufferN(0)),network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.BufferN(22)),pubkey:r.typeforce.maybe(r.isPoint),signature:r.typeforce.maybe(n.isCanonicalScriptSignature),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))},u);const l=i.value(()=>{const g=s.bech32.decode(u.address),m=g.words.shift(),E=s.bech32.fromWords(g.words);return{version:m,prefix:g.prefix,data:Buffer.from(E)}}),d=u.network||t.bitcoin,y={name:"p2wpkh",network:d};if(i.prop(y,"address",()=>{if(!y.hash)return;const g=s.bech32.toWords(y.hash);return g.unshift(0),s.bech32.encode(d.bech32,g)}),i.prop(y,"hash",()=>{if(u.output)return u.output.slice(2,22);if(u.address)return l().data;if(u.pubkey||y.pubkey)return e.hash160(u.pubkey||y.pubkey)}),i.prop(y,"output",()=>{if(y.hash)return n.compile([o.OP_0,y.hash])}),i.prop(y,"pubkey",()=>{if(u.pubkey)return u.pubkey;if(u.witness)return u.witness[1]}),i.prop(y,"signature",()=>{if(u.witness)return u.witness[0]}),i.prop(y,"input",()=>{if(y.witness)return c}),i.prop(y,"witness",()=>{if(u.pubkey&&u.signature)return[u.signature,u.pubkey]}),f.validate){let g=Buffer.from([]);if(u.address){if(d&&d.bech32!==l().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(l().version!==0)throw new TypeError("Invalid address version");if(l().data.length!==20)throw new TypeError("Invalid address data");g=l().data}if(u.hash){if(g.length>0&&!g.equals(u.hash))throw new TypeError("Hash mismatch");g=u.hash}if(u.output){if(u.output.length!==22||u.output[0]!==o.OP_0||u.output[1]!==20)throw new TypeError("Output is invalid");if(g.length>0&&!g.equals(u.output.slice(2)))throw new TypeError("Hash mismatch");g=u.output.slice(2)}if(u.pubkey){const m=e.hash160(u.pubkey);if(g.length>0&&!g.equals(m))throw new TypeError("Hash mismatch");if(g=m,!(0,r.isPoint)(u.pubkey)||u.pubkey.length!==33)throw new TypeError("Invalid pubkey for p2wpkh")}if(u.witness){if(u.witness.length!==2)throw new TypeError("Witness is invalid");if(!n.isCanonicalScriptSignature(u.witness[0]))throw new TypeError("Witness has invalid signature");if(!(0,r.isPoint)(u.witness[1])||u.witness[1].length!==33)throw new TypeError("Witness has invalid pubkey");if(u.signature&&!u.signature.equals(u.witness[0]))throw new TypeError("Signature mismatch");if(u.pubkey&&!u.pubkey.equals(u.witness[1]))throw new TypeError("Pubkey mismatch");const m=e.hash160(u.witness[1]);if(g.length>0&&!g.equals(m))throw new TypeError("Hash mismatch")}}return Object.assign(y,u)}return fo.p2wpkh=a,fo}var lo={},yp;function J8(){if(yp)return lo;yp=1,Object.defineProperty(lo,"__esModule",{value:!0}),lo.p2wsh=void 0;const e=Pr(),t=Wn(),n=rn(),r=Xt(),i=gi(),s=ac(),o=n.OPS,c=Buffer.alloc(0);function a(f){return!!(Buffer.isBuffer(f)&&f.length===65&&f[0]===4&&(0,r.isPoint)(f))}function u(f,l){if(!f.address&&!f.hash&&!f.output&&!f.redeem&&!f.witness)throw new TypeError("Not enough data");l=Object.assign({validate:!0},l||{}),(0,r.typeforce)({network:r.typeforce.maybe(r.typeforce.Object),address:r.typeforce.maybe(r.typeforce.String),hash:r.typeforce.maybe(r.typeforce.BufferN(32)),output:r.typeforce.maybe(r.typeforce.BufferN(34)),redeem:r.typeforce.maybe({input:r.typeforce.maybe(r.typeforce.Buffer),network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.Buffer),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))}),input:r.typeforce.maybe(r.typeforce.BufferN(0)),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))},f);const d=i.value(()=>{const E=s.bech32.decode(f.address),_=E.words.shift(),S=s.bech32.fromWords(E.words);return{version:_,prefix:E.prefix,data:Buffer.from(S)}}),y=i.value(()=>n.decompile(f.redeem.input));let g=f.network;g||(g=f.redeem&&f.redeem.network||t.bitcoin);const m={network:g};if(i.prop(m,"address",()=>{if(!m.hash)return;const E=s.bech32.toWords(m.hash);return E.unshift(0),s.bech32.encode(g.bech32,E)}),i.prop(m,"hash",()=>{if(f.output)return f.output.slice(2);if(f.address)return d().data;if(m.redeem&&m.redeem.output)return e.sha256(m.redeem.output)}),i.prop(m,"output",()=>{if(m.hash)return n.compile([o.OP_0,m.hash])}),i.prop(m,"redeem",()=>{if(f.witness)return{output:f.witness[f.witness.length-1],input:c,witness:f.witness.slice(0,-1)}}),i.prop(m,"input",()=>{if(m.witness)return c}),i.prop(m,"witness",()=>{if(f.redeem&&f.redeem.input&&f.redeem.input.length>0&&f.redeem.output&&f.redeem.output.length>0){const E=n.toStack(y());return m.redeem=Object.assign({witness:E},f.redeem),m.redeem.input=c,[].concat(E,f.redeem.output)}if(f.redeem&&f.redeem.output&&f.redeem.witness)return[].concat(f.redeem.witness,f.redeem.output)}),i.prop(m,"name",()=>{const E=["p2wsh"];return m.redeem!==void 0&&m.redeem.name!==void 0&&E.push(m.redeem.name),E.join("-")}),l.validate){let E=Buffer.from([]);if(f.address){if(d().prefix!==g.bech32)throw new TypeError("Invalid prefix or Network mismatch");if(d().version!==0)throw new TypeError("Invalid address version");if(d().data.length!==32)throw new TypeError("Invalid address data");E=d().data}if(f.hash){if(E.length>0&&!E.equals(f.hash))throw new TypeError("Hash mismatch");E=f.hash}if(f.output){if(f.output.length!==34||f.output[0]!==o.OP_0||f.output[1]!==32)throw new TypeError("Output is invalid");const _=f.output.slice(2);if(E.length>0&&!E.equals(_))throw new TypeError("Hash mismatch");E=_}if(f.redeem){if(f.redeem.network&&f.redeem.network!==g)throw new TypeError("Network mismatch");if(f.redeem.input&&f.redeem.input.length>0&&f.redeem.witness&&f.redeem.witness.length>0)throw new TypeError("Ambiguous witness source");if(f.redeem.output){const _=n.decompile(f.redeem.output);if(!_||_.length<1)throw new TypeError("Redeem.output is invalid");if(f.redeem.output.byteLength>3600)throw new TypeError("Redeem.output unspendable if larger than 3600 bytes");if(n.countNonPushOnlyOPs(_)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const S=e.sha256(f.redeem.output);if(E.length>0&&!E.equals(S))throw new TypeError("Hash mismatch");E=S}if(f.redeem.input&&!n.isPushOnly(y()))throw new TypeError("Non push-only scriptSig");if(f.witness&&f.redeem.witness&&!(0,r.stacksEqual)(f.witness,f.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(f.redeem.input&&y().some(a)||f.redeem.output&&(n.decompile(f.redeem.output)||[]).some(a))throw new TypeError("redeem.input or redeem.output contains uncompressed pubkey")}if(f.witness&&f.witness.length>0){const _=f.witness[f.witness.length-1];if(f.redeem&&f.redeem.output&&!f.redeem.output.equals(_))throw new TypeError("Witness and redeem.output mismatch");if(f.witness.some(a)||(n.decompile(_)||[]).some(a))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(m,f)}return lo.p2wsh=u,lo}var ho={},Ii={},gp;function Sh(){if(gp)return Ii;gp=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.getEccLib=Ii.initEccLib=void 0;const e={};function t(c,a){c?c!==e.eccLib&&(a?.DANGER_DO_NOT_VERIFY_ECCLIB||i(c),e.eccLib=c):e.eccLib=c}Ii.initEccLib=t;function n(){if(!e.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return e.eccLib}Ii.getEccLib=n;const r=c=>Buffer.from(c,"hex");function i(c){s(typeof c.isXOnlyPoint=="function"),s(c.isXOnlyPoint(r("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),s(c.isXOnlyPoint(r("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),s(c.isXOnlyPoint(r("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),s(c.isXOnlyPoint(r("0000000000000000000000000000000000000000000000000000000000000001"))),s(!c.isXOnlyPoint(r("0000000000000000000000000000000000000000000000000000000000000000"))),s(!c.isXOnlyPoint(r("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),s(typeof c.xOnlyPointAddTweak=="function"),o.forEach(a=>{const u=c.xOnlyPointAddTweak(r(a.pubkey),r(a.tweak));a.result===null?s(u===null):(s(u!==null),s(u.parity===a.parity),s(Buffer.from(u.xOnlyPubkey).equals(r(a.result))))})}function s(c){if(!c)throw new Error("ecc library invalid")}const o=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}];return Ii}var Of={},kt={},Fc={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var mp;function Q8(){return mp||(mp=1,(function(e,t){var n=tc(),r=n.Buffer;function i(o,c){for(var a in o)c[a]=o[a]}r.from&&r.alloc&&r.allocUnsafe&&r.allocUnsafeSlow?e.exports=n:(i(n,t),t.Buffer=s);function s(o,c,a){return r(o,c,a)}s.prototype=Object.create(r.prototype),i(r,s),s.from=function(o,c,a){if(typeof o=="number")throw new TypeError("Argument must not be a number");return r(o,c,a)},s.alloc=function(o,c,a){if(typeof o!="number")throw new TypeError("Argument must be a number");var u=r(o);return c!==void 0?typeof a=="string"?u.fill(c,a):u.fill(c):u.fill(0),u},s.allocUnsafe=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return r(o)},s.allocUnsafeSlow=function(o){if(typeof o!="number")throw new TypeError("Argument must be a number");return n.SlowBuffer(o)}})(Fc,Fc.exports)),Fc.exports}var Bf,wp;function eA(){if(wp)return Bf;wp=1;var e=Q8().Buffer,t=9007199254740991;function n(o){if(o<0||o>t||o%1!==0)throw new RangeError("value out of range")}function r(o,c,a){if(n(o),c||(c=e.allocUnsafe(s(o))),!e.isBuffer(c))throw new TypeError("buffer must be a Buffer instance");return a||(a=0),o<253?(c.writeUInt8(o,a),r.bytes=1):o<=65535?(c.writeUInt8(253,a),c.writeUInt16LE(o,a+1),r.bytes=3):o<=4294967295?(c.writeUInt8(254,a),c.writeUInt32LE(o,a+1),r.bytes=5):(c.writeUInt8(255,a),c.writeUInt32LE(o>>>0,a+1),c.writeUInt32LE(o/4294967296|0,a+5),r.bytes=9),c}function i(o,c){if(!e.isBuffer(o))throw new TypeError("buffer must be a Buffer instance");c||(c=0);var a=o.readUInt8(c);if(a<253)return i.bytes=1,a;if(a===253)return i.bytes=3,o.readUInt16LE(c+1);if(a===254)return i.bytes=5,o.readUInt32LE(c+1);i.bytes=9;var u=o.readUInt32LE(c+1),f=o.readUInt32LE(c+5),l=f*4294967296+u;return n(l),l}function s(o){return n(o),o<253?1:o<=65535?3:o<=4294967295?5:9}return Bf={encode:r,decode:i,encodingLength:s},Bf}var bp;function Eu(){if(bp)return kt;bp=1,Object.defineProperty(kt,"__esModule",{value:!0}),kt.BufferReader=kt.BufferWriter=kt.cloneBuffer=kt.reverseBuffer=kt.writeUInt64LE=kt.readUInt64LE=kt.varuint=void 0;const e=Xt(),{typeforce:t}=e,n=eA();kt.varuint=n;function r(f,l){if(typeof f!="number")throw new Error("cannot write a non-number as a number");if(f<0)throw new Error("specified a negative value for writing an unsigned value");if(f>l)throw new Error("RangeError: value out of range");if(Math.floor(f)!==f)throw new Error("value has a fractional component")}function i(f,l){const d=f.readUInt32LE(l);let y=f.readUInt32LE(l+4);return y*=4294967296,r(y+d,9007199254740991),y+d}kt.readUInt64LE=i;function s(f,l,d){return r(l,9007199254740991),f.writeInt32LE(l&-1,d),f.writeUInt32LE(Math.floor(l/4294967296),d+4),d+8}kt.writeUInt64LE=s;function o(f){if(f.length<1)return f;let l=f.length-1,d=0;for(let y=0;y<f.length/2;y++)d=f[y],f[y]=f[l],f[l]=d,l--;return f}kt.reverseBuffer=o;function c(f){const l=Buffer.allocUnsafe(f.length);return f.copy(l),l}kt.cloneBuffer=c;class a{static withCapacity(l){return new a(Buffer.alloc(l))}constructor(l,d=0){this.buffer=l,this.offset=d,t(e.tuple(e.Buffer,e.UInt32),[l,d])}writeUInt8(l){this.offset=this.buffer.writeUInt8(l,this.offset)}writeInt32(l){this.offset=this.buffer.writeInt32LE(l,this.offset)}writeUInt32(l){this.offset=this.buffer.writeUInt32LE(l,this.offset)}writeUInt64(l){this.offset=s(this.buffer,l,this.offset)}writeVarInt(l){n.encode(l,this.buffer,this.offset),this.offset+=n.encode.bytes}writeSlice(l){if(this.buffer.length<this.offset+l.length)throw new Error("Cannot write slice out of bounds");this.offset+=l.copy(this.buffer,this.offset)}writeVarSlice(l){this.writeVarInt(l.length),this.writeSlice(l)}writeVector(l){this.writeVarInt(l.length),l.forEach(d=>this.writeVarSlice(d))}end(){if(this.buffer.length===this.offset)return this.buffer;throw new Error(`buffer size ${this.buffer.length}, offset ${this.offset}`)}}kt.BufferWriter=a;class u{constructor(l,d=0){this.buffer=l,this.offset=d,t(e.tuple(e.Buffer,e.UInt32),[l,d])}readUInt8(){const l=this.buffer.readUInt8(this.offset);return this.offset++,l}readInt32(){const l=this.buffer.readInt32LE(this.offset);return this.offset+=4,l}readUInt32(){const l=this.buffer.readUInt32LE(this.offset);return this.offset+=4,l}readUInt64(){const l=i(this.buffer,this.offset);return this.offset+=8,l}readVarInt(){const l=n.decode(this.buffer,this.offset);return this.offset+=n.decode.bytes,l}readSlice(l){if(this.buffer.length<this.offset+l)throw new Error("Cannot read slice out of bounds");const d=this.buffer.slice(this.offset,this.offset+l);return this.offset+=l,d}readVarSlice(){return this.readSlice(this.readVarInt())}readVector(){const l=this.readVarInt(),d=[];for(let y=0;y<l;y++)d.push(this.readVarSlice());return d}}return kt.BufferReader=u,kt}var Ep;function Th(){return Ep||(Ep=1,(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=tc(),n=Sh(),r=Pr(),i=Eu(),s=Xt();e.LEAF_VERSION_TAPSCRIPT=192,e.MAX_TAPTREE_DEPTH=128;const o=m=>"left"in m&&"right"in m;function c(m,E){if(m.length<33)throw new TypeError(`The control-block length is too small. Got ${m.length}, expected min 33.`);const _=(m.length-33)/32;let S=E;for(let w=0;w<_;w++){const T=m.slice(33+32*w,65+32*w);S.compare(T)<0?S=y(S,T):S=y(T,S)}return S}e.rootHashFromPath=c;function a(m){if((0,s.isTapleaf)(m))return{hash:f(m)};const E=[a(m[0]),a(m[1])];E.sort((w,T)=>w.hash.compare(T.hash));const[_,S]=E;return{hash:y(_.hash,S.hash),left:_,right:S}}e.toHashTree=a;function u(m,E){if(o(m)){const _=u(m.left,E);if(_!==void 0)return[..._,m.right.hash];const S=u(m.right,E);if(S!==void 0)return[...S,m.left.hash]}else if(m.hash.equals(E))return[]}e.findScriptPath=u;function f(m){const E=m.version||e.LEAF_VERSION_TAPSCRIPT;return r.taggedHash("TapLeaf",t.Buffer.concat([t.Buffer.from([E]),g(m.output)]))}e.tapleafHash=f;function l(m,E){return r.taggedHash("TapTweak",t.Buffer.concat(E?[m,E]:[m]))}e.tapTweakHash=l;function d(m,E){if(!t.Buffer.isBuffer(m)||m.length!==32||E&&E.length!==32)return null;const _=l(m,E),S=(0,n.getEccLib)().xOnlyPointAddTweak(m,_);return!S||S.xOnlyPubkey===null?null:{parity:S.parity,x:t.Buffer.from(S.xOnlyPubkey)}}e.tweakKey=d;function y(m,E){return r.taggedHash("TapBranch",t.Buffer.concat([m,E]))}function g(m){const E=i.varuint.encodingLength(m.length),_=t.Buffer.allocUnsafe(E);return i.varuint.encode(m.length,_),t.Buffer.concat([_,m])}})(Of)),Of}var _p;function tA(){if(_p)return ho;_p=1,Object.defineProperty(ho,"__esModule",{value:!0}),ho.p2tr=void 0;const e=tc(),t=Wn(),n=rn(),r=Xt(),i=Sh(),s=Th(),o=gi(),c=ac(),a=xh(),u=n.OPS,f=1,l=80;function d(y,g){if(!y.address&&!y.output&&!y.pubkey&&!y.internalPubkey&&!(y.witness&&y.witness.length>1))throw new TypeError("Not enough data");g=Object.assign({validate:!0},g||{}),(0,r.typeforce)({address:r.typeforce.maybe(r.typeforce.String),input:r.typeforce.maybe(r.typeforce.BufferN(0)),network:r.typeforce.maybe(r.typeforce.Object),output:r.typeforce.maybe(r.typeforce.BufferN(34)),internalPubkey:r.typeforce.maybe(r.typeforce.BufferN(32)),hash:r.typeforce.maybe(r.typeforce.BufferN(32)),pubkey:r.typeforce.maybe(r.typeforce.BufferN(32)),signature:r.typeforce.maybe(r.typeforce.anyOf(r.typeforce.BufferN(64),r.typeforce.BufferN(65))),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer)),scriptTree:r.typeforce.maybe(r.isTaptree),redeem:r.typeforce.maybe({output:r.typeforce.maybe(r.typeforce.Buffer),redeemVersion:r.typeforce.maybe(r.typeforce.Number),witness:r.typeforce.maybe(r.typeforce.arrayOf(r.typeforce.Buffer))}),redeemVersion:r.typeforce.maybe(r.typeforce.Number)},y);const m=o.value(()=>(0,a.fromBech32)(y.address)),E=o.value(()=>{if(!(!y.witness||!y.witness.length))return y.witness.length>=2&&y.witness[y.witness.length-1][0]===l?y.witness.slice(0,-1):y.witness.slice()}),_=o.value(()=>{if(y.scriptTree)return(0,s.toHashTree)(y.scriptTree);if(y.hash)return{hash:y.hash}}),S=y.network||t.bitcoin,w={name:"p2tr",network:S};if(o.prop(w,"address",()=>{if(!w.pubkey)return;const T=c.bech32m.toWords(w.pubkey);return T.unshift(f),c.bech32m.encode(S.bech32,T)}),o.prop(w,"hash",()=>{const T=_();if(T)return T.hash;const O=E();if(O&&O.length>1){const A=O[O.length-1],R=A[0]&r.TAPLEAF_VERSION_MASK,M=O[O.length-2],v=(0,s.tapleafHash)({output:M,version:R});return(0,s.rootHashFromPath)(A,v)}return null}),o.prop(w,"output",()=>{if(w.pubkey)return n.compile([u.OP_1,w.pubkey])}),o.prop(w,"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(w,"redeem",()=>{const T=E();if(!(!T||T.length<2))return{output:T[T.length-2],witness:T.slice(0,-2),redeemVersion:T[T.length-1][0]&r.TAPLEAF_VERSION_MASK}}),o.prop(w,"pubkey",()=>{if(y.pubkey)return y.pubkey;if(y.output)return y.output.slice(2);if(y.address)return m().data;if(w.internalPubkey){const T=(0,s.tweakKey)(w.internalPubkey,w.hash);if(T)return T.x}}),o.prop(w,"internalPubkey",()=>{if(y.internalPubkey)return y.internalPubkey;const T=E();if(T&&T.length>1)return T[T.length-1].slice(1,33)}),o.prop(w,"signature",()=>{if(y.signature)return y.signature;const T=E();if(!(!T||T.length!==1))return T[0]}),o.prop(w,"witness",()=>{if(y.witness)return y.witness;const T=_();if(T&&y.redeem&&y.redeem.output&&y.internalPubkey){const O=(0,s.tapleafHash)({output:y.redeem.output,version:w.redeemVersion}),A=(0,s.findScriptPath)(T,O);if(!A)return;const R=(0,s.tweakKey)(y.internalPubkey,T.hash);if(!R)return;const M=e.Buffer.concat([e.Buffer.from([w.redeemVersion|R.parity]),y.internalPubkey].concat(A));return[y.redeem.output,M]}if(y.signature)return[y.signature]}),g.validate){let T=e.Buffer.from([]);if(y.address){if(S&&S.bech32!==m().prefix)throw new TypeError("Invalid prefix or Network mismatch");if(m().version!==f)throw new TypeError("Invalid address version");if(m().data.length!==32)throw new TypeError("Invalid address data");T=m().data}if(y.pubkey){if(T.length>0&&!T.equals(y.pubkey))throw new TypeError("Pubkey mismatch");T=y.pubkey}if(y.output){if(y.output.length!==34||y.output[0]!==u.OP_1||y.output[1]!==32)throw new TypeError("Output is invalid");if(T.length>0&&!T.equals(y.output.slice(2)))throw new TypeError("Pubkey mismatch");T=y.output.slice(2)}if(y.internalPubkey){const R=(0,s.tweakKey)(y.internalPubkey,w.hash);if(T.length>0&&!T.equals(R.x))throw new TypeError("Pubkey mismatch");T=R.x}if(T&&T.length&&!(0,i.getEccLib)().isXOnlyPoint(T))throw new TypeError("Invalid pubkey for p2tr");const O=_();if(y.hash&&O&&!y.hash.equals(O.hash))throw new TypeError("Hash mismatch");if(y.redeem&&y.redeem.output&&O){const R=(0,s.tapleafHash)({output:y.redeem.output,version:w.redeemVersion});if(!(0,s.findScriptPath)(O,R))throw new TypeError("Redeem script not in tree")}const A=E();if(y.redeem&&w.redeem){if(y.redeem.redeemVersion&&y.redeem.redeemVersion!==w.redeem.redeemVersion)throw new TypeError("Redeem.redeemVersion and witness mismatch");if(y.redeem.output){if(n.decompile(y.redeem.output).length===0)throw new TypeError("Redeem.output is invalid");if(w.redeem.output&&!y.redeem.output.equals(w.redeem.output))throw new TypeError("Redeem.output and witness mismatch")}if(y.redeem.witness&&w.redeem.witness&&!(0,r.stacksEqual)(y.redeem.witness,w.redeem.witness))throw new TypeError("Redeem.witness and witness mismatch")}if(A&&A.length)if(A.length===1){if(y.signature&&!y.signature.equals(A[0]))throw new TypeError("Signature mismatch")}else{const R=A[A.length-1];if(R.length<33)throw new TypeError(`The control-block length is too small. Got ${R.length}, expected min 33.`);if((R.length-33)%32!==0)throw new TypeError(`The control-block length of ${R.length} is incorrect!`);const M=(R.length-33)/32;if(M>128)throw new TypeError(`The script path is too long. Got ${M}, expected max 128.`);const v=R.slice(1,33);if(y.internalPubkey&&!y.internalPubkey.equals(v))throw new TypeError("Internal pubkey mismatch");if(!(0,i.getEccLib)().isXOnlyPoint(v))throw new TypeError("Invalid internalPubkey for p2tr witness");const U=R[0]&r.TAPLEAF_VERSION_MASK,V=A[A.length-2],K=(0,s.tapleafHash)({output:V,version:U}),H=(0,s.rootHashFromPath)(R,K),$=(0,s.tweakKey)(v,H);if(!$)throw new TypeError("Invalid outputKey for p2tr witness");if(T.length&&!T.equals($.x))throw new TypeError("Pubkey mismatch for p2tr witness");if($.parity!==(R[0]&1))throw new Error("Incorrect parity")}}return Object.assign(w,y)}return ho.p2tr=d,ho}var Sp;function Ec(){return Sp||(Sp=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=L8();Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const n=$8();Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return n.p2ms}});const r=D8();Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return r.p2pk}});const i=z8();Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const s=Y8();Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return s.p2sh}});const o=Z8();Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const c=J8();Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return c.p2wsh}});const a=tA();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return a.p2tr}})})(gf)),gf}var Tp;function xh(){if(Tp)return Yt;Tp=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.toOutputScript=Yt.fromOutputScript=Yt.toBech32=Yt.toBase58Check=Yt.fromBech32=Yt.fromBase58Check=void 0;const e=Wn(),t=Ec(),n=rn(),r=Xt(),i=ac(),s=_h(),o=40,c=2,a=16,u=2,f=80,l="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 d(w,T){const O=w.slice(2);if(O.length<c||O.length>o)throw new TypeError("Invalid program length for segwit address");const A=w[0]-f;if(A<u||A>a)throw new TypeError("Invalid version for segwit address");if(w[1]!==O.length)throw new TypeError("Invalid script for segwit address");return console.warn(l),E(O,A,T.bech32)}function y(w){const T=Buffer.from(s.decode(w));if(T.length<21)throw new TypeError(w+" is too short");if(T.length>21)throw new TypeError(w+" is too long");const O=T.readUInt8(0),A=T.slice(1);return{version:O,hash:A}}Yt.fromBase58Check=y;function g(w){let T,O;try{T=i.bech32.decode(w)}catch{}if(T){if(O=T.words[0],O!==0)throw new TypeError(w+" uses wrong encoding")}else if(T=i.bech32m.decode(w),O=T.words[0],O===0)throw new TypeError(w+" uses wrong encoding");const A=i.bech32.fromWords(T.words.slice(1));return{version:O,prefix:T.prefix,data:Buffer.from(A)}}Yt.fromBech32=g;function m(w,T){(0,r.typeforce)((0,r.tuple)(r.Hash160bit,r.UInt8),arguments);const O=Buffer.allocUnsafe(21);return O.writeUInt8(T,0),w.copy(O,1),s.encode(O)}Yt.toBase58Check=m;function E(w,T,O){const A=i.bech32.toWords(w);return A.unshift(T),T===0?i.bech32.encode(O,A):i.bech32m.encode(O,A)}Yt.toBech32=E;function _(w,T){T=T||e.bitcoin;try{return t.p2pkh({output:w,network:T}).address}catch{}try{return t.p2sh({output:w,network:T}).address}catch{}try{return t.p2wpkh({output:w,network:T}).address}catch{}try{return t.p2wsh({output:w,network:T}).address}catch{}try{return t.p2tr({output:w,network:T}).address}catch{}try{return d(w,T)}catch{}throw new Error(n.toASM(w)+" has no matching Address")}Yt.fromOutputScript=_;function S(w,T){T=T||e.bitcoin;let O,A;try{O=y(w)}catch{}if(O){if(O.version===T.pubKeyHash)return t.p2pkh({hash:O.hash}).output;if(O.version===T.scriptHash)return t.p2sh({hash:O.hash}).output}else{try{A=g(w)}catch{}if(A){if(A.prefix!==T.bech32)throw new Error(w+" has an invalid prefix");if(A.version===0){if(A.data.length===20)return t.p2wpkh({hash:A.data}).output;if(A.data.length===32)return t.p2wsh({hash:A.data}).output}else if(A.version===1){if(A.data.length===32)return t.p2tr({pubkey:A.data}).output}else if(A.version>=u&&A.version<=a&&A.data.length>=c&&A.data.length<=o)return console.warn(l),n.compile([A.version+f,A.data])}}throw new Error(w+" has no matching Script")}return Yt.toOutputScript=S,Yt}var po={},yo={},xp;function nA(){if(xp)return yo;xp=1,Object.defineProperty(yo,"__esModule",{value:!0}),yo.fastMerkleRoot=void 0;function e(t,n){if(!Array.isArray(t))throw TypeError("Expected values Array");if(typeof n!="function")throw TypeError("Expected digest Function");let r=t.length;const i=t.concat();for(;r>1;){let s=0;for(let o=0;o<r;o+=2,++s){const c=i[o],a=o+1===r?c:i[o+1],u=Buffer.concat([c,a]);i[s]=n(u)}r=s}return i[0]}return yo.fastMerkleRoot=e,yo}var go={},Ap;function _c(){if(Ap)return go;Ap=1,Object.defineProperty(go,"__esModule",{value:!0}),go.Transaction=void 0;const e=Eu(),t=Pr(),n=rn(),r=rn(),i=Xt(),{typeforce:s}=i;function o(E){const _=E.length;return e.varuint.encodingLength(_)+_}function c(E){const _=E.length;return e.varuint.encodingLength(_)+E.reduce((S,w)=>S+o(w),0)}const a=Buffer.allocUnsafe(0),u=[],f=Buffer.from("0000000000000000000000000000000000000000000000000000000000000000","hex"),l=Buffer.from("0000000000000000000000000000000000000000000000000000000000000001","hex"),d=Buffer.from("ffffffffffffffff","hex"),y={script:a,valueBuffer:d};function g(E){return E.value!==void 0}class m{constructor(){this.version=1,this.locktime=0,this.ins=[],this.outs=[]}static fromBuffer(_,S){const w=new e.BufferReader(_),T=new m;T.version=w.readInt32();const O=w.readUInt8(),A=w.readUInt8();let R=!1;O===m.ADVANCED_TRANSACTION_MARKER&&A===m.ADVANCED_TRANSACTION_FLAG?R=!0:w.offset-=2;const M=w.readVarInt();for(let U=0;U<M;++U)T.ins.push({hash:w.readSlice(32),index:w.readUInt32(),script:w.readVarSlice(),sequence:w.readUInt32(),witness:u});const v=w.readVarInt();for(let U=0;U<v;++U)T.outs.push({value:w.readUInt64(),script:w.readVarSlice()});if(R){for(let U=0;U<M;++U)T.ins[U].witness=w.readVector();if(!T.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(T.locktime=w.readUInt32(),S)return T;if(w.offset!==_.length)throw new Error("Transaction has unexpected data");return T}static fromHex(_){return m.fromBuffer(Buffer.from(_,"hex"),!1)}static isCoinbaseHash(_){s(i.Hash256bit,_);for(let S=0;S<32;++S)if(_[S]!==0)return!1;return!0}isCoinbase(){return this.ins.length===1&&m.isCoinbaseHash(this.ins[0].hash)}addInput(_,S,w,T){return s(i.tuple(i.Hash256bit,i.UInt32,i.maybe(i.UInt32),i.maybe(i.Buffer)),arguments),i.Null(w)&&(w=m.DEFAULT_SEQUENCE),this.ins.push({hash:_,index:S,script:T||a,sequence:w,witness:u})-1}addOutput(_,S){return s(i.tuple(i.Buffer,i.Satoshi),arguments),this.outs.push({script:_,value:S})-1}hasWitnesses(){return this.ins.some(_=>_.witness.length!==0)}stripWitnesses(){this.ins.forEach(_=>{_.witness=u})}weight(){const _=this.byteLength(!1),S=this.byteLength(!0);return _*3+S}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(_=!0){const S=_&&this.hasWitnesses();return(S?10:8)+e.varuint.encodingLength(this.ins.length)+e.varuint.encodingLength(this.outs.length)+this.ins.reduce((w,T)=>w+40+o(T.script),0)+this.outs.reduce((w,T)=>w+8+o(T.script),0)+(S?this.ins.reduce((w,T)=>w+c(T.witness),0):0)}clone(){const _=new m;return _.version=this.version,_.locktime=this.locktime,_.ins=this.ins.map(S=>({hash:S.hash,index:S.index,script:S.script,sequence:S.sequence,witness:S.witness})),_.outs=this.outs.map(S=>({script:S.script,value:S.value})),_}hashForSignature(_,S,w){if(s(i.tuple(i.UInt32,i.Buffer,i.Number),arguments),_>=this.ins.length)return l;const T=n.compile(n.decompile(S).filter(R=>R!==r.OPS.OP_CODESEPARATOR)),O=this.clone();if((w&31)===m.SIGHASH_NONE)O.outs=[],O.ins.forEach((R,M)=>{M!==_&&(R.sequence=0)});else if((w&31)===m.SIGHASH_SINGLE){if(_>=this.outs.length)return l;O.outs.length=_+1;for(let R=0;R<_;R++)O.outs[R]=y;O.ins.forEach((R,M)=>{M!==_&&(R.sequence=0)})}w&m.SIGHASH_ANYONECANPAY?(O.ins=[O.ins[_]],O.ins[0].script=T):(O.ins.forEach(R=>{R.script=a}),O.ins[_].script=T);const A=Buffer.allocUnsafe(O.byteLength(!1)+4);return A.writeInt32LE(w,A.length-4),O.__toBuffer(A,0,!1),t.hash256(A)}hashForWitnessV1(_,S,w,T,O,A){if(s(i.tuple(i.UInt32,s.arrayOf(i.Buffer),s.arrayOf(i.Satoshi),i.UInt32),arguments),w.length!==this.ins.length||S.length!==this.ins.length)throw new Error("Must supply prevout script and value for all inputs");const R=T===m.SIGHASH_DEFAULT?m.SIGHASH_ALL:T&m.SIGHASH_OUTPUT_MASK,v=(T&m.SIGHASH_INPUT_MASK)===m.SIGHASH_ANYONECANPAY,U=R===m.SIGHASH_NONE,V=R===m.SIGHASH_SINGLE;let K=a,H=a,$=a,P=a,D=a;if(!v){let q=e.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(N=>{q.writeSlice(N.hash),q.writeUInt32(N.index)}),K=t.sha256(q.end()),q=e.BufferWriter.withCapacity(8*this.ins.length),w.forEach(N=>q.writeUInt64(N)),H=t.sha256(q.end()),q=e.BufferWriter.withCapacity(S.map(o).reduce((N,L)=>N+L)),S.forEach(N=>q.writeVarSlice(N)),$=t.sha256(q.end()),q=e.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(N=>q.writeUInt32(N.sequence)),P=t.sha256(q.end())}if(U||V){if(V&&_<this.outs.length){const q=this.outs[_],N=e.BufferWriter.withCapacity(8+o(q.script));N.writeUInt64(q.value),N.writeVarSlice(q.script),D=t.sha256(N.end())}}else{const q=this.outs.map(L=>8+o(L.script)).reduce((L,G)=>L+G),N=e.BufferWriter.withCapacity(q);this.outs.forEach(L=>{N.writeUInt64(L.value),N.writeVarSlice(L.script)}),D=t.sha256(N.end())}const F=(O?2:0)+(A?1:0),x=174-(v?49:0)-(U?32:0)+(A?32:0)+(O?37:0),B=e.BufferWriter.withCapacity(x);if(B.writeUInt8(T),B.writeInt32(this.version),B.writeUInt32(this.locktime),B.writeSlice(K),B.writeSlice(H),B.writeSlice($),B.writeSlice(P),U||V||B.writeSlice(D),B.writeUInt8(F),v){const q=this.ins[_];B.writeSlice(q.hash),B.writeUInt32(q.index),B.writeUInt64(w[_]),B.writeVarSlice(S[_]),B.writeUInt32(q.sequence)}else B.writeUInt32(_);if(A){const q=e.BufferWriter.withCapacity(o(A));q.writeVarSlice(A),B.writeSlice(t.sha256(q.end()))}return V&&B.writeSlice(D),O&&(B.writeSlice(O),B.writeUInt8(0),B.writeUInt32(4294967295)),t.taggedHash("TapSighash",Buffer.concat([Buffer.from([0]),B.end()]))}hashForWitnessV0(_,S,w,T){s(i.tuple(i.UInt32,i.Buffer,i.Satoshi,i.UInt32),arguments);let O=Buffer.from([]),A,R=f,M=f,v=f;if(T&m.SIGHASH_ANYONECANPAY||(O=Buffer.allocUnsafe(36*this.ins.length),A=new e.BufferWriter(O,0),this.ins.forEach(V=>{A.writeSlice(V.hash),A.writeUInt32(V.index)}),M=t.hash256(O)),!(T&m.SIGHASH_ANYONECANPAY)&&(T&31)!==m.SIGHASH_SINGLE&&(T&31)!==m.SIGHASH_NONE&&(O=Buffer.allocUnsafe(4*this.ins.length),A=new e.BufferWriter(O,0),this.ins.forEach(V=>{A.writeUInt32(V.sequence)}),v=t.hash256(O)),(T&31)!==m.SIGHASH_SINGLE&&(T&31)!==m.SIGHASH_NONE){const V=this.outs.reduce((K,H)=>K+8+o(H.script),0);O=Buffer.allocUnsafe(V),A=new e.BufferWriter(O,0),this.outs.forEach(K=>{A.writeUInt64(K.value),A.writeVarSlice(K.script)}),R=t.hash256(O)}else if((T&31)===m.SIGHASH_SINGLE&&_<this.outs.length){const V=this.outs[_];O=Buffer.allocUnsafe(8+o(V.script)),A=new e.BufferWriter(O,0),A.writeUInt64(V.value),A.writeVarSlice(V.script),R=t.hash256(O)}O=Buffer.allocUnsafe(156+o(S)),A=new e.BufferWriter(O,0);const U=this.ins[_];return A.writeInt32(this.version),A.writeSlice(M),A.writeSlice(v),A.writeSlice(U.hash),A.writeUInt32(U.index),A.writeVarSlice(S),A.writeUInt64(w),A.writeUInt32(U.sequence),A.writeSlice(R),A.writeUInt32(this.locktime),A.writeUInt32(T),t.hash256(O)}getHash(_){return _&&this.isCoinbase()?Buffer.alloc(32,0):t.hash256(this.__toBuffer(void 0,void 0,_))}getId(){return(0,e.reverseBuffer)(this.getHash(!1)).toString("hex")}toBuffer(_,S){return this.__toBuffer(_,S,!0)}toHex(){return this.toBuffer(void 0,void 0).toString("hex")}setInputScript(_,S){s(i.tuple(i.Number,i.Buffer),arguments),this.ins[_].script=S}setWitness(_,S){s(i.tuple(i.Number,[i.Buffer]),arguments),this.ins[_].witness=S}__toBuffer(_,S,w=!1){_||(_=Buffer.allocUnsafe(this.byteLength(w)));const T=new e.BufferWriter(_,S||0);T.writeInt32(this.version);const O=w&&this.hasWitnesses();return O&&(T.writeUInt8(m.ADVANCED_TRANSACTION_MARKER),T.writeUInt8(m.ADVANCED_TRANSACTION_FLAG)),T.writeVarInt(this.ins.length),this.ins.forEach(A=>{T.writeSlice(A.hash),T.writeUInt32(A.index),T.writeVarSlice(A.script),T.writeUInt32(A.sequence)}),T.writeVarInt(this.outs.length),this.outs.forEach(A=>{g(A)?T.writeUInt64(A.value):T.writeSlice(A.valueBuffer),T.writeVarSlice(A.script)}),O&&this.ins.forEach(A=>{T.writeVector(A.witness)}),T.writeUInt32(this.locktime),S!==void 0?_.slice(S,T.offset):_}}return go.Transaction=m,m.DEFAULT_SEQUENCE=4294967295,m.SIGHASH_DEFAULT=0,m.SIGHASH_ALL=1,m.SIGHASH_NONE=2,m.SIGHASH_SINGLE=3,m.SIGHASH_ANYONECANPAY=128,m.SIGHASH_OUTPUT_MASK=3,m.SIGHASH_INPUT_MASK=128,m.ADVANCED_TRANSACTION_MARKER=0,m.ADVANCED_TRANSACTION_FLAG=1,go}var vp;function rA(){if(vp)return po;vp=1,Object.defineProperty(po,"__esModule",{value:!0}),po.Block=void 0;const e=Eu(),t=Pr(),n=nA(),r=_c(),i=Xt(),{typeforce:s}=i,o=new TypeError("Cannot compute merkle root for zero transactions"),c=new TypeError("Cannot compute witness commit for non-segwit block");class a{constructor(){this.version=1,this.prevHash=void 0,this.merkleRoot=void 0,this.timestamp=0,this.witnessCommit=void 0,this.bits=0,this.nonce=0,this.transactions=void 0}static fromBuffer(d){if(d.length<80)throw new Error("Buffer too small (< 80 bytes)");const y=new e.BufferReader(d),g=new a;if(g.version=y.readInt32(),g.prevHash=y.readSlice(32),g.merkleRoot=y.readSlice(32),g.timestamp=y.readUInt32(),g.bits=y.readUInt32(),g.nonce=y.readUInt32(),d.length===80)return g;const m=()=>{const S=r.Transaction.fromBuffer(y.buffer.slice(y.offset),!0);return y.offset+=S.byteLength(),S},E=y.readVarInt();g.transactions=[];for(let S=0;S<E;++S){const w=m();g.transactions.push(w)}const _=g.getWitnessCommit();return _&&(g.witnessCommit=_),g}static fromHex(d){return a.fromBuffer(Buffer.from(d,"hex"))}static calculateTarget(d){const y=((d&4278190080)>>24)-3,g=d&8388607,m=Buffer.alloc(32,0);return m.writeUIntBE(g,29-y,3),m}static calculateMerkleRoot(d,y){if(s([{getHash:i.Function}],d),d.length===0)throw o;if(y&&!u(d))throw c;const g=d.map(E=>E.getHash(y)),m=(0,n.fastMerkleRoot)(g,t.hash256);return y?t.hash256(Buffer.concat([m,d[0].ins[0].witness[0]])):m}getWitnessCommit(){if(!u(this.transactions))return null;const d=this.transactions[0].outs.filter(g=>g.script.slice(0,6).equals(Buffer.from("6a24aa21a9ed","hex"))).map(g=>g.script.slice(6,38));if(d.length===0)return null;const y=d[d.length-1];return y instanceof Buffer&&y.length===32?y:null}hasWitnessCommit(){return this.witnessCommit instanceof Buffer&&this.witnessCommit.length===32||this.getWitnessCommit()!==null}hasWitness(){return f(this.transactions)}weight(){const d=this.byteLength(!1,!1),y=this.byteLength(!1,!0);return d*3+y}byteLength(d,y=!0){return d||!this.transactions?80:80+e.varuint.encodingLength(this.transactions.length)+this.transactions.reduce((g,m)=>g+m.byteLength(y),0)}getHash(){return t.hash256(this.toBuffer(!0))}getId(){return(0,e.reverseBuffer)(this.getHash()).toString("hex")}getUTCDate(){const d=new Date(0);return d.setUTCSeconds(this.timestamp),d}toBuffer(d){const y=Buffer.allocUnsafe(this.byteLength(d)),g=new e.BufferWriter(y);return g.writeInt32(this.version),g.writeSlice(this.prevHash),g.writeSlice(this.merkleRoot),g.writeUInt32(this.timestamp),g.writeUInt32(this.bits),g.writeUInt32(this.nonce),d||!this.transactions||(e.varuint.encode(this.transactions.length,y,g.offset),g.offset+=e.varuint.encode.bytes,this.transactions.forEach(m=>{const E=m.byteLength();m.toBuffer(y,g.offset),g.offset+=E})),y}toHex(d){return this.toBuffer(d).toString("hex")}checkTxRoots(){const d=this.hasWitnessCommit();return!d&&this.hasWitness()?!1:this.__checkMerkleRoot()&&(d?this.__checkWitnessCommit():!0)}checkProofOfWork(){const d=(0,e.reverseBuffer)(this.getHash()),y=a.calculateTarget(this.bits);return d.compare(y)<=0}__checkMerkleRoot(){if(!this.transactions)throw o;const d=a.calculateMerkleRoot(this.transactions);return this.merkleRoot.compare(d)===0}__checkWitnessCommit(){if(!this.transactions)throw o;if(!this.hasWitnessCommit())throw c;const d=a.calculateMerkleRoot(this.transactions,!0);return this.witnessCommit.compare(d)===0}}po.Block=a;function u(l){return l instanceof Array&&l[0]&&l[0].ins&&l[0].ins instanceof Array&&l[0].ins[0]&&l[0].ins[0].witness&&l[0].ins[0].witness instanceof Array&&l[0].ins[0].witness.length>0}function f(l){return l instanceof Array&&l.some(d=>typeof d=="object"&&d.ins instanceof Array&&d.ins.some(y=>typeof y=="object"&&y.witness instanceof Array&&y.witness.length>0))}return po}var mo={},Mc={},qc={},Nf={},cs={},as={},kf={},Ip;function Mt(){return Ip||(Ip=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),(function(t){t[t.UNSIGNED_TX=0]="UNSIGNED_TX",t[t.GLOBAL_XPUB=1]="GLOBAL_XPUB"})(e.GlobalTypes||(e.GlobalTypes={})),e.GLOBAL_TYPE_NAMES=["unsignedTx","globalXpub"],(function(t){t[t.NON_WITNESS_UTXO=0]="NON_WITNESS_UTXO",t[t.WITNESS_UTXO=1]="WITNESS_UTXO",t[t.PARTIAL_SIG=2]="PARTIAL_SIG",t[t.SIGHASH_TYPE=3]="SIGHASH_TYPE",t[t.REDEEM_SCRIPT=4]="REDEEM_SCRIPT",t[t.WITNESS_SCRIPT=5]="WITNESS_SCRIPT",t[t.BIP32_DERIVATION=6]="BIP32_DERIVATION",t[t.FINAL_SCRIPTSIG=7]="FINAL_SCRIPTSIG",t[t.FINAL_SCRIPTWITNESS=8]="FINAL_SCRIPTWITNESS",t[t.POR_COMMITMENT=9]="POR_COMMITMENT",t[t.TAP_KEY_SIG=19]="TAP_KEY_SIG",t[t.TAP_SCRIPT_SIG=20]="TAP_SCRIPT_SIG",t[t.TAP_LEAF_SCRIPT=21]="TAP_LEAF_SCRIPT",t[t.TAP_BIP32_DERIVATION=22]="TAP_BIP32_DERIVATION",t[t.TAP_INTERNAL_KEY=23]="TAP_INTERNAL_KEY",t[t.TAP_MERKLE_ROOT=24]="TAP_MERKLE_ROOT"})(e.InputTypes||(e.InputTypes={})),e.INPUT_TYPE_NAMES=["nonWitnessUtxo","witnessUtxo","partialSig","sighashType","redeemScript","witnessScript","bip32Derivation","finalScriptSig","finalScriptWitness","porCommitment","tapKeySig","tapScriptSig","tapLeafScript","tapBip32Derivation","tapInternalKey","tapMerkleRoot"],(function(t){t[t.REDEEM_SCRIPT=0]="REDEEM_SCRIPT",t[t.WITNESS_SCRIPT=1]="WITNESS_SCRIPT",t[t.BIP32_DERIVATION=2]="BIP32_DERIVATION",t[t.TAP_INTERNAL_KEY=5]="TAP_INTERNAL_KEY",t[t.TAP_TREE=6]="TAP_TREE",t[t.TAP_BIP32_DERIVATION=7]="TAP_BIP32_DERIVATION"})(e.OutputTypes||(e.OutputTypes={})),e.OUTPUT_TYPE_NAMES=["redeemScript","witnessScript","bip32Derivation","tapInternalKey","tapTree","tapBip32Derivation"]})(kf)),kf}var Vr={},Op;function iA(){if(Op)return Vr;Op=1,Object.defineProperty(Vr,"__esModule",{value:!0});const e=Mt(),t=o=>[...Array(o).keys()];function n(o){if(o.key[0]!==e.GlobalTypes.GLOBAL_XPUB)throw new Error("Decode Error: could not decode globalXpub with key 0x"+o.key.toString("hex"));if(o.key.length!==79||![2,3].includes(o.key[46]))throw new Error("Decode Error: globalXpub has invalid extended pubkey in key 0x"+o.key.toString("hex"));if(o.value.length/4%1!==0)throw new Error("Decode Error: Global GLOBAL_XPUB value length should be multiple of 4");const c=o.key.slice(1),a={masterFingerprint:o.value.slice(0,4),extendedPubkey:c,path:"m"};for(const u of t(o.value.length/4-1)){const f=o.value.readUInt32LE(u*4+4),l=!!(f&2147483648),d=f&2147483647;a.path+="/"+d.toString(10)+(l?"'":"")}return a}Vr.decode=n;function r(o){const c=Buffer.from([e.GlobalTypes.GLOBAL_XPUB]),a=Buffer.concat([c,o.extendedPubkey]),u=o.path.split("/"),f=Buffer.allocUnsafe(u.length*4);o.masterFingerprint.copy(f,0);let l=4;return u.slice(1).forEach(d=>{const y=d.slice(-1)==="'";let g=2147483647&parseInt(y?d.slice(0,-1):d,10);y&&(g+=2147483648),f.writeUInt32LE(g,l),l+=4}),{key:a,value:f}}Vr.encode=r,Vr.expected="{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }";function i(o){const c=o.extendedPubkey,a=o.masterFingerprint,u=o.path;return Buffer.isBuffer(c)&&c.length===78&&[2,3].indexOf(c[45])>-1&&Buffer.isBuffer(a)&&a.length===4&&typeof u=="string"&&!!u.match(/^m(\/\d+'?)*$/)}Vr.check=i;function s(o,c,a){const u=c.extendedPubkey.toString("hex");return a.has(u)?!1:(a.add(u),o.filter(f=>f.extendedPubkey.equals(c.extendedPubkey)).length===0)}return Vr.canAddToArray=s,Vr}var Vc={},Bp;function sA(){if(Bp)return Vc;Bp=1,Object.defineProperty(Vc,"__esModule",{value:!0});const e=Mt();function t(n){return{key:Buffer.from([e.GlobalTypes.UNSIGNED_TX]),value:n.toBuffer()}}return Vc.encode=t,Vc}var Lr={},Np;function oA(){if(Np)return Lr;Np=1,Object.defineProperty(Lr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.FINAL_SCRIPTSIG)throw new Error("Decode Error: could not decode finalScriptSig with key 0x"+s.key.toString("hex"));return s.value}Lr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.FINAL_SCRIPTSIG]),value:s}}Lr.encode=n,Lr.expected="Buffer";function r(s){return Buffer.isBuffer(s)}Lr.check=r;function i(s,o){return!!s&&!!o&&s.finalScriptSig===void 0}return Lr.canAdd=i,Lr}var $r={},kp;function cA(){if(kp)return $r;kp=1,Object.defineProperty($r,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.FINAL_SCRIPTWITNESS)throw new Error("Decode Error: could not decode finalScriptWitness with key 0x"+s.key.toString("hex"));return s.value}$r.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.FINAL_SCRIPTWITNESS]),value:s}}$r.encode=n,$r.expected="Buffer";function r(s){return Buffer.isBuffer(s)}$r.check=r;function i(s,o){return!!s&&!!o&&s.finalScriptWitness===void 0}return $r.canAdd=i,$r}var Dr={},Pp;function aA(){if(Pp)return Dr;Pp=1,Object.defineProperty(Dr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.NON_WITNESS_UTXO)throw new Error("Decode Error: could not decode nonWitnessUtxo with key 0x"+s.key.toString("hex"));return s.value}Dr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.NON_WITNESS_UTXO]),value:s}}Dr.encode=n,Dr.expected="Buffer";function r(s){return Buffer.isBuffer(s)}Dr.check=r;function i(s,o){return!!s&&!!o&&s.nonWitnessUtxo===void 0}return Dr.canAdd=i,Dr}var jr={},Rp;function uA(){if(Rp)return jr;Rp=1,Object.defineProperty(jr,"__esModule",{value:!0});const e=Mt();function t(o){if(o.key[0]!==e.InputTypes.PARTIAL_SIG)throw new Error("Decode Error: could not decode partialSig with key 0x"+o.key.toString("hex"));if(!(o.key.length===34||o.key.length===66)||![2,3,4].includes(o.key[1]))throw new Error("Decode Error: partialSig has invalid pubkey in key 0x"+o.key.toString("hex"));return{pubkey:o.key.slice(1),signature:o.value}}jr.decode=t;function n(o){const c=Buffer.from([e.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([c,o.pubkey]),value:o.signature}}jr.encode=n,jr.expected="{ pubkey: Buffer; signature: Buffer; }";function r(o){return Buffer.isBuffer(o.pubkey)&&Buffer.isBuffer(o.signature)&&[33,65].includes(o.pubkey.length)&&[2,3,4].includes(o.pubkey[0])&&i(o.signature)}jr.check=r;function i(o){if(!Buffer.isBuffer(o)||o.length<9||o[0]!==48||o.length!==o[1]+3||o[2]!==2)return!1;const c=o[3];if(c>33||c<1||o[3+c+1]!==2)return!1;const a=o[3+c+2];return!(a>33||a<1||o.length!==3+c+2+a+2)}function s(o,c,a){const u=c.pubkey.toString("hex");return a.has(u)?!1:(a.add(u),o.filter(f=>f.pubkey.equals(c.pubkey)).length===0)}return jr.canAddToArray=s,jr}var Kr={},Up;function fA(){if(Up)return Kr;Up=1,Object.defineProperty(Kr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+s.key.toString("hex"));return s.value.toString("utf8")}Kr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.POR_COMMITMENT]),value:Buffer.from(s,"utf8")}}Kr.encode=n,Kr.expected="string";function r(s){return typeof s=="string"}Kr.check=r;function i(s,o){return!!s&&!!o&&s.porCommitment===void 0}return Kr.canAdd=i,Kr}var Gr={},Cp;function lA(){if(Cp)return Gr;Cp=1,Object.defineProperty(Gr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.SIGHASH_TYPE)throw new Error("Decode Error: could not decode sighashType with key 0x"+s.key.toString("hex"));return s.value.readUInt32LE(0)}Gr.decode=t;function n(s){const o=Buffer.from([e.InputTypes.SIGHASH_TYPE]),c=Buffer.allocUnsafe(4);return c.writeUInt32LE(s,0),{key:o,value:c}}Gr.encode=n,Gr.expected="number";function r(s){return typeof s=="number"}Gr.check=r;function i(s,o){return!!s&&!!o&&s.sighashType===void 0}return Gr.canAdd=i,Gr}var Wr={},Hp;function hA(){if(Hp)return Wr;Hp=1,Object.defineProperty(Wr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.TAP_KEY_SIG||s.key.length!==1)throw new Error("Decode Error: could not decode tapKeySig with key 0x"+s.key.toString("hex"));if(!r(s.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return s.value}Wr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.TAP_KEY_SIG]),value:s}}Wr.encode=n,Wr.expected="Buffer";function r(s){return Buffer.isBuffer(s)&&(s.length===64||s.length===65)}Wr.check=r;function i(s,o){return!!s&&!!o&&s.tapKeySig===void 0}return Wr.canAdd=i,Wr}var Xr={},Fp;function dA(){if(Fp)return Xr;Fp=1,Object.defineProperty(Xr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.TAP_LEAF_SCRIPT)throw new Error("Decode Error: could not decode tapLeafScript with key 0x"+s.key.toString("hex"));if((s.key.length-2)%32!==0)throw new Error("Decode Error: tapLeafScript has invalid control block in key 0x"+s.key.toString("hex"));const o=s.value[s.value.length-1];if((s.key[1]&254)!==o)throw new Error("Decode Error: tapLeafScript bad leaf version in key 0x"+s.key.toString("hex"));const c=s.value.slice(0,-1);return{controlBlock:s.key.slice(1),script:c,leafVersion:o}}Xr.decode=t;function n(s){const o=Buffer.from([e.InputTypes.TAP_LEAF_SCRIPT]),c=Buffer.from([s.leafVersion]);return{key:Buffer.concat([o,s.controlBlock]),value:Buffer.concat([s.script,c])}}Xr.encode=n,Xr.expected="{ controlBlock: Buffer; leafVersion: number, script: Buffer; }";function r(s){return Buffer.isBuffer(s.controlBlock)&&(s.controlBlock.length-1)%32===0&&(s.controlBlock[0]&254)===s.leafVersion&&Buffer.isBuffer(s.script)}Xr.check=r;function i(s,o,c){const a=o.controlBlock.toString("hex");return c.has(a)?!1:(c.add(a),s.filter(u=>u.controlBlock.equals(o.controlBlock)).length===0)}return Xr.canAddToArray=i,Xr}var zr={},Mp;function pA(){if(Mp)return zr;Mp=1,Object.defineProperty(zr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.TAP_MERKLE_ROOT||s.key.length!==1)throw new Error("Decode Error: could not decode tapMerkleRoot with key 0x"+s.key.toString("hex"));if(!r(s.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return s.value}zr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.TAP_MERKLE_ROOT]),value:s}}zr.encode=n,zr.expected="Buffer";function r(s){return Buffer.isBuffer(s)&&s.length===32}zr.check=r;function i(s,o){return!!s&&!!o&&s.tapMerkleRoot===void 0}return zr.canAdd=i,zr}var Yr={},qp;function yA(){if(qp)return Yr;qp=1,Object.defineProperty(Yr,"__esModule",{value:!0});const e=Mt();function t(s){if(s.key[0]!==e.InputTypes.TAP_SCRIPT_SIG)throw new Error("Decode Error: could not decode tapScriptSig with key 0x"+s.key.toString("hex"));if(s.key.length!==65)throw new Error("Decode Error: tapScriptSig has invalid key 0x"+s.key.toString("hex"));if(s.value.length!==64&&s.value.length!==65)throw new Error("Decode Error: tapScriptSig has invalid signature in key 0x"+s.key.toString("hex"));const o=s.key.slice(1,33),c=s.key.slice(33);return{pubkey:o,leafHash:c,signature:s.value}}Yr.decode=t;function n(s){const o=Buffer.from([e.InputTypes.TAP_SCRIPT_SIG]);return{key:Buffer.concat([o,s.pubkey,s.leafHash]),value:s.signature}}Yr.encode=n,Yr.expected="{ pubkey: Buffer; leafHash: Buffer; signature: Buffer; }";function r(s){return Buffer.isBuffer(s.pubkey)&&Buffer.isBuffer(s.leafHash)&&Buffer.isBuffer(s.signature)&&s.pubkey.length===32&&s.leafHash.length===32&&(s.signature.length===64||s.signature.length===65)}Yr.check=r;function i(s,o,c){const a=o.pubkey.toString("hex")+o.leafHash.toString("hex");return c.has(a)?!1:(c.add(a),s.filter(u=>u.pubkey.equals(o.pubkey)&&u.leafHash.equals(o.leafHash)).length===0)}return Yr.canAddToArray=i,Yr}var Zr={},lr={},us={},Vp;function ts(){if(Vp)return us;Vp=1,Object.defineProperty(us,"__esModule",{value:!0});const e=9007199254740991;function t(s){if(s<0||s>e||s%1!==0)throw new RangeError("value out of range")}function n(s,o,c){if(t(s),o||(o=Buffer.allocUnsafe(i(s))),!Buffer.isBuffer(o))throw new TypeError("buffer must be a Buffer instance");return c||(c=0),s<253?(o.writeUInt8(s,c),Object.assign(n,{bytes:1})):s<=65535?(o.writeUInt8(253,c),o.writeUInt16LE(s,c+1),Object.assign(n,{bytes:3})):s<=4294967295?(o.writeUInt8(254,c),o.writeUInt32LE(s,c+1),Object.assign(n,{bytes:5})):(o.writeUInt8(255,c),o.writeUInt32LE(s>>>0,c+1),o.writeUInt32LE(s/4294967296|0,c+5),Object.assign(n,{bytes:9})),o}us.encode=n;function r(s,o){if(!Buffer.isBuffer(s))throw new TypeError("buffer must be a Buffer instance");o||(o=0);const c=s.readUInt8(o);if(c<253)return Object.assign(r,{bytes:1}),c;if(c===253)return Object.assign(r,{bytes:3}),s.readUInt16LE(o+1);if(c===254)return Object.assign(r,{bytes:5}),s.readUInt32LE(o+1);{Object.assign(r,{bytes:9});const a=s.readUInt32LE(o+1),f=s.readUInt32LE(o+5)*4294967296+a;return t(f),f}}us.decode=r;function i(s){return t(s),s<253?1:s<=65535?3:s<=4294967295?5:9}return us.encodingLength=i,us}var Lp;function Ah(){if(Lp)return lr;Lp=1,Object.defineProperty(lr,"__esModule",{value:!0});const e=ts();lr.range=c=>[...Array(c).keys()];function t(c){if(c.length<1)return c;let a=c.length-1,u=0;for(let f=0;f<c.length/2;f++)u=c[f],c[f]=c[a],c[a]=u,a--;return c}lr.reverseBuffer=t;function n(c){const a=c.map(r);return a.push(Buffer.from([0])),Buffer.concat(a)}lr.keyValsToBuffer=n;function r(c){const a=c.key.length,u=c.value.length,f=e.encodingLength(a),l=e.encodingLength(u),d=Buffer.allocUnsafe(f+a+l+u);return e.encode(a,d,0),c.key.copy(d,f),e.encode(u,d,f+a),c.value.copy(d,f+a+l),d}lr.keyValToBuffer=r;function i(c,a){if(typeof c!="number")throw new Error("cannot write a non-number as a number");if(c<0)throw new Error("specified a negative value for writing an unsigned value");if(c>a)throw new Error("RangeError: value out of range");if(Math.floor(c)!==c)throw new Error("value has a fractional component")}function s(c,a){const u=c.readUInt32LE(a);let f=c.readUInt32LE(a+4);return f*=4294967296,i(f+u,9007199254740991),f+u}lr.readUInt64LE=s;function o(c,a,u){return i(a,9007199254740991),c.writeInt32LE(a&-1,u),c.writeUInt32LE(Math.floor(a/4294967296),u+4),u+8}return lr.writeUInt64LE=o,lr}var $p;function gA(){if($p)return Zr;$p=1,Object.defineProperty(Zr,"__esModule",{value:!0});const e=Mt(),t=Ah(),n=ts();function r(c){if(c.key[0]!==e.InputTypes.WITNESS_UTXO)throw new Error("Decode Error: could not decode witnessUtxo with key 0x"+c.key.toString("hex"));const a=t.readUInt64LE(c.value,0);let u=8;const f=n.decode(c.value,u);u+=n.encodingLength(f);const l=c.value.slice(u);if(l.length!==f)throw new Error("Decode Error: WITNESS_UTXO script is not proper length");return{script:l,value:a}}Zr.decode=r;function i(c){const{script:a,value:u}=c,f=n.encodingLength(a.length),l=Buffer.allocUnsafe(8+f+a.length);return t.writeUInt64LE(l,u,0),n.encode(a.length,l,8),a.copy(l,8+f),{key:Buffer.from([e.InputTypes.WITNESS_UTXO]),value:l}}Zr.encode=i,Zr.expected="{ script: Buffer; value: number; }";function s(c){return Buffer.isBuffer(c.script)&&typeof c.value=="number"}Zr.check=s;function o(c,a){return!!c&&!!a&&c.witnessUtxo===void 0}return Zr.canAdd=o,Zr}var Jr={},Dp;function mA(){if(Dp)return Jr;Dp=1,Object.defineProperty(Jr,"__esModule",{value:!0});const e=Mt(),t=ts();function n(o){if(o.key[0]!==e.OutputTypes.TAP_TREE||o.key.length!==1)throw new Error("Decode Error: could not decode tapTree with key 0x"+o.key.toString("hex"));let c=0;const a=[];for(;c<o.value.length;){const u=o.value[c++],f=o.value[c++],l=t.decode(o.value,c);c+=t.encodingLength(l),a.push({depth:u,leafVersion:f,script:o.value.slice(c,c+l)}),c+=l}return{leaves:a}}Jr.decode=n;function r(o){const c=Buffer.from([e.OutputTypes.TAP_TREE]),a=[].concat(...o.leaves.map(u=>[Buffer.of(u.depth,u.leafVersion),t.encode(u.script.length),u.script]));return{key:c,value:Buffer.concat(a)}}Jr.encode=r,Jr.expected="{ leaves: [{ depth: number; leafVersion: number, script: Buffer; }] }";function i(o){return Array.isArray(o.leaves)&&o.leaves.every(c=>c.depth>=0&&c.depth<=128&&(c.leafVersion&254)===c.leafVersion&&Buffer.isBuffer(c.script))}Jr.check=i;function s(o,c){return!!o&&!!c&&o.tapTree===void 0}return Jr.canAdd=s,Jr}var Lc={},jp;function zw(){if(jp)return Lc;jp=1,Object.defineProperty(Lc,"__esModule",{value:!0});const e=r=>[...Array(r).keys()],t=r=>r.length===33&&[2,3].includes(r[0])||r.length===65&&r[0]===4;function n(r,i=t){function s(f){if(f.key[0]!==r)throw new Error("Decode Error: could not decode bip32Derivation with key 0x"+f.key.toString("hex"));const l=f.key.slice(1);if(!i(l))throw new Error("Decode Error: bip32Derivation has invalid pubkey in key 0x"+f.key.toString("hex"));if(f.value.length/4%1!==0)throw new Error("Decode Error: Input BIP32_DERIVATION value length should be multiple of 4");const d={masterFingerprint:f.value.slice(0,4),pubkey:l,path:"m"};for(const y of e(f.value.length/4-1)){const g=f.value.readUInt32LE(y*4+4),m=!!(g&2147483648),E=g&2147483647;d.path+="/"+E.toString(10)+(m?"'":"")}return d}function o(f){const l=Buffer.from([r]),d=Buffer.concat([l,f.pubkey]),y=f.path.split("/"),g=Buffer.allocUnsafe(y.length*4);f.masterFingerprint.copy(g,0);let m=4;return y.slice(1).forEach(E=>{const _=E.slice(-1)==="'";let S=2147483647&parseInt(_?E.slice(0,-1):E,10);_&&(S+=2147483648),g.writeUInt32LE(S,m),m+=4}),{key:d,value:g}}const c="{ masterFingerprint: Buffer; pubkey: Buffer; path: string; }";function a(f){return Buffer.isBuffer(f.pubkey)&&Buffer.isBuffer(f.masterFingerprint)&&typeof f.path=="string"&&i(f.pubkey)&&f.masterFingerprint.length===4}function u(f,l,d){const y=l.pubkey.toString("hex");return d.has(y)?!1:(d.add(y),f.filter(g=>g.pubkey.equals(l.pubkey)).length===0)}return{decode:s,encode:o,check:a,expected:c,canAddToArray:u}}return Lc.makeConverter=n,Lc}var $c={},Kp;function wA(){if(Kp)return $c;Kp=1,Object.defineProperty($c,"__esModule",{value:!0});function e(t){return n;function n(r){let i;if(t.includes(r.key[0])&&(i=r.key.slice(1),!(i.length===33||i.length===65)||![2,3,4].includes(i[0])))throw new Error("Format Error: invalid pubkey in key 0x"+r.key.toString("hex"));return i}}return $c.makeChecker=e,$c}var Dc={},Gp;function bA(){if(Gp)return Dc;Gp=1,Object.defineProperty(Dc,"__esModule",{value:!0});function e(t){function n(c){if(c.key[0]!==t)throw new Error("Decode Error: could not decode redeemScript with key 0x"+c.key.toString("hex"));return c.value}function r(c){return{key:Buffer.from([t]),value:c}}const i="Buffer";function s(c){return Buffer.isBuffer(c)}function o(c,a){return!!c&&!!a&&c.redeemScript===void 0}return{decode:n,encode:r,check:s,expected:i,canAdd:o}}return Dc.makeConverter=e,Dc}var jc={},Wp;function EA(){if(Wp)return jc;Wp=1,Object.defineProperty(jc,"__esModule",{value:!0});const e=ts(),t=zw(),n=i=>i.length===32;function r(i){const s=t.makeConverter(i,n);function o(f){const l=e.decode(f.value),d=e.encodingLength(l),y=s.decode({key:f.key,value:f.value.slice(d+l*32)}),g=new Array(l);for(let m=0,E=d;m<l;m++,E+=32)g[m]=f.value.slice(E,E+32);return Object.assign({},y,{leafHashes:g})}function c(f){const l=s.encode(f),d=e.encodingLength(f.leafHashes.length),y=Buffer.allocUnsafe(d);e.encode(f.leafHashes.length,y);const g=Buffer.concat([y,...f.leafHashes,l.value]);return Object.assign({},l,{value:g})}const a="{ masterFingerprint: Buffer; pubkey: Buffer; path: string; leafHashes: Buffer[]; }";function u(f){return Array.isArray(f.leafHashes)&&f.leafHashes.every(l=>Buffer.isBuffer(l)&&l.length===32)&&s.check(f)}return{decode:o,encode:c,check:u,expected:a,canAddToArray:s.canAddToArray}}return jc.makeConverter=r,jc}var Kc={},Xp;function _A(){if(Xp)return Kc;Xp=1,Object.defineProperty(Kc,"__esModule",{value:!0});function e(t){function n(c){if(c.key[0]!==t||c.key.length!==1)throw new Error("Decode Error: could not decode tapInternalKey with key 0x"+c.key.toString("hex"));if(c.value.length!==32)throw new Error("Decode Error: tapInternalKey not a 32-byte x-only pubkey");return c.value}function r(c){return{key:Buffer.from([t]),value:c}}const i="Buffer";function s(c){return Buffer.isBuffer(c)&&c.length===32}function o(c,a){return!!c&&!!a&&c.tapInternalKey===void 0}return{decode:n,encode:r,check:s,expected:i,canAdd:o}}return Kc.makeConverter=e,Kc}var Gc={},zp;function SA(){if(zp)return Gc;zp=1,Object.defineProperty(Gc,"__esModule",{value:!0});function e(t){function n(c){if(c.key[0]!==t)throw new Error("Decode Error: could not decode witnessScript with key 0x"+c.key.toString("hex"));return c.value}function r(c){return{key:Buffer.from([t]),value:c}}const i="Buffer";function s(c){return Buffer.isBuffer(c)}function o(c,a){return!!c&&!!a&&c.witnessScript===void 0}return{decode:n,encode:r,check:s,expected:i,canAdd:o}}return Gc.makeConverter=e,Gc}var Yp;function vh(){if(Yp)return as;Yp=1,Object.defineProperty(as,"__esModule",{value:!0});const e=Mt(),t=iA(),n=sA(),r=oA(),i=cA(),s=aA(),o=uA(),c=fA(),a=lA(),u=hA(),f=dA(),l=pA(),d=yA(),y=gA(),g=mA(),m=zw(),E=wA(),_=bA(),S=EA(),w=_A(),T=SA(),O={unsignedTx:n,globalXpub:t,checkPubkey:E.makeChecker([])};as.globals=O;const A={nonWitnessUtxo:s,partialSig:o,sighashType:a,finalScriptSig:r,finalScriptWitness:i,porCommitment:c,witnessUtxo:y,bip32Derivation:m.makeConverter(e.InputTypes.BIP32_DERIVATION),redeemScript:_.makeConverter(e.InputTypes.REDEEM_SCRIPT),witnessScript:T.makeConverter(e.InputTypes.WITNESS_SCRIPT),checkPubkey:E.makeChecker([e.InputTypes.PARTIAL_SIG,e.InputTypes.BIP32_DERIVATION]),tapKeySig:u,tapScriptSig:d,tapLeafScript:f,tapBip32Derivation:S.makeConverter(e.InputTypes.TAP_BIP32_DERIVATION),tapInternalKey:w.makeConverter(e.InputTypes.TAP_INTERNAL_KEY),tapMerkleRoot:l};as.inputs=A;const R={bip32Derivation:m.makeConverter(e.OutputTypes.BIP32_DERIVATION),redeemScript:_.makeConverter(e.OutputTypes.REDEEM_SCRIPT),witnessScript:T.makeConverter(e.OutputTypes.WITNESS_SCRIPT),checkPubkey:E.makeChecker([e.OutputTypes.BIP32_DERIVATION]),tapBip32Derivation:S.makeConverter(e.OutputTypes.TAP_BIP32_DERIVATION),tapTree:g,tapInternalKey:w.makeConverter(e.OutputTypes.TAP_INTERNAL_KEY)};return as.outputs=R,as}var Zp;function TA(){if(Zp)return cs;Zp=1,Object.defineProperty(cs,"__esModule",{value:!0});const e=vh(),t=Ah(),n=ts(),r=Mt();function i(c,a){let u=0;function f(){const R=n.decode(c,u);u+=n.encodingLength(R);const M=c.slice(u,u+R);return u+=R,M}function l(){const R=c.readUInt32BE(u);return u+=4,R}function d(){const R=c.readUInt8(u);return u+=1,R}function y(){const R=f(),M=f();return{key:R,value:M}}function g(){if(u>=c.length)throw new Error("Format Error: Unexpected End of PSBT");const R=c.readUInt8(u)===0;return R&&u++,R}if(l()!==1886610036)throw new Error("Format Error: Invalid Magic Number");if(d()!==255)throw new Error("Format Error: Magic Number must be followed by 0xff separator");const m=[],E={};for(;!g();){const R=y(),M=R.key.toString("hex");if(E[M])throw new Error("Format Error: Keys must be unique for global keymap: key "+M);E[M]=1,m.push(R)}const _=m.filter(R=>R.key[0]===r.GlobalTypes.UNSIGNED_TX);if(_.length!==1)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const S=a(_[0].value),{inputCount:w,outputCount:T}=S.getInputOutputCounts(),O=[],A=[];for(const R of t.range(w)){const M={},v=[];for(;!g();){const U=y(),V=U.key.toString("hex");if(M[V])throw new Error("Format Error: Keys must be unique for each input: input index "+R+" key "+V);M[V]=1,v.push(U)}O.push(v)}for(const R of t.range(T)){const M={},v=[];for(;!g();){const U=y(),V=U.key.toString("hex");if(M[V])throw new Error("Format Error: Keys must be unique for each output: output index "+R+" key "+V);M[V]=1,v.push(U)}A.push(v)}return o(S,{globalMapKeyVals:m,inputKeyVals:O,outputKeyVals:A})}cs.psbtFromBuffer=i;function s(c,a,u){if(!a.equals(Buffer.from([u])))throw new Error(`Format Error: Invalid ${c} key: ${a.toString("hex")}`)}cs.checkKeyBuffer=s;function o(c,{globalMapKeyVals:a,inputKeyVals:u,outputKeyVals:f}){const l={unsignedTx:c};let d=0;for(const _ of a)switch(_.key[0]){case r.GlobalTypes.UNSIGNED_TX:if(s("global",_.key,r.GlobalTypes.UNSIGNED_TX),d>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");d++;break;case r.GlobalTypes.GLOBAL_XPUB:l.globalXpub===void 0&&(l.globalXpub=[]),l.globalXpub.push(e.globals.globalXpub.decode(_));break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(_)}const y=u.length,g=f.length,m=[],E=[];for(const _ of t.range(y)){const S={};for(const w of u[_])switch(e.inputs.checkPubkey(w),w.key[0]){case r.InputTypes.NON_WITNESS_UTXO:if(s("input",w.key,r.InputTypes.NON_WITNESS_UTXO),S.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");S.nonWitnessUtxo=e.inputs.nonWitnessUtxo.decode(w);break;case r.InputTypes.WITNESS_UTXO:if(s("input",w.key,r.InputTypes.WITNESS_UTXO),S.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");S.witnessUtxo=e.inputs.witnessUtxo.decode(w);break;case r.InputTypes.PARTIAL_SIG:S.partialSig===void 0&&(S.partialSig=[]),S.partialSig.push(e.inputs.partialSig.decode(w));break;case r.InputTypes.SIGHASH_TYPE:if(s("input",w.key,r.InputTypes.SIGHASH_TYPE),S.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");S.sighashType=e.inputs.sighashType.decode(w);break;case r.InputTypes.REDEEM_SCRIPT:if(s("input",w.key,r.InputTypes.REDEEM_SCRIPT),S.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");S.redeemScript=e.inputs.redeemScript.decode(w);break;case r.InputTypes.WITNESS_SCRIPT:if(s("input",w.key,r.InputTypes.WITNESS_SCRIPT),S.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");S.witnessScript=e.inputs.witnessScript.decode(w);break;case r.InputTypes.BIP32_DERIVATION:S.bip32Derivation===void 0&&(S.bip32Derivation=[]),S.bip32Derivation.push(e.inputs.bip32Derivation.decode(w));break;case r.InputTypes.FINAL_SCRIPTSIG:s("input",w.key,r.InputTypes.FINAL_SCRIPTSIG),S.finalScriptSig=e.inputs.finalScriptSig.decode(w);break;case r.InputTypes.FINAL_SCRIPTWITNESS:s("input",w.key,r.InputTypes.FINAL_SCRIPTWITNESS),S.finalScriptWitness=e.inputs.finalScriptWitness.decode(w);break;case r.InputTypes.POR_COMMITMENT:s("input",w.key,r.InputTypes.POR_COMMITMENT),S.porCommitment=e.inputs.porCommitment.decode(w);break;case r.InputTypes.TAP_KEY_SIG:s("input",w.key,r.InputTypes.TAP_KEY_SIG),S.tapKeySig=e.inputs.tapKeySig.decode(w);break;case r.InputTypes.TAP_SCRIPT_SIG:S.tapScriptSig===void 0&&(S.tapScriptSig=[]),S.tapScriptSig.push(e.inputs.tapScriptSig.decode(w));break;case r.InputTypes.TAP_LEAF_SCRIPT:S.tapLeafScript===void 0&&(S.tapLeafScript=[]),S.tapLeafScript.push(e.inputs.tapLeafScript.decode(w));break;case r.InputTypes.TAP_BIP32_DERIVATION:S.tapBip32Derivation===void 0&&(S.tapBip32Derivation=[]),S.tapBip32Derivation.push(e.inputs.tapBip32Derivation.decode(w));break;case r.InputTypes.TAP_INTERNAL_KEY:s("input",w.key,r.InputTypes.TAP_INTERNAL_KEY),S.tapInternalKey=e.inputs.tapInternalKey.decode(w);break;case r.InputTypes.TAP_MERKLE_ROOT:s("input",w.key,r.InputTypes.TAP_MERKLE_ROOT),S.tapMerkleRoot=e.inputs.tapMerkleRoot.decode(w);break;default:S.unknownKeyVals||(S.unknownKeyVals=[]),S.unknownKeyVals.push(w)}m.push(S)}for(const _ of t.range(g)){const S={};for(const w of f[_])switch(e.outputs.checkPubkey(w),w.key[0]){case r.OutputTypes.REDEEM_SCRIPT:if(s("output",w.key,r.OutputTypes.REDEEM_SCRIPT),S.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");S.redeemScript=e.outputs.redeemScript.decode(w);break;case r.OutputTypes.WITNESS_SCRIPT:if(s("output",w.key,r.OutputTypes.WITNESS_SCRIPT),S.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");S.witnessScript=e.outputs.witnessScript.decode(w);break;case r.OutputTypes.BIP32_DERIVATION:S.bip32Derivation===void 0&&(S.bip32Derivation=[]),S.bip32Derivation.push(e.outputs.bip32Derivation.decode(w));break;case r.OutputTypes.TAP_INTERNAL_KEY:s("output",w.key,r.OutputTypes.TAP_INTERNAL_KEY),S.tapInternalKey=e.outputs.tapInternalKey.decode(w);break;case r.OutputTypes.TAP_TREE:s("output",w.key,r.OutputTypes.TAP_TREE),S.tapTree=e.outputs.tapTree.decode(w);break;case r.OutputTypes.TAP_BIP32_DERIVATION:S.tapBip32Derivation===void 0&&(S.tapBip32Derivation=[]),S.tapBip32Derivation.push(e.outputs.tapBip32Derivation.decode(w));break;default:S.unknownKeyVals||(S.unknownKeyVals=[]),S.unknownKeyVals.push(w)}E.push(S)}return{globalMap:l,inputs:m,outputs:E}}return cs.psbtFromKeyVals=o,cs}var wo={},Jp;function xA(){if(Jp)return wo;Jp=1,Object.defineProperty(wo,"__esModule",{value:!0});const e=vh(),t=Ah();function n({globalMap:o,inputs:c,outputs:a}){const{globalKeyVals:u,inputKeyVals:f,outputKeyVals:l}=s({globalMap:o,inputs:c,outputs:a}),d=t.keyValsToBuffer(u),y=_=>_.length===0?[Buffer.from([0])]:_.map(t.keyValsToBuffer),g=y(f),m=y(l),E=Buffer.allocUnsafe(5);return E.writeUIntBE(482972169471,0,5),Buffer.concat([E,d].concat(g,m))}wo.psbtToBuffer=n;const r=(o,c)=>o.key.compare(c.key);function i(o,c){const a=new Set,u=Object.entries(o).reduce((l,[d,y])=>{if(d==="unknownKeyVals")return l;const g=c[d];if(g===void 0)return l;const m=(Array.isArray(y)?y:[y]).map(g.encode);return m.map(_=>_.key.toString("hex")).forEach(_=>{if(a.has(_))throw new Error("Serialize Error: Duplicate key: "+_);a.add(_)}),l.concat(m)},[]),f=o.unknownKeyVals?o.unknownKeyVals.filter(l=>!a.has(l.key.toString("hex"))):[];return u.concat(f).sort(r)}function s({globalMap:o,inputs:c,outputs:a}){return{globalKeyVals:i(o,e.globals),inputKeyVals:c.map(u=>i(u,e.inputs)),outputKeyVals:a.map(u=>i(u,e.outputs))}}return wo.psbtToKeyVals=s,wo}var Qp;function Yw(){return Qp||(Qp=1,(function(e){function t(n){for(var r in n)e.hasOwnProperty(r)||(e[r]=n[r])}Object.defineProperty(e,"__esModule",{value:!0}),t(TA()),t(xA())})(Nf)),Nf}var ey;function AA(){if(ey)return qc;ey=1,Object.defineProperty(qc,"__esModule",{value:!0});const e=Yw();function t(s){const o=s[0],c=e.psbtToKeyVals(o),a=s.slice(1);if(a.length===0)throw new Error("Combine: Nothing to combine");const u=r(o);if(u===void 0)throw new Error("Combine: Self missing transaction");const f=i(c.globalKeyVals),l=c.inputKeyVals.map(i),d=c.outputKeyVals.map(i);for(const y of a){const g=r(y);if(g===void 0||!g.toBuffer().equals(u.toBuffer()))throw new Error("Combine: One of the Psbts does not have the same transaction.");const m=e.psbtToKeyVals(y);i(m.globalKeyVals).forEach(n(f,c.globalKeyVals,m.globalKeyVals)),m.inputKeyVals.map(i).forEach((w,T)=>w.forEach(n(l[T],c.inputKeyVals[T],m.inputKeyVals[T]))),m.outputKeyVals.map(i).forEach((w,T)=>w.forEach(n(d[T],c.outputKeyVals[T],m.outputKeyVals[T])))}return e.psbtFromKeyVals(u,{globalMapKeyVals:c.globalKeyVals,inputKeyVals:c.inputKeyVals,outputKeyVals:c.outputKeyVals})}qc.combine=t;function n(s,o,c){return a=>{if(s.has(a))return;const u=c.filter(f=>f.key.toString("hex")===a)[0];o.push(u),s.add(a)}}function r(s){return s.globalMap.unsignedTx}function i(s){const o=new Set;return s.forEach(c=>{const a=c.key.toString("hex");if(o.has(a))throw new Error("Combine: KeyValue Map keys should be unique");o.add(a)}),o}return qc}var Pf={},ty;function Zw(){return ty||(ty=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0});const t=vh();function n(y,g){const m=y[g];if(m===void 0)throw new Error(`No input #${g}`);return m}e.checkForInput=n;function r(y,g){const m=y[g];if(m===void 0)throw new Error(`No output #${g}`);return m}e.checkForOutput=r;function i(y,g,m){if(y.key[0]<m)throw new Error("Use the method for your specific key instead of addUnknownKeyVal*");if(g&&g.filter(E=>E.key.equals(y.key)).length!==0)throw new Error(`Duplicate Key: ${y.key.toString("hex")}`)}e.checkHasKey=i;function s(y){let g=0;return Object.keys(y).forEach(m=>{Number(isNaN(Number(m)))&&g++}),g}e.getEnumLength=s;function o(y,g){let m=!1;if(g.nonWitnessUtxo||g.witnessUtxo){const E=!!g.redeemScript,_=!!g.witnessScript,S=!E||!!g.finalScriptSig,w=!_||!!g.finalScriptWitness,T=!!g.finalScriptSig||!!g.finalScriptWitness;m=S&&w&&T}if(m===!1)throw new Error(`Input #${y} has too much or too little data to clean`)}e.inputCheckUncleanFinalized=o;function c(y,g,m,E){throw new Error(`Data for ${y} key ${g} is incorrect: Expected ${m} and got ${JSON.stringify(E)}`)}function a(y){return(g,m)=>{for(const E of Object.keys(g)){const _=g[E],{canAdd:S,canAddToArray:w,check:T,expected:O}=t[y+"s"][E]||{},A=!!w;if(T)if(A){if(!Array.isArray(_)||m[E]&&!Array.isArray(m[E]))throw new Error(`Key type ${E} must be an array`);_.every(T)||c(y,E,O,_);const R=m[E]||[],M=new Set;if(!_.every(v=>w(R,v,M)))throw new Error("Can not add duplicate data to array");m[E]=R.concat(_)}else{if(T(_)||c(y,E,O,_),!S(m,_))throw new Error(`Can not add duplicate data to ${y}`);m[E]=_}}}}e.updateGlobal=a("global"),e.updateInput=a("input"),e.updateOutput=a("output");function u(y,g){const m=y.length-1,E=n(y,m);e.updateInput(g,E)}e.addInputAttributes=u;function f(y,g){const m=y.length-1,E=r(y,m);e.updateOutput(g,E)}e.addOutputAttributes=f;function l(y,g){if(!Buffer.isBuffer(g)||g.length<4)throw new Error("Set Version: Invalid Transaction");return g.writeUInt32LE(y,0),g}e.defaultVersionSetter=l;function d(y,g){if(!Buffer.isBuffer(g)||g.length<4)throw new Error("Set Locktime: Invalid Transaction");return g.writeUInt32LE(y,g.length-4),g}e.defaultLocktimeSetter=d})(Pf)),Pf}var ny;function vA(){if(ny)return Mc;ny=1,Object.defineProperty(Mc,"__esModule",{value:!0});const e=AA(),t=Yw(),n=Mt(),r=Zw();class i{constructor(o){this.inputs=[],this.outputs=[],this.globalMap={unsignedTx:o}}static fromBase64(o,c){const a=Buffer.from(o,"base64");return this.fromBuffer(a,c)}static fromHex(o,c){const a=Buffer.from(o,"hex");return this.fromBuffer(a,c)}static fromBuffer(o,c){const a=t.psbtFromBuffer(o,c),u=new this(a.globalMap.unsignedTx);return Object.assign(u,a),u}toBase64(){return this.toBuffer().toString("base64")}toHex(){return this.toBuffer().toString("hex")}toBuffer(){return t.psbtToBuffer(this)}updateGlobal(o){return r.updateGlobal(o,this.globalMap),this}updateInput(o,c){const a=r.checkForInput(this.inputs,o);return r.updateInput(c,a),this}updateOutput(o,c){const a=r.checkForOutput(this.outputs,o);return r.updateOutput(c,a),this}addUnknownKeyValToGlobal(o){return r.checkHasKey(o,this.globalMap.unknownKeyVals,r.getEnumLength(n.GlobalTypes)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(o),this}addUnknownKeyValToInput(o,c){const a=r.checkForInput(this.inputs,o);return r.checkHasKey(c,a.unknownKeyVals,r.getEnumLength(n.InputTypes)),a.unknownKeyVals||(a.unknownKeyVals=[]),a.unknownKeyVals.push(c),this}addUnknownKeyValToOutput(o,c){const a=r.checkForOutput(this.outputs,o);return r.checkHasKey(c,a.unknownKeyVals,r.getEnumLength(n.OutputTypes)),a.unknownKeyVals||(a.unknownKeyVals=[]),a.unknownKeyVals.push(c),this}addInput(o){this.globalMap.unsignedTx.addInput(o),this.inputs.push({unknownKeyVals:[]});const c=o.unknownKeyVals||[],a=this.inputs.length-1;if(!Array.isArray(c))throw new Error("unknownKeyVals must be an Array");return c.forEach(u=>this.addUnknownKeyValToInput(a,u)),r.addInputAttributes(this.inputs,o),this}addOutput(o){this.globalMap.unsignedTx.addOutput(o),this.outputs.push({unknownKeyVals:[]});const c=o.unknownKeyVals||[],a=this.outputs.length-1;if(!Array.isArray(c))throw new Error("unknownKeyVals must be an Array");return c.forEach(u=>this.addUnknownKeyValToOutput(a,u)),r.addOutputAttributes(this.outputs,o),this}clearFinalizedInput(o){const c=r.checkForInput(this.inputs,o);r.inputCheckUncleanFinalized(o,c);for(const a of Object.keys(c))["witnessUtxo","nonWitnessUtxo","finalScriptSig","finalScriptWitness","unknownKeyVals"].includes(a)||delete c[a];return this}combine(...o){const c=e.combine([this].concat(o));return Object.assign(this,c),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}}return Mc.Psbt=i,Mc}var Qe={},ze={},ry;function dl(){if(ry)return ze;ry=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.signatureBlocksAction=ze.checkInputForSig=ze.pubkeyInScript=ze.pubkeyPositionInScript=ze.witnessStackToScriptWitness=ze.isP2TR=ze.isP2SHScript=ze.isP2WSHScript=ze.isP2WPKH=ze.isP2PKH=ze.isP2PK=ze.isP2MS=void 0;const e=ts(),t=rn(),n=_c(),r=Pr(),i=Ec();function s(y){return g=>{try{return y({output:g}),!0}catch{return!1}}}ze.isP2MS=s(i.p2ms),ze.isP2PK=s(i.p2pk),ze.isP2PKH=s(i.p2pkh),ze.isP2WPKH=s(i.p2wpkh),ze.isP2WSHScript=s(i.p2wsh),ze.isP2SHScript=s(i.p2sh),ze.isP2TR=s(i.p2tr);function o(y){let g=Buffer.allocUnsafe(0);function m(w){g=Buffer.concat([g,Buffer.from(w)])}function E(w){const T=g.length,O=e.encodingLength(w);g=Buffer.concat([g,Buffer.allocUnsafe(O)]),e.encode(w,g,T)}function _(w){E(w.length),m(w)}function S(w){E(w.length),w.forEach(_)}return S(y),g}ze.witnessStackToScriptWitness=o;function c(y,g){const m=(0,r.hash160)(y),E=y.slice(1,33),_=t.decompile(g);if(_===null)throw new Error("Unknown script error");return _.findIndex(S=>typeof S=="number"?!1:S.equals(y)||S.equals(m)||S.equals(E))}ze.pubkeyPositionInScript=c;function a(y,g){return c(y,g)!==-1}ze.pubkeyInScript=a;function u(y,g){return l(y).some(E=>f(E,t.signature.decode,g))}ze.checkInputForSig=u;function f(y,g,m){const{hashType:E}=g(y),_=[];switch(E&n.Transaction.SIGHASH_ANYONECANPAY&&_.push("addInput"),E&31){case n.Transaction.SIGHASH_ALL:break;case n.Transaction.SIGHASH_SINGLE:case n.Transaction.SIGHASH_NONE:_.push("addOutput"),_.push("setInputSequence");break}return _.indexOf(m)===-1}ze.signatureBlocksAction=f;function l(y){let g=[];if((y.partialSig||[]).length===0){if(!y.finalScriptSig&&!y.finalScriptWitness)return[];g=d(y)}else g=y.partialSig;return g.map(m=>m.signature)}function d(y){const g=y.finalScriptSig?t.decompile(y.finalScriptSig)||[]:[],m=y.finalScriptWitness?t.decompile(y.finalScriptWitness)||[]:[];return g.concat(m).filter(E=>Buffer.isBuffer(E)&&t.isCanonicalScriptSignature(E)).map(E=>({signature:E}))}return ze}var iy;function IA(){if(iy)return Qe;iy=1,Object.defineProperty(Qe,"__esModule",{value:!0}),Qe.checkTaprootInputForSigs=Qe.tapTreeFromList=Qe.tapTreeToList=Qe.tweakInternalPubKey=Qe.checkTaprootOutputFields=Qe.checkTaprootInputFields=Qe.isTaprootOutput=Qe.isTaprootInput=Qe.serializeTaprootSignature=Qe.tapScriptFinalizer=Qe.toXOnly=void 0;const e=Xt(),t=_c(),n=dl(),r=Th(),i=Ec(),s=dl(),o=x=>x.length===32?x:x.slice(1,33);Qe.toXOnly=o;function c(x,B,q){const N=P(B,x,q);try{const G=H(B,N).concat(N.script).concat(N.controlBlock);return{finalScriptWitness:(0,n.witnessStackToScriptWitness)(G)}}catch(L){throw new Error(`Can not finalize taproot input #${x}: ${L}`)}}Qe.tapScriptFinalizer=c;function a(x,B){const q=B?Buffer.from([B]):Buffer.from([]);return Buffer.concat([x,q])}Qe.serializeTaprootSignature=a;function u(x){return x&&!!(x.tapInternalKey||x.tapMerkleRoot||x.tapLeafScript&&x.tapLeafScript.length||x.tapBip32Derivation&&x.tapBip32Derivation.length||x.witnessUtxo&&(0,n.isP2TR)(x.witnessUtxo.script))}Qe.isTaprootInput=u;function f(x,B){return x&&!!(x.tapInternalKey||x.tapTree||x.tapBip32Derivation&&x.tapBip32Derivation.length||B&&(0,n.isP2TR)(B))}Qe.isTaprootOutput=f;function l(x,B,q){v(x,B,q),V(x,B,q)}Qe.checkTaprootInputFields=l;function d(x,B,q){U(x,B,q),y(x,B)}Qe.checkTaprootOutputFields=d;function y(x,B){if(!B.tapTree&&!B.tapInternalKey)return;const q=B.tapInternalKey||x.tapInternalKey,N=B.tapTree||x.tapTree;if(q){const{script:L}=x,G=g(q,N);if(L&&!L.equals(G))throw new Error("Error adding output. Script or address missmatch.")}}function g(x,B){const q=B&&_(B.leaves),{output:N}=(0,i.p2tr)({internalPubkey:x,scriptTree:q});return N}function m(x,B){const q=B.tapInternalKey,N=q&&(0,r.tweakKey)(q,B.tapMerkleRoot);if(!N)throw new Error(`Cannot tweak tap internal key for input #${x}. Public key: ${q&&q.toString("hex")}`);return N.x}Qe.tweakInternalPubKey=m;function E(x){if(!(0,e.isTaptree)(x))throw new Error("Cannot convert taptree to tapleaf list. Expecting a tapree structure.");return A(x)}Qe.tapTreeToList=E;function _(x=[]){return x.length===1&&x[0].depth===0?{output:x[0].script,version:x[0].leafVersion}:R(x)}Qe.tapTreeFromList=_;function S(x,B){return T(x).some(N=>(0,s.signatureBlocksAction)(N,w,B))}Qe.checkTaprootInputForSigs=S;function w(x){return{signature:x.slice(0,64),hashType:x.slice(64)[0]||t.Transaction.SIGHASH_DEFAULT}}function T(x){const B=[];if(x.tapKeySig&&B.push(x.tapKeySig),x.tapScriptSig&&B.push(...x.tapScriptSig.map(q=>q.signature)),!B.length){const q=O(x.finalScriptWitness);q&&B.push(q)}return B}function O(x){if(!x)return;const B=x.slice(2);if(B.length===64||B.length===65)return B}function A(x,B=[],q=0){if(q>r.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return x?(0,e.isTapleaf)(x)?(B.push({depth:q,leafVersion:x.version||r.LEAF_VERSION_TAPSCRIPT,script:x.output}),B):(x[0]&&A(x[0],B,q+1),x[1]&&A(x[1],B,q+1),B):[]}function R(x){let B;for(const q of x)if(B=M(q,B),!B)throw new Error("No room left to insert tapleaf in tree");return B}function M(x,B,q=0){if(q>r.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(x.depth===q)return B?void 0:{output:x.script,version:x.leafVersion};if((0,e.isTapleaf)(B))return;const N=M(x,B&&B[0],q+1);if(N)return[N,B&&B[1]];const L=M(x,B&&B[1],q+1);if(L)return[B&&B[0],L]}function v(x,B,q){const N=u(x)&&F(B),L=F(x)&&u(B),G=x===B&&u(B)&&F(B);if(N||L||G)throw new Error(`Invalid arguments for Psbt.${q}. Cannot use both taproot and non-taproot fields.`)}function U(x,B,q){const N=f(x)&&F(B),L=F(x)&&f(B),G=x===B&&f(B)&&F(B);if(N||L||G)throw new Error(`Invalid arguments for Psbt.${q}. Cannot use both taproot and non-taproot fields.`)}function V(x,B,q){if(B.tapMerkleRoot){const N=(B.tapLeafScript||[]).every(G=>K(G,B.tapMerkleRoot)),L=(x.tapLeafScript||[]).every(G=>K(G,B.tapMerkleRoot));if(!N||!L)throw new Error(`Invalid arguments for Psbt.${q}. Tapleaf not part of taptree.`)}else if(x.tapMerkleRoot&&!(B.tapLeafScript||[]).every(L=>K(L,x.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${q}. Tapleaf not part of taptree.`)}function K(x,B){if(!B)return!0;const q=(0,r.tapleafHash)({output:x.script,version:x.leafVersion});return(0,r.rootHashFromPath)(x.controlBlock,q).equals(B)}function H(x,B){const q=(0,r.tapleafHash)({output:B.script,version:B.leafVersion});return(x.tapScriptSig||[]).filter(N=>N.leafHash.equals(q)).map(N=>$(B.script,N)).sort((N,L)=>L.positionInScript-N.positionInScript).map(N=>N.signature)}function $(x,B){return Object.assign({positionInScript:(0,n.pubkeyPositionInScript)(B.pubkey,x)},B)}function P(x,B,q){if(!x.tapScriptSig||!x.tapScriptSig.length)throw new Error(`Can not finalize taproot input #${B}. No tapleaf script signature provided.`);const N=(x.tapLeafScript||[]).sort((L,G)=>L.controlBlock.length-G.controlBlock.length).find(L=>D(L,x.tapScriptSig,q));if(!N)throw new Error(`Can not finalize taproot input #${B}. Signature for tapleaf script not found.`);return N}function D(x,B,q){const N=(0,r.tapleafHash)({output:x.script,version:x.leafVersion});return(!q||q.equals(N))&&B.find(G=>G.leafHash.equals(N))!==void 0}function F(x){return x&&!!(x.redeemScript||x.witnessScript||x.bip32Derivation&&x.bip32Derivation.length)}return Qe}var sy;function OA(){if(sy)return mo;sy=1,Object.defineProperty(mo,"__esModule",{value:!0}),mo.Psbt=void 0;const e=vA(),t=ts(),n=Zw(),r=xh(),i=Eu(),s=Wn(),o=Ec(),c=Th(),a=rn(),u=_c(),f=IA(),l=dl(),d={network:s.bitcoin,maximumFeeRate:5e3};class y{static fromBase64(h,b={}){const I=Buffer.from(h,"base64");return this.fromBuffer(I,b)}static fromHex(h,b={}){const I=Buffer.from(h,"hex");return this.fromBuffer(I,b)}static fromBuffer(h,b={}){const I=e.Psbt.fromBuffer(h,g),C=new y(b,I);return V(C.__CACHE.__TX,C.__CACHE),C}constructor(h={},b=new e.Psbt(new m)){this.data=b,this.opts=Object.assign({},d,h),this.__CACHE={__NON_WITNESS_UTXO_TX_CACHE:[],__NON_WITNESS_UTXO_BUF_CACHE:[],__TX_IN_CACHE:{},__TX:this.data.globalMap.unsignedTx.tx,__UNSAFE_SIGN_NONSEGWIT:!1},this.data.inputs.length===0&&this.setVersion(2);const I=(C,j,W,ie)=>Object.defineProperty(C,j,{enumerable:W,writable:ie});I(this,"__CACHE",!1,!0),I(this,"opts",!1,!0)}get inputCount(){return this.data.inputs.length}get version(){return this.__CACHE.__TX.version}set version(h){this.setVersion(h)}get locktime(){return this.__CACHE.__TX.locktime}set locktime(h){this.setLocktime(h)}get txInputs(){return this.__CACHE.__TX.ins.map(h=>({hash:(0,i.cloneBuffer)(h.hash),index:h.index,sequence:h.sequence}))}get txOutputs(){return this.__CACHE.__TX.outs.map(h=>{let b;try{b=(0,r.fromOutputScript)(h.script,this.opts.network)}catch{}return{script:(0,i.cloneBuffer)(h.script),value:h.value,address:b}})}combine(...h){return this.data.combine(...h.map(b=>b.data)),this}clone(){const h=y.fromBuffer(this.data.toBuffer());return h.opts=JSON.parse(JSON.stringify(this.opts)),h}setMaximumFeeRate(h){O(h),this.opts.maximumFeeRate=h}setVersion(h){O(h),R(this.data.inputs,"setVersion");const b=this.__CACHE;return b.__TX.version=h,b.__EXTRACTED_TX=void 0,this}setLocktime(h){O(h),R(this.data.inputs,"setLocktime");const b=this.__CACHE;return b.__TX.locktime=h,b.__EXTRACTED_TX=void 0,this}setInputSequence(h,b){O(b),R(this.data.inputs,"setInputSequence");const I=this.__CACHE;if(I.__TX.ins.length<=h)throw new Error("Input index too high");return I.__TX.ins[h].sequence=b,I.__EXTRACTED_TX=void 0,this}addInputs(h){return h.forEach(b=>this.addInput(b)),this}addInput(h){if(arguments.length>1||!h||h.hash===void 0||h.index===void 0)throw new Error("Invalid arguments for Psbt.addInput. Requires single object with at least [hash] and [index]");(0,f.checkTaprootInputFields)(h,h,"addInput"),R(this.data.inputs,"addInput"),h.witnessScript&&ne(h.witnessScript);const b=this.__CACHE;this.data.addInput(h);const I=b.__TX.ins[b.__TX.ins.length-1];K(b,I);const C=this.data.inputs.length-1,j=this.data.inputs[C];return j.nonWitnessUtxo&&ye(this.__CACHE,j,C),b.__FEE=void 0,b.__FEE_RATE=void 0,b.__EXTRACTED_TX=void 0,this}addOutputs(h){return h.forEach(b=>this.addOutput(b)),this}addOutput(h){if(arguments.length>1||!h||h.value===void 0||h.address===void 0&&h.script===void 0)throw new Error("Invalid arguments for Psbt.addOutput. Requires single object with at least [script or address] and [value]");R(this.data.inputs,"addOutput");const{address:b}=h;if(typeof b=="string"){const{network:C}=this.opts,j=(0,r.toOutputScript)(b,C);h=Object.assign({},h,{script:j})}(0,f.checkTaprootOutputFields)(h,h,"addOutput");const I=this.__CACHE;return this.data.addOutput(h),I.__FEE=void 0,I.__FEE_RATE=void 0,I.__EXTRACTED_TX=void 0,this}extractTransaction(h){if(!this.data.inputs.every(w))throw new Error("Not finalized");const b=this.__CACHE;if(h||A(this,b,this.opts),b.__EXTRACTED_TX)return b.__EXTRACTED_TX;const I=b.__TX.clone();return J(this.data.inputs,I,b,!0),I}getFeeRate(){return D("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return D("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return(0,n.checkForInput)(this.data.inputs,0),k(this.data.inputs.length).forEach(h=>this.finalizeInput(h)),this}finalizeInput(h,b){const I=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(I)?this._finalizeTaprootInput(h,I,void 0,b):this._finalizeInput(h,I,b)}finalizeTaprootInput(h,b,I=f.tapScriptFinalizer){const C=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(C))return this._finalizeTaprootInput(h,C,b,I);throw new Error(`Cannot finalize input #${h}. Not Taproot.`)}_finalizeInput(h,b,I=F){const{script:C,isP2SH:j,isP2WSH:W,isSegwit:ie}=ue(h,b,this.__CACHE);if(!C)throw new Error(`No script found for input #${h}`);M(b);const{finalScriptSig:Q,finalScriptWitness:fe}=I(h,b,C,ie,j,W);if(Q&&this.data.updateInput(h,{finalScriptSig:Q}),fe&&this.data.updateInput(h,{finalScriptWitness:fe}),!Q&&!fe)throw new Error(`Unknown error finalizing input #${h}`);return this.data.clearFinalizedInput(h),this}_finalizeTaprootInput(h,b,I,C=f.tapScriptFinalizer){if(!b.witnessUtxo)throw new Error(`Cannot finalize input #${h}. Missing withness utxo.`);if(b.tapKeySig){const j=o.p2tr({output:b.witnessUtxo.script,signature:b.tapKeySig}),W=(0,l.witnessStackToScriptWitness)(j.witness);this.data.updateInput(h,{finalScriptWitness:W})}else{const{finalScriptWitness:j}=C(h,b,I);this.data.updateInput(h,{finalScriptWitness:j})}return this.data.clearFinalizedInput(h),this}getInputType(h){const b=(0,n.checkForInput)(this.data.inputs,h),I=Ae(h,b,this.__CACHE),C=oe(I,h,"input",b.redeemScript||It(b.finalScriptSig),b.witnessScript||Oe(b.finalScriptWitness)),j=C.type==="raw"?"":C.type+"-",W=re(C.meaningfulScript);return j+W}inputHasPubkey(h,b){const I=(0,n.checkForInput)(this.data.inputs,h);return tt(b,I,h,this.__CACHE)}inputHasHDKey(h,b){const I=(0,n.checkForInput)(this.data.inputs,h),C=T(b);return!!I.bip32Derivation&&I.bip32Derivation.some(C)}outputHasPubkey(h,b){const I=(0,n.checkForOutput)(this.data.outputs,h);return ut(b,I,h,this.__CACHE)}outputHasHDKey(h,b){const I=(0,n.checkForOutput)(this.data.outputs,h),C=T(b);return!!I.bip32Derivation&&I.bip32Derivation.some(C)}validateSignaturesOfAllInputs(h){return(0,n.checkForInput)(this.data.inputs,0),k(this.data.inputs.length).map(I=>this.validateSignaturesOfInput(I,h)).reduce((I,C)=>C===!0&&I,!0)}validateSignaturesOfInput(h,b,I){const C=this.data.inputs[h];return(0,f.isTaprootInput)(C)?this.validateSignaturesOfTaprootInput(h,b,I):this._validateSignaturesOfInput(h,b,I)}_validateSignaturesOfInput(h,b,I){const C=this.data.inputs[h],j=(C||{}).partialSig;if(!C||!j||j.length<1)throw new Error("No signatures to validate");if(typeof b!="function")throw new Error("Need validator function to validate signatures");const W=I?j.filter(Ne=>Ne.pubkey.equals(I)):j;if(W.length<1)throw new Error("No signatures for this pubkey");const ie=[];let Q,fe,he;for(const Ne of W){const Pe=a.signature.decode(Ne.signature),{hash:nt,script:je}=he!==Pe.hashType?q(h,Object.assign({},C,{sighashType:Pe.hashType}),this.__CACHE,!0):{hash:Q,script:fe};he=Pe.hashType,Q=nt,fe=je,v(Ne.pubkey,je,"verify"),ie.push(b(Ne.pubkey,nt,Pe.signature))}return ie.every(Ne=>Ne===!0)}validateSignaturesOfTaprootInput(h,b,I){const C=this.data.inputs[h],j=(C||{}).tapKeySig,W=(C||{}).tapScriptSig;if(!C&&!j&&!(W&&!W.length))throw new Error("No signatures to validate");if(typeof b!="function")throw new Error("Need validator function to validate signatures");I=I&&(0,f.toXOnly)(I);const ie=I?X(h,C,this.data.inputs,I,this.__CACHE):N(h,C,this.data.inputs,this.__CACHE);if(!ie.length)throw new Error("No signatures for this pubkey");const Q=ie.find(he=>!he.leafHash);let fe=0;if(j&&Q){if(!b(Q.pubkey,Q.hash,G(j)))return!1;fe++}if(W)for(const he of W){const Ne=ie.find(Pe=>he.pubkey.equals(Pe.pubkey));if(Ne){if(!b(he.pubkey,Ne.hash,G(he.signature)))return!1;fe++}}return fe>0}signAllInputsHD(h,b=[u.Transaction.SIGHASH_ALL]){if(!h||!h.publicKey||!h.fingerprint)throw new Error("Need HDSigner to sign input");const I=[];for(const C of k(this.data.inputs.length))try{this.signInputHD(C,h,b),I.push(!0)}catch{I.push(!1)}if(I.every(C=>C===!1))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(h,b=[u.Transaction.SIGHASH_ALL]){return new Promise((I,C)=>{if(!h||!h.publicKey||!h.fingerprint)return C(new Error("Need HDSigner to sign input"));const j=[],W=[];for(const ie of k(this.data.inputs.length))W.push(this.signInputHDAsync(ie,h,b).then(()=>{j.push(!0)},()=>{j.push(!1)}));return Promise.all(W).then(()=>{if(j.every(ie=>ie===!1))return C(new Error("No inputs were signed"));I()})})}signInputHD(h,b,I=[u.Transaction.SIGHASH_ALL]){if(!b||!b.publicKey||!b.fingerprint)throw new Error("Need HDSigner to sign input");return te(h,this.data.inputs,b).forEach(j=>this.signInput(h,j,I)),this}signInputHDAsync(h,b,I=[u.Transaction.SIGHASH_ALL]){return new Promise((C,j)=>{if(!b||!b.publicKey||!b.fingerprint)return j(new Error("Need HDSigner to sign input"));const ie=te(h,this.data.inputs,b).map(Q=>this.signInputAsync(h,Q,I));return Promise.all(ie).then(()=>{C()}).catch(j)})}signAllInputs(h,b){if(!h||!h.publicKey)throw new Error("Need Signer to sign input");const I=[];for(const C of k(this.data.inputs.length))try{this.signInput(C,h,b),I.push(!0)}catch{I.push(!1)}if(I.every(C=>C===!1))throw new Error("No inputs were signed");return this}signAllInputsAsync(h,b){return new Promise((I,C)=>{if(!h||!h.publicKey)return C(new Error("Need Signer to sign input"));const j=[],W=[];for(const[ie]of this.data.inputs.entries())W.push(this.signInputAsync(ie,h,b).then(()=>{j.push(!0)},()=>{j.push(!1)}));return Promise.all(W).then(()=>{if(j.every(ie=>ie===!1))return C(new Error("No inputs were signed"));I()})})}signInput(h,b,I){if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const C=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(C)?this._signTaprootInput(h,C,b,void 0,I):this._signInput(h,b,I)}signTaprootInput(h,b,I,C){if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const j=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(j))return this._signTaprootInput(h,j,b,I,C);throw new Error(`Input #${h} is not of type Taproot.`)}_signInput(h,b,I=[u.Transaction.SIGHASH_ALL]){const{hash:C,sighashType:j}=B(this.data.inputs,h,b.publicKey,this.__CACHE,I),W=[{pubkey:b.publicKey,signature:a.signature.encode(b.sign(C),j)}];return this.data.updateInput(h,{partialSig:W}),this}_signTaprootInput(h,b,I,C,j=[u.Transaction.SIGHASH_DEFAULT]){const W=this.checkTaprootHashesForSig(h,b,I,C,j),ie=W.filter(fe=>!fe.leafHash).map(fe=>(0,f.serializeTaprootSignature)(I.signSchnorr(fe.hash),b.sighashType))[0],Q=W.filter(fe=>!!fe.leafHash).map(fe=>({pubkey:(0,f.toXOnly)(I.publicKey),signature:(0,f.serializeTaprootSignature)(I.signSchnorr(fe.hash),b.sighashType),leafHash:fe.leafHash}));return ie&&this.data.updateInput(h,{tapKeySig:ie}),Q.length&&this.data.updateInput(h,{tapScriptSig:Q}),this}signInputAsync(h,b,I){return Promise.resolve().then(()=>{if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const C=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(C)?this._signTaprootInputAsync(h,C,b,void 0,I):this._signInputAsync(h,b,I)})}signTaprootInputAsync(h,b,I,C){return Promise.resolve().then(()=>{if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const j=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(j))return this._signTaprootInputAsync(h,j,b,I,C);throw new Error(`Input #${h} is not of type Taproot.`)})}_signInputAsync(h,b,I=[u.Transaction.SIGHASH_ALL]){const{hash:C,sighashType:j}=B(this.data.inputs,h,b.publicKey,this.__CACHE,I);return Promise.resolve(b.sign(C)).then(W=>{const ie=[{pubkey:b.publicKey,signature:a.signature.encode(W,j)}];this.data.updateInput(h,{partialSig:ie})})}async _signTaprootInputAsync(h,b,I,C,j=[u.Transaction.SIGHASH_DEFAULT]){const W=this.checkTaprootHashesForSig(h,b,I,C,j),ie=[],Q=W.filter(he=>!he.leafHash)[0];if(Q){const he=Promise.resolve(I.signSchnorr(Q.hash)).then(Ne=>({tapKeySig:(0,f.serializeTaprootSignature)(Ne,b.sighashType)}));ie.push(he)}const fe=W.filter(he=>!!he.leafHash);if(fe.length){const he=fe.map(Ne=>Promise.resolve(I.signSchnorr(Ne.hash)).then(Pe=>({tapScriptSig:[{pubkey:(0,f.toXOnly)(I.publicKey),signature:(0,f.serializeTaprootSignature)(Pe,b.sighashType),leafHash:Ne.leafHash}]})));ie.push(...he)}return Promise.all(ie).then(he=>{he.forEach(Ne=>this.data.updateInput(h,Ne))})}checkTaprootHashesForSig(h,b,I,C,j){if(typeof I.signSchnorr!="function")throw new Error(`Need Schnorr Signer to sign taproot input #${h}.`);const W=X(h,b,this.data.inputs,I.publicKey,this.__CACHE,C,j);if(!W||!W.length)throw new Error(`Can not sign for input #${h} with the key ${I.publicKey.toString("hex")}`);return W}toBuffer(){return _(this.__CACHE),this.data.toBuffer()}toHex(){return _(this.__CACHE),this.data.toHex()}toBase64(){return _(this.__CACHE),this.data.toBase64()}updateGlobal(h){return this.data.updateGlobal(h),this}updateInput(h,b){return b.witnessScript&&ne(b.witnessScript),(0,f.checkTaprootInputFields)(this.data.inputs[h],b,"updateInput"),this.data.updateInput(h,b),b.nonWitnessUtxo&&ye(this.__CACHE,this.data.inputs[h],h),this}updateOutput(h,b){const I=this.data.outputs[h];return(0,f.checkTaprootOutputFields)(I,b,"updateOutput"),this.data.updateOutput(h,b),this}addUnknownKeyValToGlobal(h){return this.data.addUnknownKeyValToGlobal(h),this}addUnknownKeyValToInput(h,b){return this.data.addUnknownKeyValToInput(h,b),this}addUnknownKeyValToOutput(h,b){return this.data.addUnknownKeyValToOutput(h,b),this}clearFinalizedInput(h){return this.data.clearFinalizedInput(h),this}}mo.Psbt=y;const g=p=>new m(p);class m{constructor(h=Buffer.from([2,0,0,0,0,0,0,0,0,0])){this.tx=u.Transaction.fromBuffer(h),U(this.tx),Object.defineProperty(this,"tx",{enumerable:!1,writable:!0})}getInputOutputCounts(){return{inputCount:this.tx.ins.length,outputCount:this.tx.outs.length}}addInput(h){if(h.hash===void 0||h.index===void 0||!Buffer.isBuffer(h.hash)&&typeof h.hash!="string"||typeof h.index!="number")throw new Error("Error adding input.");const b=typeof h.hash=="string"?(0,i.reverseBuffer)(Buffer.from(h.hash,"hex")):h.hash;this.tx.addInput(b,h.index,h.sequence)}addOutput(h){if(h.script===void 0||h.value===void 0||!Buffer.isBuffer(h.script)||typeof h.value!="number")throw new Error("Error adding output.");this.tx.addOutput(h.script,h.value)}toBuffer(){return this.tx.toBuffer()}}function E(p,h,b){switch(b){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return S(1,p.partialSig);case"multisig":const I=o.p2ms({output:h});return S(I.m,p.partialSig,I.pubkeys);default:return!1}}function _(p){if(p.__UNSAFE_SIGN_NONSEGWIT!==!1)throw new Error("Not BIP174 compliant, can not export")}function S(p,h,b){if(!h)return!1;let I;if(b?I=b.map(C=>{const j=mn(C);return h.find(W=>W.pubkey.equals(j))}).filter(C=>!!C):I=h,I.length>p)throw new Error("Too many signatures");return I.length===p}function w(p){return!!p.finalScriptSig||!!p.finalScriptWitness}function T(p){return h=>!(!h.masterFingerprint.equals(p.fingerprint)||!p.derivePath(h.path).publicKey.equals(h.pubkey))}function O(p){if(typeof p!="number"||p!==Math.floor(p)||p>4294967295||p<0)throw new Error("Invalid 32 bit integer")}function A(p,h,b){const I=h.__FEE_RATE||p.getFeeRate(),C=h.__EXTRACTED_TX.virtualSize(),j=I*C;if(I>=b.maximumFeeRate)throw new Error(`Warning: You are paying around ${(j/1e8).toFixed(8)} in fees, which is ${I} satoshi per byte for a transaction with a VSize of ${C} bytes (segwit counted as 0.25 byte per byte). Use setMaximumFeeRate method to raise your threshold, or pass true to the first arg of extractTransaction.`)}function R(p,h){p.forEach(b=>{if((0,f.isTaprootInput)(b)?(0,f.checkTaprootInputForSigs)(b,h):(0,l.checkInputForSig)(b,h))throw new Error("Can not modify transaction, signatures exist.")})}function M(p){if(!p.sighashType||!p.partialSig)return;const{partialSig:h,sighashType:b}=p;h.forEach(I=>{const{hashType:C}=a.signature.decode(I.signature);if(b!==C)throw new Error("Signature sighash does not match input sighash type")})}function v(p,h,b){if(!(0,l.pubkeyInScript)(p,h))throw new Error(`Can not ${b} for this input with the key ${p.toString("hex")}`)}function U(p){if(!p.ins.every(b=>b.script&&b.script.length===0&&b.witness&&b.witness.length===0))throw new Error("Format Error: Transaction ScriptSigs are not empty")}function V(p,h){p.ins.forEach(b=>{K(h,b)})}function K(p,h){const b=(0,i.reverseBuffer)(Buffer.from(h.hash)).toString("hex")+":"+h.index;if(p.__TX_IN_CACHE[b])throw new Error("Duplicate input detected.");p.__TX_IN_CACHE[b]=1}function H(p,h){return(b,I,C,j)=>{const W=p({redeem:{output:C}}).output;if(!I.equals(W))throw new Error(`${h} for ${j} #${b} doesn't match the scriptPubKey in the prevout`)}}const $=H(o.p2sh,"Redeem script"),P=H(o.p2wsh,"Witness script");function D(p,h,b,I){if(!b.every(w))throw new Error(`PSBT must be finalized to calculate ${h}`);if(p==="__FEE_RATE"&&I.__FEE_RATE)return I.__FEE_RATE;if(p==="__FEE"&&I.__FEE)return I.__FEE;let C,j=!0;if(I.__EXTRACTED_TX?(C=I.__EXTRACTED_TX,j=!1):C=I.__TX.clone(),J(b,C,I,j),p==="__FEE_RATE")return I.__FEE_RATE;if(p==="__FEE")return I.__FEE}function F(p,h,b,I,C,j){const W=re(b);if(!E(h,b,W))throw new Error(`Can not finalize input #${p}`);return x(b,W,h.partialSig,I,C,j)}function x(p,h,b,I,C,j){let W,ie;const Q=ce(p,h,b),fe=j?o.p2wsh({redeem:Q}):null,he=C?o.p2sh({redeem:fe||Q}):null;return I?(fe?ie=(0,l.witnessStackToScriptWitness)(fe.witness):ie=(0,l.witnessStackToScriptWitness)(Q.witness),he&&(W=he.input)):he?W=he.input:W=Q.input,{finalScriptSig:W,finalScriptWitness:ie}}function B(p,h,b,I,C){const j=(0,n.checkForInput)(p,h),{hash:W,sighashType:ie,script:Q}=q(h,j,I,!1,C);return v(b,Q,"sign"),{hash:W,sighashType:ie}}function q(p,h,b,I,C){const j=b.__TX,W=h.sighashType||u.Transaction.SIGHASH_ALL;Y(W,C);let ie,Q;if(h.nonWitnessUtxo){const Ne=le(b,h,p),Pe=j.ins[p].hash,nt=Ne.getHash();if(!Pe.equals(nt))throw new Error(`Non-witness UTXO hash for input #${p} doesn't match the hash specified in the prevout`);const je=j.ins[p].index;Q=Ne.outs[je]}else if(h.witnessUtxo)Q=h.witnessUtxo;else throw new Error("Need a Utxo input item for signing");const{meaningfulScript:fe,type:he}=oe(Q.script,p,"input",h.redeemScript,h.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(he)>=0)ie=j.hashForWitnessV0(p,fe,Q.value,W);else if((0,l.isP2WPKH)(fe)){const Ne=o.p2pkh({hash:fe.slice(2)}).output;ie=j.hashForWitnessV0(p,Ne,Q.value,W)}else{if(h.nonWitnessUtxo===void 0&&b.__UNSAFE_SIGN_NONSEGWIT===!1)throw new Error(`Input #${p} has witnessUtxo but non-segwit script: ${fe.toString("hex")}`);!I&&b.__UNSAFE_SIGN_NONSEGWIT!==!1&&console.warn(`Warning: Signing non-segwit inputs without the full parent transaction means there is a chance that a miner could feed you incorrect information to trick you into paying large fees. This behavior is the same as Psbt's predecessor (TransactionBuilder - now removed) when signing non-segwit scripts. You are not able to export this Psbt with toBuffer|toBase64|toHex since it is not BIP174 compliant.
74
74
  *********************
75
75
  PROCEED WITH CAUTION!
76
- *********************`),ie=j.hashForSignature(p,fe,W)}return{script:fe,sighashType:W,hash:ie}}function N(p,h,b,I){const C=[];if(h.tapInternalKey){const W=L(p,h,I);W&&C.push(W)}if(h.tapScriptSig){const W=h.tapScriptSig.map(ie=>ie.pubkey);C.push(...W)}return C.map(W=>X(p,h,b,W,I)).flat()}function L(p,h,b){const{script:I}=qe(p,h,b);return(0,l.isP2TR)(I)?I.subarray(2,34):null}function G(p){return p.length===64?p:p.subarray(0,64)}function X(p,h,b,I,C,j,W){const ie=C.__TX,Q=h.sighashType||u.Transaction.SIGHASH_DEFAULT;Y(Q,W);const fe=b.map((je,Xn)=>qe(Xn,je,C)),he=fe.map(je=>je.script),Ne=fe.map(je=>je.value),Pe=[];if(h.tapInternalKey&&!j){const je=L(p,h,C)||Buffer.from([]);if((0,f.toXOnly)(I).equals(je)){const Xn=ie.hashForWitnessV1(p,he,Ne,Q);Pe.push({pubkey:I,hash:Xn})}}const nt=(h.tapLeafScript||[]).filter(je=>(0,l.pubkeyInScript)(I,je.script)).map(je=>{const Xn=(0,c.tapleafHash)({output:je.script,version:je.leafVersion});return Object.assign({hash:Xn},je)}).filter(je=>!j||j.equals(je.hash)).map(je=>{const Xn=ie.hashForWitnessV1(p,he,Ne,Q,je.hash);return{pubkey:I,hash:Xn,leafHash:je.hash}});return Pe.concat(nt)}function Y(p,h){if(h&&h.indexOf(p)<0){const b=we(p);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${b}`)}}function ce(p,h,b){let I;switch(h){case"multisig":const C=Z(p,b);I=o.p2ms({output:p,signatures:C});break;case"pubkey":I=o.p2pk({output:p,signature:b[0].signature});break;case"pubkeyhash":I=o.p2pkh({output:p,pubkey:b[0].pubkey,signature:b[0].signature});break;case"witnesspubkeyhash":I=o.p2wpkh({output:p,pubkey:b[0].pubkey,signature:b[0].signature});break}return I}function ue(p,h,b){const I=b.__TX,C={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(C.isP2SH=!!h.redeemScript,C.isP2WSH=!!h.witnessScript,h.witnessScript)C.script=h.witnessScript;else if(h.redeemScript)C.script=h.redeemScript;else if(h.nonWitnessUtxo){const j=le(b,h,p),W=I.ins[p].index;C.script=j.outs[W].script}else h.witnessUtxo&&(C.script=h.witnessUtxo.script);return(h.witnessScript||(0,l.isP2WPKH)(C.script))&&(C.isSegwit=!0),C}function te(p,h,b){const I=(0,n.checkForInput)(h,p);if(!I.bip32Derivation||I.bip32Derivation.length===0)throw new Error("Need bip32Derivation to sign with HD");const C=I.bip32Derivation.map(W=>{if(W.masterFingerprint.equals(b.fingerprint))return W}).filter(W=>!!W);if(C.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return C.map(W=>{const ie=b.derivePath(W.path);if(!W.pubkey.equals(ie.publicKey))throw new Error("pubkey did not match bip32Derivation");return ie})}function Z(p,h){return o.p2ms({output:p}).pubkeys.map(I=>(h.filter(C=>C.pubkey.equals(I))[0]||{}).signature).filter(I=>!!I)}function ae(p){let h=0;function b(W){return h+=W,p.slice(h-W,h)}function I(){const W=t.decode(p,h);return h+=t.decode.bytes,W}function C(){return b(I())}function j(){const W=I(),ie=[];for(let Q=0;Q<W;Q++)ie.push(C());return ie}return j()}function we(p){let h=p&u.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(p&31){case u.Transaction.SIGHASH_ALL:h+="SIGHASH_ALL";break;case u.Transaction.SIGHASH_SINGLE:h+="SIGHASH_SINGLE";break;case u.Transaction.SIGHASH_NONE:h+="SIGHASH_NONE";break}return h}function ye(p,h,b){p.__NON_WITNESS_UTXO_BUF_CACHE[b]=h.nonWitnessUtxo;const I=u.Transaction.fromBuffer(h.nonWitnessUtxo);p.__NON_WITNESS_UTXO_TX_CACHE[b]=I;const C=p,j=b;delete h.nonWitnessUtxo,Object.defineProperty(h,"nonWitnessUtxo",{enumerable:!0,get(){const W=C.__NON_WITNESS_UTXO_BUF_CACHE[j],ie=C.__NON_WITNESS_UTXO_TX_CACHE[j];if(W!==void 0)return W;{const Q=ie.toBuffer();return C.__NON_WITNESS_UTXO_BUF_CACHE[j]=Q,Q}},set(W){C.__NON_WITNESS_UTXO_BUF_CACHE[j]=W}})}function J(p,h,b,I){let C=0;p.forEach((Q,fe)=>{if(I&&Q.finalScriptSig&&(h.ins[fe].script=Q.finalScriptSig),I&&Q.finalScriptWitness&&(h.ins[fe].witness=ae(Q.finalScriptWitness)),Q.witnessUtxo)C+=Q.witnessUtxo.value;else if(Q.nonWitnessUtxo){const he=le(b,Q,fe),Ne=h.ins[fe].index,Pe=he.outs[Ne];C+=Pe.value}});const j=h.outs.reduce((Q,fe)=>Q+fe.value,0),W=C-j;if(W<0)throw new Error("Outputs are spending more than Inputs");const ie=h.virtualSize();b.__FEE=W,b.__EXTRACTED_TX=h,b.__FEE_RATE=Math.floor(W/ie)}function le(p,h,b){const I=p.__NON_WITNESS_UTXO_TX_CACHE;return I[b]||ye(p,h,b),I[b]}function Ae(p,h,b){const{script:I}=qe(p,h,b);return I}function qe(p,h,b){if(h.witnessUtxo!==void 0)return{script:h.witnessUtxo.script,value:h.witnessUtxo.value};if(h.nonWitnessUtxo!==void 0){const C=le(b,h,p).outs[b.__TX.ins[p].index];return{script:C.script,value:C.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function tt(p,h,b,I){const C=Ae(b,h,I),{meaningfulScript:j}=oe(C,b,"input",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(p,j)}function ut(p,h,b,I){const C=I.__TX.outs[b].script,{meaningfulScript:j}=oe(C,b,"output",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(p,j)}function It(p){if(!p)return;const h=a.decompile(p);if(!h)return;const b=h[h.length-1];if(!(!Buffer.isBuffer(b)||it(b)||Ce(b)||!a.decompile(b)))return b}function Oe(p){if(!p)return;const h=ae(p),b=h[h.length-1];if(!(it(b)||!a.decompile(b)))return b}function mn(p){if(p.length===65){const h=p[64]&1,b=p.slice(0,33);return b[0]=2|h,b}return p.slice()}function it(p){return p.length===33&&a.isCanonicalPubKey(p)}function Ce(p){return a.isCanonicalScriptSignature(p)}function oe(p,h,b,I,C){const j=(0,l.isP2SHScript)(p),W=j&&I&&(0,l.isP2WSHScript)(I),ie=(0,l.isP2WSHScript)(p);if(j&&I===void 0)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((ie||W)&&C===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let Q;return W?(Q=C,$(h,p,I,b),P(h,I,C,b),ne(Q)):ie?(Q=C,P(h,p,C,b),ne(Q)):j?(Q=I,$(h,p,I,b)):Q=p,{meaningfulScript:Q,type:W?"p2sh-p2wsh":j?"p2sh":ie?"p2wsh":"raw"}}function ne(p){if((0,l.isP2WPKH)(p)||(0,l.isP2SHScript)(p))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function re(p){return(0,l.isP2WPKH)(p)?"witnesspubkeyhash":(0,l.isP2PKH)(p)?"pubkeyhash":(0,l.isP2MS)(p)?"multisig":(0,l.isP2PK)(p)?"pubkey":"nonstandard"}function k(p){return[...Array(p).keys()]}return mo}var oy;function BA(){return oy||(oy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.initEccLib=e.Transaction=e.opcodes=e.Psbt=e.Block=e.script=e.payments=e.networks=e.crypto=e.address=void 0;const t=xh();e.address=t;const n=Pr();e.crypto=n;const r=Wn();e.networks=r;const i=Ec();e.payments=i;const s=nn();e.script=s;var o=rA();Object.defineProperty(e,"Block",{enumerable:!0,get:function(){return o.Block}});var c=OA();Object.defineProperty(e,"Psbt",{enumerable:!0,get:function(){return c.Psbt}});var a=bh();Object.defineProperty(e,"opcodes",{enumerable:!0,get:function(){return a.OPS}});var u=_c();Object.defineProperty(e,"Transaction",{enumerable:!0,get:function(){return u.Transaction}});var f=Sh();Object.defineProperty(e,"initEccLib",{enumerable:!0,get:function(){return f.initEccLib}})})(yf)),yf}var Oi={},cy;function NA(){if(cy)return Oi;cy=1,Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.base26Decode=Oi.base26Encode=void 0;function e(n){let r=0n;for(let i=0;i<n.length;i++){const s=BigInt(n.charCodeAt(i)-65),o=BigInt(n.length)-1n-BigInt(i);if(o==0n)r+=s;else{const c=26n**o;r+=c*(s+1n)}}return r}Oi.base26Encode=e;function t(n){if(n===340282366920938463463374607431768211455n)return"BCGDENLQRQWDSLRUGSNLBTMFIJAV";n+=1n;let r=[];for(;n>0;){const i=(n-1n)%26n;r.push("ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Number(i))),n=(n-1n)/26n}return r.reverse().join("")}return Oi.base26Decode=t,Oi}var Bi={},ay;function Jw(){if(ay)return Bi;ay=1,Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.none=Bi.some=void 0;class e{constructor(){}isSome(){return!1}map(s){return new e}value(){return null}}class t{constructor(s){this._value=s}isSome(){return!0}map(s){return new t(s(this.value()))}value(){return this._value}}function n(i){return new t(i)}Bi.some=n;function r(){return new e}return Bi.none=r,Bi}var Ni={},uy;function kA(){if(uy)return Ni;uy=1,Object.defineProperty(Ni,"__esModule",{value:!0}),Ni.decodeLEB128=Ni.encodeLEB128=void 0;function e(n){const r=[];let i=!0;for(;i;){let s=Number(n&BigInt(127));n>>=BigInt(7),n===BigInt(0)?i=!1:s|=128,r.push(s)}return r}Ni.encodeLEB128=e;function t(n){let r=BigInt(0);for(let i=0;i<n.length;i++){const s=BigInt(n[i]);if(i>18)throw new Error("Overlong");let o=s&BigInt(127);if(i==18&&(o&BigInt(124))!=BigInt(0))throw new Error("Overflow");if(r|=o<<BigInt(7)*BigInt(i),(s&BigInt(128))==BigInt(0))return{n:r,len:i+1}}throw new Error("Unterminated")}return Ni.decodeLEB128=t,Ni}var Rf={},fy;function PA(){return fy||(fy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.toPushData=e.chunks=e.toHex=e.zero2=void 0;const t=s=>s.length%2===1?"0"+s:s;e.zero2=t;const n=s=>{let o="";for(let c=0;c<s.length;c++)o+=(0,e.zero2)(s[c].toString(16));return o};e.toHex=n;function r(s,o){const c=[];let a=0;for(;a<s.length;){const u=s.slice(a,a+o);c.push(u),a+=o}return c}e.chunks=r;function i(s){const o=[],c=s.length;if(c<76){const a=Buffer.alloc(1);a.writeUInt8(c),o.push(a)}else if(c<=255){o.push(Buffer.from("4c","hex"));const a=Buffer.alloc(1);a.writeUInt8(c),o.push(a)}else if(c<=65535){o.push(Buffer.from("4d","hex"));const a=Buffer.alloc(2);a.writeUint16LE(c),o.push(a)}else{o.push(Buffer.from("4e","hex"));const a=Buffer.alloc(4);a.writeUint32LE(c),o.push(a)}return o.push(s),Buffer.concat(o)}e.toPushData=i})(Rf)),Rf}var hr={},ly;function Qw(){if(ly)return hr;ly=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.removeSpacers=hr.getSpacersVal=hr.applySpacers=void 0;function e(r,i){let s="";for(let o=0;o<r.length;o++)s+=r.charAt(o),i>0&&((i&1)===1&&(s+="•"),i>>=1);return s}hr.applySpacers=e;function t(r){let i=0,s=0;for(let o=0;o<r.length;o++)r.charAt(o)==="•"&&(i+=1<<o-1-s,s++);return i}hr.getSpacersVal=t;function n(r){return r.replace(/[•]+/g,"")}return hr.removeSpacers=n,hr}var hy;function RA(){if(hy)return Xe;hy=1,Object.defineProperty(Xe,"__esModule",{value:!0}),Xe.EtchInscription=Xe.Message=Xe.Runestone=Xe.Etching=Xe.Rune=Xe.Terms=Xe.Range=Xe.Flaw=Xe.Tag=Xe.Flag=Xe.Edict=Xe.RuneId=void 0;const e=BA(),t=NA(),n=Jw(),r=kA(),i=PA(),s=Qw();class o{constructor(w,T){this.block=w,this.idx=T}next(w,T){if(w>BigInt(Number.MAX_SAFE_INTEGER)||T>BigInt(Number.MAX_SAFE_INTEGER))return(0,n.none)();let O=BigInt(this.block)+w;if(O>BigInt(Number.MAX_SAFE_INTEGER))return(0,n.none)();let A=w===0n?BigInt(this.idx)+T:T;return A>BigInt(Number.MAX_SAFE_INTEGER)?(0,n.none)():(0,n.some)(new o(Number(O),Number(A)))}}Xe.RuneId=o;class c{constructor(w,T,O){this.id=w,this.amount=T,this.output=O}static from_integers(w,T,O,A){return A>4294967295n||A<0n||Number(A)>w.outs.length?(0,n.none)():(0,n.some)(new c(T,O,Number(A)))}}Xe.Edict=c;var a;(function(S){S[S.Etching=0]="Etching",S[S.Terms=1]="Terms",S[S.Turbo=2]="Turbo",S[S.Cenotaph=127]="Cenotaph"})(a||(Xe.Flag=a={}));var u;(function(S){S[S.Body=0]="Body",S[S.Flags=2]="Flags",S[S.Rune=4]="Rune",S[S.Premine=6]="Premine",S[S.Cap=8]="Cap",S[S.Amount=10]="Amount",S[S.HeightStart=12]="HeightStart",S[S.HeightEnd=14]="HeightEnd",S[S.OffsetStart=16]="OffsetStart",S[S.OffsetEnd=18]="OffsetEnd",S[S.Mint=20]="Mint",S[S.Pointer=22]="Pointer",S[S.Cenotaph=126]="Cenotaph",S[S.Divisibility=1]="Divisibility",S[S.Spacers=3]="Spacers",S[S.Symbol=5]="Symbol",S[S.Nop=127]="Nop"})(u||(Xe.Tag=u={}));var f;(function(S){S[S.EdictOutput=0]="EdictOutput",S[S.EdictRuneId=1]="EdictRuneId",S[S.InvalidScript=2]="InvalidScript",S[S.Opcode=3]="Opcode",S[S.SupplyOverflow=4]="SupplyOverflow",S[S.TrailingIntegers=5]="TrailingIntegers",S[S.TruncatedField=6]="TruncatedField",S[S.UnrecognizedEvenTag=7]="UnrecognizedEvenTag",S[S.UnrecognizedFlag=8]="UnrecognizedFlag",S[S.Varint=9]="Varint"})(f||(Xe.Flaw=f={}));class l{constructor(w,T){this.start=w,this.end=T}}Xe.Range=l;class d{constructor(w,T,O,A){this.amount=w,this.cap=T,this.height=O,this.offset=A}}Xe.Terms=d;class y{constructor(w){this.value=w}get name(){return y.toName(this.value)}static toName(w){return(0,t.base26Decode)(w)}static fromName(w){return new y((0,t.base26Encode)((0,s.removeSpacers)(w)))}toString(){return this.name}}Xe.Rune=y;class g{constructor(w,T,O,A,R,M,v){this.divisibility=w,this.premine=T,this.rune=O,this.spacers=A,this.symbol=R,this.terms=M,this.turbo=v}}Xe.Etching=g,g.MAX_DIVISIBILITY=38,g.MAX_SPACERS=134217727;class m{constructor(w=[],T,O,A){this.edicts=w,this.etching=T,this.mint=O,this.pointer=A}static create(w,T="etch"){if(T==="etch"){w=w;const O=y.fromName(w.name),A=new d(w.amount,w.cap,new l(w.startHeight?(0,n.some)(w.startHeight):(0,n.none)(),w.endHeight?(0,n.some)(w.endHeight):(0,n.none)()),new l(w.startOffset?(0,n.some)(w.startOffset):(0,n.none)(),w.endOffset?(0,n.some)(w.endOffset):(0,n.none)())),R=w.divisibility?(0,n.some)(w.divisibility):(0,n.none)(),M=w.premine?(0,n.some)(w.premine):(0,n.none)(),v=w.name.indexOf("•")>-1?(0,n.some)((0,s.getSpacersVal)(w.name)):(0,n.none)(),U=w.symbol?(0,n.some)(w.symbol):(0,n.none)(),V=typeof w.pointer=="number"?(0,n.some)(w.pointer):(0,n.none)(),K=new g(R,M,(0,n.some)(O),v,U,(0,n.some)(A),!0);return new m([],(0,n.some)(K),(0,n.none)(),V)}else if(T==="mint"){w=w;const O=typeof w.pointer=="number"?(0,n.some)(w.pointer):(0,n.none)();return new m([],(0,n.none)(),(0,n.some)(new o(w.block,w.txIdx)),O)}else throw new Error(`not ${T} support now`)}static decipher(w){const T=e.Transaction.fromHex(w),O=m.payload(T);if(O.isSome()){const A=m.integers(O.value()),R=E.from_integers(T,A.value()),M=R.getEtching(),v=R.getMint(),U=R.getPointer();return(0,n.some)(new m(R.edicts,M,v,U))}return(0,n.none)()}encipher(){const T=this.toMessage().toBuffer(),O=Buffer.from("6a5d","hex");let A;if(T.length<76)A=Buffer.alloc(1),A.writeUint8(T.length);else if(T.length<256)A=Buffer.alloc(2),A.writeUint8(76),A.writeUint8(T.length);else if(T.length<65536)A=Buffer.alloc(3),A.writeUint8(77),A.writeUint16LE(T.length);else if(T.length<4294967296)A=Buffer.alloc(5),A.writeUint8(78),A.writeUint32LE(T.length);else throw new Error("runestone too big!");return Buffer.concat([O,A,T])}static payload(w){for(const T of w.outs){const O=e.script.decompile(T.script);if(O[0]===e.script.OPS.OP_RETURN&&O[1]===m.MAGIC_NUMBER){for(let A=2;A<O.length;A++){const R=O[A];return R instanceof Uint8Array?(0,n.some)(Array.from(R)):(0,n.none)()}return(0,n.none)()}}return(0,n.none)()}static integers(w){let T=[],O=0;for(;O<w.length;){let{n:A,len:R}=(0,r.decodeLEB128)(w.slice(O));T.push(A),O+=R}return(0,n.some)(T)}toMessage(){let w=new Map;const T=this.etching.value();if(T){let R=1;if(T.terms.isSome()){let $=1<<a.Terms;R|=$}if(T.turbo){let $=1<<a.Turbo;R|=$}w.set(u.Flags,[BigInt(R)]);const M=T.rune.value();M!==null&&w.set(u.Rune,[BigInt(M.value)]);const v=T.divisibility.value();v!==null&&w.set(u.Divisibility,[BigInt(v)]);const U=T.spacers.value();U!==null&&w.set(u.Spacers,[BigInt(U)]);const V=T.symbol.value();V!==null&&w.set(u.Symbol,[BigInt(V.charCodeAt(0))]);const K=T.premine.value();K!==null&&w.set(u.Premine,[BigInt(K)]);const H=T.terms.value();if(H!==null){w.set(u.Amount,[BigInt(H.amount)]),w.set(u.Cap,[BigInt(H.cap)]);const $=H.height.start.value();$&&w.set(u.HeightStart,[BigInt($)]);const P=H.height.end.value();P&&w.set(u.HeightEnd,[BigInt(P)]);const D=H.offset.start.value();D&&w.set(u.OffsetStart,[BigInt(D)]);const F=H.offset.end.value();F&&w.set(u.OffsetEnd,[BigInt(F)])}}const O=this.mint.value();O!==null&&w.set(u.Mint,[BigInt(O.block),BigInt(O.idx)]);const A=this.pointer.value();return A!==null&&w.set(u.Pointer,[BigInt(A)]),new E(w,this.edicts,0)}}Xe.Runestone=m,m.MAGIC_NUMBER=93;class E{constructor(w=new Map,T=[],O=0){this.fields=w,this.edicts=T,this.flaws=O}static from_integers(w,T){let O=new Map,A=[],R=0,M=!1;for(let v=0;v<T.length;){let U=T[v];if(Number(U)===u.Body){M=!0,v+=1;continue}if(M){let V=new o(0,0);for(const K of(0,i.chunks)(T.slice(v),4)){if(K.length!=4){R|=f.TrailingIntegers;break}let H=V.next(K[0],K[1]);if(!H.isSome()){R|=f.EdictRuneId;break}const $=c.from_integers(w,H.value(),K[2],K[3]);if(!$.isSome()){R|=f.EdictOutput;break}V=H.value(),A.push($.value())}v+=4}else{let V=T[v+1];const K=O.get(Number(U))||[];K.push(V),O.set(Number(U),K),v+=2}}return new E(O,A,R)}addFieldVal(w,T){const O=this.fields.get(Number(w))||[];O.push(T),this.fields.set(Number(w),O)}addEdict(w){this.edicts.push(w)}toBuffer(){const w=[];for(const[T,O]of this.fields)for(const A of O){const R=Buffer.alloc(1);R.writeUInt8(T),w.push(R),w.push(Buffer.from((0,r.encodeLEB128)(A)))}if(this.edicts.length>0){w.push(Buffer.from("00","hex")),this.edicts.sort((A,R)=>A.id.block==R.id.block?A.id.idx-R.id.idx:A.id.block-R.id.block);let T=0n,O=0n;for(let A=0;A<this.edicts.length;A++){const R=this.edicts[A];if(A==0)T=BigInt(R.id.block),O=BigInt(R.id.idx),w.push(Buffer.from((0,r.encodeLEB128)(T))),w.push(Buffer.from((0,r.encodeLEB128)(O)));else{const M=BigInt(R.id.block),v=BigInt(R.id.idx);if(M==T){const U=v-O;O=v,w.push(Buffer.from((0,r.encodeLEB128)(0n))),w.push(Buffer.from((0,r.encodeLEB128)(U)))}else{const U=M-T;T=M,O=v,w.push(Buffer.from((0,r.encodeLEB128)(U))),w.push(Buffer.from((0,r.encodeLEB128)(v)))}}w.push(Buffer.from((0,r.encodeLEB128)(BigInt(R.amount)))),w.push(Buffer.from((0,r.encodeLEB128)(BigInt(R.output))))}}return Buffer.concat(w)}getFlags(){return Number(this.fields.get(u.Flags))}hasFlags(w){const T=this.getFlags(),O=1<<w;return(T&O)!=0}getMint(){if(!this.fields.has(u.Mint))return(0,n.none)();const[w,T]=this.fields.get(u.Mint);return(0,n.some)(new o(Number(w),Number(T)))}getEtching(){if(!this.hasFlags(a.Etching))return(0,n.none)();const w=this.getDivisibility(),T=this.getPremine(),O=this.getRune(),A=this.getSpacers(),R=this.getSymbol(),M=this.getTerms(),v=this.hasFlags(a.Turbo);return(0,n.some)(new g(w,T,O,A,R,M,v))}getDivisibility(){if(!this.fields.has(u.Divisibility))return(0,n.none)();const[w]=this.fields.get(u.Divisibility);if(w>g.MAX_DIVISIBILITY)throw new Error("invalid divisibility");return(0,n.some)(Number(w))}getPremine(){if(!this.fields.has(u.Premine))return(0,n.none)();const[w]=this.fields.get(u.Premine);return(0,n.some)(Number(w))}getRune(){if(!this.fields.has(u.Rune))return(0,n.none)();const[w]=this.fields.get(u.Rune);return(0,n.some)(new y(w))}getSpacers(){if(!this.fields.has(u.Spacers))return(0,n.none)();const[w]=this.fields.get(u.Spacers);if(w>g.MAX_SPACERS)throw new Error("invalid spacers");return(0,n.some)(Number(w))}getHeightStart(){if(!this.fields.has(u.HeightStart))return(0,n.none)();const[w]=this.fields.get(u.HeightStart);return(0,n.some)(Number(w))}getHeightEnd(){if(!this.fields.has(u.HeightEnd))return(0,n.none)();const[w]=this.fields.get(u.HeightEnd);return(0,n.some)(Number(w))}getOffsetStart(){if(!this.fields.has(u.OffsetStart))return(0,n.none)();const[w]=this.fields.get(u.OffsetStart);return(0,n.some)(Number(w))}getOffsetEnd(){if(!this.fields.has(u.OffsetEnd))return(0,n.none)();const[w]=this.fields.get(u.OffsetEnd);return(0,n.some)(Number(w))}getCap(){if(!this.fields.has(u.Cap))return(0,n.none)();const[w]=this.fields.get(u.Cap);return(0,n.some)(Number(w))}getAmount(){if(!this.fields.has(u.Amount))return(0,n.none)();const[w]=this.fields.get(u.Amount);return(0,n.some)(Number(w))}getSymbol(){if(!this.fields.has(u.Symbol))return(0,n.none)();const[w]=this.fields.get(u.Symbol);return(0,n.some)(String.fromCharCode(Number(w)))}getTerms(){if(!this.hasFlags(a.Terms))return(0,n.none)();const w=this.getCap();if(!w.isSome())throw new Error("no cap field");const T=this.getAmount();if(!T.isSome())throw new Error("no amount field");const O=this.getHeightStart(),A=this.getHeightEnd(),R=this.getOffsetStart(),M=this.getOffsetEnd(),v=new l(O,A),U=new l(R,M);return(0,n.some)(new d(T.value(),w.value(),v,U))}getPointer(){if(!this.fields.has(u.Pointer))return(0,n.none)();const[w]=this.fields.get(u.Pointer);return(0,n.some)(Number(w))}}Xe.Message=E;class _{constructor(w=new Map,T=Buffer.alloc(0)){this.fields=w,this.data=T}setContent(w,T){this.fields.set(1,Buffer.from(w,"utf8")),this.data=T}setRune(w){let O=(0,t.base26Encode)((0,s.removeSpacers)(w)).toString(16);O.length%2===1&&(O="0"+O),this.setField(_.Tag.RUNE,Buffer.from(O,"hex").reverse())}setField(w,T){this.fields.set(w,T)}static decipher(w,T){const R=e.Transaction.fromHex(w).ins[T].witness[1],M=e.script.decompile(R),v=new Map,U=[];let V=!1;for(let K=5;K<M.length-1;){const H=M[K];if(H===0){V=!0,K++;continue}else if(V)U.push(H),K++;else{const $=H-80,P=M[K+1];if(typeof P=="number"){const D=Buffer.alloc(1);D.writeUint8(P),v.set($,D)}else v.set($,P);K+=2}}return new _(v,Buffer.concat(U))}encipher(){const w=[];if(this.data&&this.data.length>0){w.push(Buffer.from("0063036f7264","hex")),Array.from(this.fields.entries()).sort((O,A)=>O[0]-A[0]).forEach(([O,A])=>{const R=Buffer.alloc(1);R.writeUInt8(O),w.push(Buffer.from("01","hex")),w.push(R),A.length!=1||A[0]!=0?w.push((0,i.toPushData)(A)):w.push(A)}),w.push(Buffer.from("00","hex"));const T=(0,i.chunks)(Array.from(this.data),520);for(const O of T)w.push((0,i.toPushData)(Buffer.from(O)))}else{w.push(Buffer.from("0063","hex"));const T=this.fields.get(_.Tag.RUNE);if(!T)throw new Error("No rune found!");w.push((0,i.toPushData)(T))}return w.push(Buffer.from("68","hex")),Buffer.concat(w)}}return Xe.EtchInscription=_,_.Tag={CONTENT_TYPE:1,POINTER:2,PARENT:3,METADATA:5,METAPROTOCOL:7,CONTENT_ENCODING:9,DELEGATE:11,RUNE:13},Xe}var dy;function UA(){return dy||(dy=1,(function(e){var t=Ei&&Ei.__createBinding||(Object.create?(function(s,o,c,a){a===void 0&&(a=c);var u=Object.getOwnPropertyDescriptor(o,c);(!u||("get"in u?!o.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return o[c]}}),Object.defineProperty(s,a,u)}):(function(s,o,c,a){a===void 0&&(a=c),s[a]=o[c]})),n=Ei&&Ei.__exportStar||function(s,o){for(var c in s)c!=="default"&&!Object.prototype.hasOwnProperty.call(o,c)&&t(o,s,c)};Object.defineProperty(e,"__esModule",{value:!0}),e.removeSpacers=e.getSpacersVal=e.applySpacers=e.some=e.none=void 0,n(RA(),e);var r=Jw();Object.defineProperty(e,"none",{enumerable:!0,get:function(){return r.none}}),Object.defineProperty(e,"some",{enumerable:!0,get:function(){return r.some}});var i=Qw();Object.defineProperty(e,"applySpacers",{enumerable:!0,get:function(){return i.applySpacers}}),Object.defineProperty(e,"getSpacersVal",{enumerable:!0,get:function(){return i.getSpacersVal}}),Object.defineProperty(e,"removeSpacers",{enumerable:!0,get:function(){return i.removeSpacers}})})(Ei)),Ei}var fs=UA();function Eo(e){if(e.length%2!==0)throw new Error("Hex string must have even length");const t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substr(n,2),16);return t}function Ih(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function Oh(e){return e===Ns.Mainnet?Pn:Fy}function Bh(e,t=Ns.Testnet){const n=Oh(t);return Ag(e,n)}function si(e){const t=Pn,n=Fy,r=D1;let i,s,o=on.UNKNOWN;if(e.startsWith("bc1")||e.startsWith("tb1")||e.startsWith("bcrt1"))try{return s=kl(e),s.version===0?s.data.length===20?o=on.P2WPKH:o=on.P2WSH:o=on.P2TR,o}catch{return on.UNKNOWN}else try{return i=xg(e),i.version===t.pubKeyHash||i.version===n.pubKeyHash||i.version===r.pubKeyHash?o=on.P2PKH:(i.version===t.scriptHash||(i.version,n.scriptHash),o=on.P2SH_P2WPKH),o}catch{return on.UNKNOWN}}function CA(e,t,n){const r=Bh(e,n),i=t.coins?.[0];return{txid:t.txid,vout:t.vout,satoshis:t.sats.toString(),height:void 0,runes:i?[{id:i.id,amount:i.value.toString()}]:[],address:e,scriptPk:Ih(r)}}async function e1(e,t){try{const n=t===Ns.Mainnet?"https://mpc.omnity.network/utxo-status":"https://mpc.omnity.network/testnet4/utxo-status",r=await ht.post(n,e).then(c=>c.data);if(!r)return null;const i=JSON.stringify(r),o=new TextEncoder().encode(i);return Array.from(o)}catch{return null}}const HA=Object.freeze(Object.defineProperty({__proto__:null,bytesToHex:Ih,formatPoolUtxo:CA,getAddressType:si,getScriptByAddress:Bh,getUtxoProof:e1,hexToBytes:Eo,toBitcoinNetwork:Oh},Symbol.toStringTag,{value:"Module"})),FA="kqs64-paaaa-aaaar-qamza-cai",MA="hvyp5-5yaaa-aaaao-qjxha-cai",Qr=BigInt(546),sn="0:0",qA="https://runescan-hasura-mainnet.omnity.network/v1/graphql",VA="https://runescan-hasura-testnet.omnity.network/v1/graphql",py={P2PKH:148,P2SH_P2WPKH:91,P2WPKH:68,P2WSH:140,P2SH:108,P2TR:58,UNKNOWN:110},yy={P2PKH:34,P2SH_P2WPKH:32,P2WPKH:31,P2WSH:43,P2SH:32,P2TR:43,UNKNOWN:34},LA=new Set(["P2WPKH","P2WSH","P2SH_P2WPKH","P2TR"]),$A=2;class oi{psbt;client;inputAddressTypes=[];outputAddressTypes=[];config;userInputUtxoDusts=BigInt(0);intentions=[];txFee=BigInt(0);additionalDustNeeded=BigInt(0);inputUtxos=[];constructor(t,n){this.config=t,this.psbt=new ma({network:Oh(t.network)}),this.client=n}addInput(t){if(this.inputUtxos.findIndex(i=>i.txid===t.txid&&i.vout===t.vout)>=0)return;const{address:n}=t;if(si(n)===on.P2TR){let i=t.pubkey;i||t.address===this.config.address&&this.config.publicKey&&(i=this.config.publicKey);const s=i?i.length===66?i.slice(2):i:void 0;s?this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:Eo(t.scriptPk)},xpubkey:Eo(s)}):this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:Eo(t.scriptPk)}})}else this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:Eo(t.scriptPk)}});this.inputAddressTypes.push(si(n)),this.inputUtxos.push(t),(n===this.config.address||n===this.config.paymentAddress)&&t.runes.length!==0&&(this.userInputUtxoDusts+=BigInt(t.satoshis))}addOutput(t,n){this.psbt.addOutput({address:t,value:n}),this.outputAddressTypes.push(si(t))}addScriptOutput(t){this.psbt.addOutput({script:t,value:BigInt(0)}),this.outputAddressTypes.push({OpReturn:BigInt(t.length)})}selectRuneUtxos(t,n,r){const i=[];if(r==BigInt(0))return i;for(const s of t)if(s.runes.length){const o=s.runes.find(c=>c.id==n);if(o&&BigInt(o.amount)==r){i.push(s);break}}if(i.length==0){let s=BigInt(0);for(const o of t)if(o.runes.forEach(c=>{c.id==n&&(s=s+BigInt(c.amount))}),i.push(o),s>=r)break;if(s<r)throw new Error("INSUFFICIENT_RUNE_UTXOs")}return i}selectBtcUtxos(t,n,r=!1){const i=[];if(n<=BigInt(0))return i;let s=BigInt(0);for(const o of t)if(!(o.runes.length&&!r)&&(s+=BigInt(o.satoshis),i.push(o),s>=n))break;if(s<n)throw new Error(`Insufficient BTC UTXOs: need ${n}, have ${s}`);return i}async addBtcAndFees(t,n){const r=this.config.paymentAddress,i=this.additionalDustNeeded,s=si(r),o=this.userInputUtxoDusts,c=this.config.feeRate;this.outputAddressTypes.push(s);let a=!0,u=BigInt(0),f=BigInt(0),l=[],d=BigInt(0),y=BigInt(0);const g=[...this.inputAddressTypes];do{if(u=f,c!==void 0){const _=oi.estimateTxVirtualSize(this.inputAddressTypes,this.outputAddressTypes);f=BigInt(Math.round(c*_))}else f=(await this.client.orchestrator.estimate_min_tx_fee({input_types:this.inputAddressTypes,pool_address:this.intentions.map(S=>S.poolAddress),output_types:this.outputAddressTypes}).catch(S=>{throw console.error("estimate_min_tx_fee failed:",S),S})).Ok;if(d=n+f+i-o,f>u&&d>0){const _=this.selectBtcUtxos(t,d);if(_.length===0)throw new Error("INSUFFICIENT_BTC_UTXOs");this.inputAddressTypes=g.concat(_.map(()=>s));const S=_.reduce((w,T)=>w+BigInt(T.satoshis),BigInt(0));S-d>0&&S-d>Qr||(this.outputAddressTypes.pop(),a=!1),l=_}}while(f>u&&d>0);this.inputAddressTypes=[...g],a&&this.outputAddressTypes.pop();let m=BigInt(0);l.forEach(_=>{this.addInput(_),m+=BigInt(_.satoshis)});const E=m-d;if(E<0)throw new Error("Insufficient UTXO(s)");E>Qr?this.addOutput(r,E):E>BigInt(0)&&(y=E),this.txFee=y+f}async getInvolvedAddressUtxos(){const t={},n={},r=new Map,i=this.intentions.map(o=>o.poolAddress);r.set(this.config.paymentAddress,{needBtc:!0,runeIds:new Set});const s=o=>{const c=o.trim();return r.has(c)||r.set(c,{needBtc:!1,runeIds:new Set}),r.get(c)};for(const o of this.intentions){for(const u of o.inputCoins){const f=s(u.from);u.coin.id===sn?f.needBtc=!0:f.runeIds.add(u.coin.id)}for(const u of o.outputCoins){const f=s(u.to);u.coin.id===sn?f.needBtc=!0:f.runeIds.add(u.coin.id)}const c=s(o.poolAddress),a=[...o.inputCoins.map(u=>u.coin.id),...o.outputCoins.map(u=>u.coin.id)];for(const u of a)u===sn?c.needBtc=!0:c.runeIds.add(u)}return await Promise.all(Array.from(r.entries()).map(async([o,c])=>{if(c.needBtc)try{t[o]=await this.client.getBtcUtxos(o,!i.includes(o))}catch{t[o]=[]}c.runeIds.size>0&&(n[o]={},await Promise.all(Array.from(c.runeIds).map(async a=>{try{n[o][a]=await this.client.getRuneUtxos(o,a)}catch{n[o][a]=[]}})))})),{btc:t,rune:n}}addInputsAndCalculateOutputs(t){if(!this.intentions.length)throw new Error("No intentions added");const n=this.intentions.map(a=>a.poolAddress),r={},i={};let s=BigInt(0);const o=new Map,c=new Set;this.intentions.forEach(({poolAddress:a,inputCoins:u,outputCoins:f,poolUtxos:l})=>{const d=[...u.filter(({from:g})=>!n.includes(g))],y=[...f];if(d.forEach(({coin:g,from:m})=>{!f.find(E=>E.coin.id===g.id)&&!(n.includes(m)&&m!==a)&&y.push({coin:g,to:a})}),y.forEach(({coin:g})=>{u.find(m=>m.coin.id===g.id)||d.push({coin:g,from:a})}),d.length===0&&y.length===0&&l?.length){const g=o.get(a);o.set(a,g?g.concat(l):[...l]),c.add(a);return}d.forEach(({coin:g,from:m})=>{r[m]??={},r[m][g.id]=(r[m][g.id]??BigInt(0))+BigInt(g.value)}),y.forEach(({coin:g,to:m})=>{i[m]??={},i[m][g.id]=(i[m][g.id]??BigInt(0))+BigInt(g.value)})});for(const[a,u]of o.entries()){if(!u.length)continue;i[a]??={};const f=i[a];u.forEach(l=>{this.addInput(l),f[sn]=(f[sn]??BigInt(0))+BigInt(l.satoshis),l.runes.forEach(d=>{f[d.id]=(f[d.id]??BigInt(0))+BigInt(d.amount)})})}for(const[a,u]of Object.entries(r))for(const[f,l]of Object.entries(u))if(f===sn){if(a===this.config.paymentAddress){s+=l;continue}const d=t.btc[a]||[],y=this.selectBtcUtxos(d,l,n.includes(a)),m=y.reduce((E,_)=>E+BigInt(_.satoshis),BigInt(0))-l;m>BigInt(0)&&(i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+m),y.forEach(E=>{this.addInput(E),n.includes(a)&&E.runes.forEach(_=>{(r[a]?.[_.id]??BigInt(0))>BigInt(0)||(i[a]??={},i[a][_.id]=(i[a][_.id]??BigInt(0))+BigInt(_.amount))})})}else{const d=t.rune[a]?.[f]||[],y=this.selectRuneUtxos(d,f,l),g=y.reduce((_,S)=>{const w=S.runes.find(T=>T.id===f);return _+BigInt(w?.amount??0)},BigInt(0)),m=y.reduce((_,S)=>_+BigInt(S.satoshis),BigInt(0)),E=g-l;if(n.includes(a)){i[a]??={};const _=i[a],S=(r[a]?.[sn]??BigInt(0))>BigInt(0);m>BigInt(0)&&!S&&(_[sn]=(_[sn]??BigInt(0))+m),E>BigInt(0)&&(_[f]=(_[f]??BigInt(0))+E)}else E>BigInt(0)&&(i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+E);y.forEach(_=>this.addInput(_))}for(const[a,u]of Object.entries(i))if(!(r[a]||!n.includes(a)||c.has(a)))for(const[f]of Object.entries(u))if(f===sn){const l=t.btc[a]||[],d=l.reduce((y,g)=>y+BigInt(g.satoshis),BigInt(0));i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+d,l.forEach(y=>{this.addInput(y),y.runes.forEach(g=>{i[a]??={},i[a][g.id]=(i[a][g.id]??BigInt(0))+BigInt(g.amount)})})}else{const l=t.rune[a]?.[f]||[],d=l.reduce((y,g)=>{const m=g.runes.find(E=>E.id===f);return y+BigInt(m?.amount??0)},BigInt(0));i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+d,l.forEach(y=>this.addInput(y))}return{addressOutputCoinAmounts:i,paymentBtcRequired:s}}addOutputs(t){const n=this.config.mergeSelfRuneBtcOutputs===!0,r=new Set;for(const[,s]of Object.entries(t))for(const o of Object.keys(s))o!==sn&&r.add(o);const i=Array.from(r);if(i.length>0){const s=[],o=[];let c=1;i.forEach(u=>{const f=new fs.RuneId(Number(u.split(":")[0]),Number(u.split(":")[1]));for(const[l,d]of Object.entries(t)){const y=d[u]??BigInt(0);y>BigInt(0)&&(s.push(new fs.Edict(f,y,c)),o.push(l),c++)}});const a=new fs.Runestone(s,fs.none(),fs.none(),fs.none());this.addScriptOutput(new Uint8Array(a.encipher())),o.forEach(u=>{const f=t[u]?.[sn]??BigInt(0),l=u===this.config.address,d=f>BigInt(0)&&(!l||n),y=d&&f>Qr?f:Qr;this.addOutput(u,y),d?(f<Qr&&(this.additionalDustNeeded+=Qr-f),delete t[u][sn]):this.additionalDustNeeded+=Qr})}for(const[s,o]of Object.entries(t)){const c=o[sn]??BigInt(0);c>BigInt(0)&&this.addOutput(s,c)}}addIntention(t){this.intentions.push(t)}async build(){const t=await this.getInvolvedAddressUtxos();for(const u of this.intentions){const f=u.poolUtxos;if(!f)continue;t.btc[u.poolAddress]=f,t.rune[u.poolAddress]={};const l=t.rune[u.poolAddress];for(const d of f)for(const y of d.runes)(l[y.id]??=[]).push(d)}const{addressOutputCoinAmounts:n,paymentBtcRequired:r}=this.addInputsAndCalculateOutputs(t);this.addOutputs(n);const i=this.config.paymentAddress,s=t.btc[i]??[];await this.addBtcAndFees(s,r);const c=this.psbt.__CACHE.__TX.clone();for(let u=0;u<this.inputUtxos.length;u++){const l=this.inputUtxos[u].address;if(l!==this.config.paymentAddress||l!==this.config.address)continue;const d=this.psbt.data.inputs[u].redeemScript,y=si(l);if(d&&y===on.P2SH_P2WPKH){const g=tn([d]);c.setInputScript(u,g)}}const a=c.getId();return{psbt:this.psbt,txid:a,fee:this.txFee}}static estimateTxVirtualSize(t,n){const r=t.length,i=n.length;let s=8+oi.varIntSize(r)+oi.varIntSize(i),o=!1;for(const c of t){const a=oi.parseAddressType(c);if(a.key==="OpReturn")continue;const u=py[a.key]??py.UNKNOWN;s+=u,LA.has(a.key)&&(o=!0)}for(const c of n){const a=oi.parseAddressType(c);if(a.key==="OpReturn"){const f=Math.max(0,a.opReturnLength??0);s+=11+f;continue}const u=yy[a.key]??yy.UNKNOWN;s+=u}return o&&(s+=1),s+$A}static parseAddressType(t){if("OpReturn"in t){const r=t.OpReturn!==void 0?Number(t.OpReturn):0;return{key:"OpReturn",opReturnLength:Number.isFinite(r)?r:0}}const n=["P2PKH","P2SH_P2WPKH","P2WPKH","P2WSH","P2SH","P2TR"];for(const r of n)if(r in t)return{key:r};return{key:"UNKNOWN"}}static varIntSize(t){return t<253?1:t<=65535?3:t<=4294967295?5:9}async send(t){if(!this.intentions.length)throw new Error("No itentions added");const n=this.inputUtxos.filter(i=>i.address===this.config.paymentAddress||i.address===this.config.address),r=await e1(n,this.config.network);if(!r)throw new Error("Failed to get utxo proof");return this.client.orchestrator.invoke({intention_set:{tx_fee_in_sats:this.txFee,initiator_address:this.config.paymentAddress,intentions:this.intentions.map(({action:i,actionParams:s,poolAddress:o,inputCoins:c,outputCoins:a,exchangeId:u,nonce:f})=>({exchange_id:u??this.config.exchangeId,input_coins:c.filter(l=>l.from!==o),output_coins:a,pool_address:o,action:i,action_params:s??"",pool_utxo_spent:[],pool_utxo_received:[],nonce:f}))},initiator_utxo_proof:r,psbt_hex:t,client_info:[this.config.clientInfo??""]}).then(i=>{if(i?.Ok)return i.Ok;{const s=i?.Err??{},o=Object.keys(s)[0],c=s[o];throw new Error(c?o==="ErrorOccurredDuringExecution"?`${o}: ${c.execution_steps?.[0]?.result?.Err??"Unknown Error"}`:`Invoke Error: ${JSON.stringify(i)}`:`Invoke Error: ${JSON.stringify(i)}`)}})}}class Is extends Error{response;request;constructor(t,n){const r=`${Is.extractMessage(t)}: ${JSON.stringify({response:t,request:n})}`;super(r),Object.setPrototypeOf(this,Is.prototype),this.response=t,this.request=n,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Is)}static extractMessage(t){return t.errors?.[0]?.message??`GraphQL Error (Code: ${String(t.status)})`}}const gy=e=>e.toUpperCase(),Uf=e=>typeof e=="function"?e():e,t1=(e,t)=>e.map((n,r)=>[n,t[r]]),ls=e=>{let t={};return e instanceof Headers?t=DA(e):Array.isArray(e)?e.forEach(([n,r])=>{n&&r!==void 0&&(t[n]=r)}):e&&(t=e),t},DA=e=>{const t={};return e.forEach((n,r)=>{t[r]=n}),t},jA=e=>{try{const t=e();return KA(t)?t.catch(n=>my(n)):t}catch(t){return my(t)}},my=e=>e instanceof Error?e:new Error(String(e)),KA=e=>typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function"&&"catch"in e&&typeof e.catch=="function"&&"finally"in e&&typeof e.finally=="function",Nh=e=>{throw new Error(`Unhandled case: ${String(e)}`)},ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),GA=(e,t)=>e.documents?e:{documents:e,requestHeaders:t,signal:void 0},WA=(e,t,n)=>e.query?e:{query:e,variables:t,requestHeaders:n,signal:void 0};function ia(e,t){if(!!!e)throw new Error(t)}function XA(e){return typeof e=="object"&&e!==null}function zA(e,t){if(!!!e)throw new Error("Unexpected invariant triggered.")}const YA=/\r\n|[\n\r]/g;function pl(e,t){let n=0,r=1;for(const i of e.body.matchAll(YA)){if(typeof i.index=="number"||zA(!1),i.index>=t)break;n=i.index+i[0].length,r+=1}return{line:r,column:t+1-n}}function ZA(e){return n1(e.source,pl(e.source,e.start))}function n1(e,t){const n=e.locationOffset.column-1,r="".padStart(n)+e.body,i=t.line-1,s=e.locationOffset.line-1,o=t.line+s,c=t.line===1?n:0,a=t.column+c,u=`${e.name}:${o}:${a}
76
+ *********************`),ie=j.hashForSignature(p,fe,W)}return{script:fe,sighashType:W,hash:ie}}function N(p,h,b,I){const C=[];if(h.tapInternalKey){const W=L(p,h,I);W&&C.push(W)}if(h.tapScriptSig){const W=h.tapScriptSig.map(ie=>ie.pubkey);C.push(...W)}return C.map(W=>X(p,h,b,W,I)).flat()}function L(p,h,b){const{script:I}=qe(p,h,b);return(0,l.isP2TR)(I)?I.subarray(2,34):null}function G(p){return p.length===64?p:p.subarray(0,64)}function X(p,h,b,I,C,j,W){const ie=C.__TX,Q=h.sighashType||u.Transaction.SIGHASH_DEFAULT;Y(Q,W);const fe=b.map((je,Xn)=>qe(Xn,je,C)),he=fe.map(je=>je.script),Ne=fe.map(je=>je.value),Pe=[];if(h.tapInternalKey&&!j){const je=L(p,h,C)||Buffer.from([]);if((0,f.toXOnly)(I).equals(je)){const Xn=ie.hashForWitnessV1(p,he,Ne,Q);Pe.push({pubkey:I,hash:Xn})}}const nt=(h.tapLeafScript||[]).filter(je=>(0,l.pubkeyInScript)(I,je.script)).map(je=>{const Xn=(0,c.tapleafHash)({output:je.script,version:je.leafVersion});return Object.assign({hash:Xn},je)}).filter(je=>!j||j.equals(je.hash)).map(je=>{const Xn=ie.hashForWitnessV1(p,he,Ne,Q,je.hash);return{pubkey:I,hash:Xn,leafHash:je.hash}});return Pe.concat(nt)}function Y(p,h){if(h&&h.indexOf(p)<0){const b=we(p);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${b}`)}}function ce(p,h,b){let I;switch(h){case"multisig":const C=Z(p,b);I=o.p2ms({output:p,signatures:C});break;case"pubkey":I=o.p2pk({output:p,signature:b[0].signature});break;case"pubkeyhash":I=o.p2pkh({output:p,pubkey:b[0].pubkey,signature:b[0].signature});break;case"witnesspubkeyhash":I=o.p2wpkh({output:p,pubkey:b[0].pubkey,signature:b[0].signature});break}return I}function ue(p,h,b){const I=b.__TX,C={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(C.isP2SH=!!h.redeemScript,C.isP2WSH=!!h.witnessScript,h.witnessScript)C.script=h.witnessScript;else if(h.redeemScript)C.script=h.redeemScript;else if(h.nonWitnessUtxo){const j=le(b,h,p),W=I.ins[p].index;C.script=j.outs[W].script}else h.witnessUtxo&&(C.script=h.witnessUtxo.script);return(h.witnessScript||(0,l.isP2WPKH)(C.script))&&(C.isSegwit=!0),C}function te(p,h,b){const I=(0,n.checkForInput)(h,p);if(!I.bip32Derivation||I.bip32Derivation.length===0)throw new Error("Need bip32Derivation to sign with HD");const C=I.bip32Derivation.map(W=>{if(W.masterFingerprint.equals(b.fingerprint))return W}).filter(W=>!!W);if(C.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return C.map(W=>{const ie=b.derivePath(W.path);if(!W.pubkey.equals(ie.publicKey))throw new Error("pubkey did not match bip32Derivation");return ie})}function Z(p,h){return o.p2ms({output:p}).pubkeys.map(I=>(h.filter(C=>C.pubkey.equals(I))[0]||{}).signature).filter(I=>!!I)}function ae(p){let h=0;function b(W){return h+=W,p.slice(h-W,h)}function I(){const W=t.decode(p,h);return h+=t.decode.bytes,W}function C(){return b(I())}function j(){const W=I(),ie=[];for(let Q=0;Q<W;Q++)ie.push(C());return ie}return j()}function we(p){let h=p&u.Transaction.SIGHASH_ANYONECANPAY?"SIGHASH_ANYONECANPAY | ":"";switch(p&31){case u.Transaction.SIGHASH_ALL:h+="SIGHASH_ALL";break;case u.Transaction.SIGHASH_SINGLE:h+="SIGHASH_SINGLE";break;case u.Transaction.SIGHASH_NONE:h+="SIGHASH_NONE";break}return h}function ye(p,h,b){p.__NON_WITNESS_UTXO_BUF_CACHE[b]=h.nonWitnessUtxo;const I=u.Transaction.fromBuffer(h.nonWitnessUtxo);p.__NON_WITNESS_UTXO_TX_CACHE[b]=I;const C=p,j=b;delete h.nonWitnessUtxo,Object.defineProperty(h,"nonWitnessUtxo",{enumerable:!0,get(){const W=C.__NON_WITNESS_UTXO_BUF_CACHE[j],ie=C.__NON_WITNESS_UTXO_TX_CACHE[j];if(W!==void 0)return W;{const Q=ie.toBuffer();return C.__NON_WITNESS_UTXO_BUF_CACHE[j]=Q,Q}},set(W){C.__NON_WITNESS_UTXO_BUF_CACHE[j]=W}})}function J(p,h,b,I){let C=0;p.forEach((Q,fe)=>{if(I&&Q.finalScriptSig&&(h.ins[fe].script=Q.finalScriptSig),I&&Q.finalScriptWitness&&(h.ins[fe].witness=ae(Q.finalScriptWitness)),Q.witnessUtxo)C+=Q.witnessUtxo.value;else if(Q.nonWitnessUtxo){const he=le(b,Q,fe),Ne=h.ins[fe].index,Pe=he.outs[Ne];C+=Pe.value}});const j=h.outs.reduce((Q,fe)=>Q+fe.value,0),W=C-j;if(W<0)throw new Error("Outputs are spending more than Inputs");const ie=h.virtualSize();b.__FEE=W,b.__EXTRACTED_TX=h,b.__FEE_RATE=Math.floor(W/ie)}function le(p,h,b){const I=p.__NON_WITNESS_UTXO_TX_CACHE;return I[b]||ye(p,h,b),I[b]}function Ae(p,h,b){const{script:I}=qe(p,h,b);return I}function qe(p,h,b){if(h.witnessUtxo!==void 0)return{script:h.witnessUtxo.script,value:h.witnessUtxo.value};if(h.nonWitnessUtxo!==void 0){const C=le(b,h,p).outs[b.__TX.ins[p].index];return{script:C.script,value:C.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function tt(p,h,b,I){const C=Ae(b,h,I),{meaningfulScript:j}=oe(C,b,"input",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(p,j)}function ut(p,h,b,I){const C=I.__TX.outs[b].script,{meaningfulScript:j}=oe(C,b,"output",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(p,j)}function It(p){if(!p)return;const h=a.decompile(p);if(!h)return;const b=h[h.length-1];if(!(!Buffer.isBuffer(b)||it(b)||Ce(b)||!a.decompile(b)))return b}function Oe(p){if(!p)return;const h=ae(p),b=h[h.length-1];if(!(it(b)||!a.decompile(b)))return b}function mn(p){if(p.length===65){const h=p[64]&1,b=p.slice(0,33);return b[0]=2|h,b}return p.slice()}function it(p){return p.length===33&&a.isCanonicalPubKey(p)}function Ce(p){return a.isCanonicalScriptSignature(p)}function oe(p,h,b,I,C){const j=(0,l.isP2SHScript)(p),W=j&&I&&(0,l.isP2WSHScript)(I),ie=(0,l.isP2WSHScript)(p);if(j&&I===void 0)throw new Error("scriptPubkey is P2SH but redeemScript missing");if((ie||W)&&C===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let Q;return W?(Q=C,$(h,p,I,b),P(h,I,C,b),ne(Q)):ie?(Q=C,P(h,p,C,b),ne(Q)):j?(Q=I,$(h,p,I,b)):Q=p,{meaningfulScript:Q,type:W?"p2sh-p2wsh":j?"p2sh":ie?"p2wsh":"raw"}}function ne(p){if((0,l.isP2WPKH)(p)||(0,l.isP2SHScript)(p))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function re(p){return(0,l.isP2WPKH)(p)?"witnesspubkeyhash":(0,l.isP2PKH)(p)?"pubkeyhash":(0,l.isP2MS)(p)?"multisig":(0,l.isP2PK)(p)?"pubkey":"nonstandard"}function k(p){return[...Array(p).keys()]}return mo}var oy;function BA(){return oy||(oy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.initEccLib=e.Transaction=e.opcodes=e.Psbt=e.Block=e.script=e.payments=e.networks=e.crypto=e.address=void 0;const t=xh();e.address=t;const n=Pr();e.crypto=n;const r=Wn();e.networks=r;const i=Ec();e.payments=i;const s=rn();e.script=s;var o=rA();Object.defineProperty(e,"Block",{enumerable:!0,get:function(){return o.Block}});var c=OA();Object.defineProperty(e,"Psbt",{enumerable:!0,get:function(){return c.Psbt}});var a=bh();Object.defineProperty(e,"opcodes",{enumerable:!0,get:function(){return a.OPS}});var u=_c();Object.defineProperty(e,"Transaction",{enumerable:!0,get:function(){return u.Transaction}});var f=Sh();Object.defineProperty(e,"initEccLib",{enumerable:!0,get:function(){return f.initEccLib}})})(yf)),yf}var Oi={},cy;function NA(){if(cy)return Oi;cy=1,Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.base26Decode=Oi.base26Encode=void 0;function e(n){let r=0n;for(let i=0;i<n.length;i++){const s=BigInt(n.charCodeAt(i)-65),o=BigInt(n.length)-1n-BigInt(i);if(o==0n)r+=s;else{const c=26n**o;r+=c*(s+1n)}}return r}Oi.base26Encode=e;function t(n){if(n===340282366920938463463374607431768211455n)return"BCGDENLQRQWDSLRUGSNLBTMFIJAV";n+=1n;let r=[];for(;n>0;){const i=(n-1n)%26n;r.push("ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Number(i))),n=(n-1n)/26n}return r.reverse().join("")}return Oi.base26Decode=t,Oi}var Bi={},ay;function Jw(){if(ay)return Bi;ay=1,Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.none=Bi.some=void 0;class e{constructor(){}isSome(){return!1}map(s){return new e}value(){return null}}class t{constructor(s){this._value=s}isSome(){return!0}map(s){return new t(s(this.value()))}value(){return this._value}}function n(i){return new t(i)}Bi.some=n;function r(){return new e}return Bi.none=r,Bi}var Ni={},uy;function kA(){if(uy)return Ni;uy=1,Object.defineProperty(Ni,"__esModule",{value:!0}),Ni.decodeLEB128=Ni.encodeLEB128=void 0;function e(n){const r=[];let i=!0;for(;i;){let s=Number(n&BigInt(127));n>>=BigInt(7),n===BigInt(0)?i=!1:s|=128,r.push(s)}return r}Ni.encodeLEB128=e;function t(n){let r=BigInt(0);for(let i=0;i<n.length;i++){const s=BigInt(n[i]);if(i>18)throw new Error("Overlong");let o=s&BigInt(127);if(i==18&&(o&BigInt(124))!=BigInt(0))throw new Error("Overflow");if(r|=o<<BigInt(7)*BigInt(i),(s&BigInt(128))==BigInt(0))return{n:r,len:i+1}}throw new Error("Unterminated")}return Ni.decodeLEB128=t,Ni}var Rf={},fy;function PA(){return fy||(fy=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.toPushData=e.chunks=e.toHex=e.zero2=void 0;const t=s=>s.length%2===1?"0"+s:s;e.zero2=t;const n=s=>{let o="";for(let c=0;c<s.length;c++)o+=(0,e.zero2)(s[c].toString(16));return o};e.toHex=n;function r(s,o){const c=[];let a=0;for(;a<s.length;){const u=s.slice(a,a+o);c.push(u),a+=o}return c}e.chunks=r;function i(s){const o=[],c=s.length;if(c<76){const a=Buffer.alloc(1);a.writeUInt8(c),o.push(a)}else if(c<=255){o.push(Buffer.from("4c","hex"));const a=Buffer.alloc(1);a.writeUInt8(c),o.push(a)}else if(c<=65535){o.push(Buffer.from("4d","hex"));const a=Buffer.alloc(2);a.writeUint16LE(c),o.push(a)}else{o.push(Buffer.from("4e","hex"));const a=Buffer.alloc(4);a.writeUint32LE(c),o.push(a)}return o.push(s),Buffer.concat(o)}e.toPushData=i})(Rf)),Rf}var hr={},ly;function Qw(){if(ly)return hr;ly=1,Object.defineProperty(hr,"__esModule",{value:!0}),hr.removeSpacers=hr.getSpacersVal=hr.applySpacers=void 0;function e(r,i){let s="";for(let o=0;o<r.length;o++)s+=r.charAt(o),i>0&&((i&1)===1&&(s+="•"),i>>=1);return s}hr.applySpacers=e;function t(r){let i=0,s=0;for(let o=0;o<r.length;o++)r.charAt(o)==="•"&&(i+=1<<o-1-s,s++);return i}hr.getSpacersVal=t;function n(r){return r.replace(/[•]+/g,"")}return hr.removeSpacers=n,hr}var hy;function RA(){if(hy)return Xe;hy=1,Object.defineProperty(Xe,"__esModule",{value:!0}),Xe.EtchInscription=Xe.Message=Xe.Runestone=Xe.Etching=Xe.Rune=Xe.Terms=Xe.Range=Xe.Flaw=Xe.Tag=Xe.Flag=Xe.Edict=Xe.RuneId=void 0;const e=BA(),t=NA(),n=Jw(),r=kA(),i=PA(),s=Qw();class o{constructor(w,T){this.block=w,this.idx=T}next(w,T){if(w>BigInt(Number.MAX_SAFE_INTEGER)||T>BigInt(Number.MAX_SAFE_INTEGER))return(0,n.none)();let O=BigInt(this.block)+w;if(O>BigInt(Number.MAX_SAFE_INTEGER))return(0,n.none)();let A=w===0n?BigInt(this.idx)+T:T;return A>BigInt(Number.MAX_SAFE_INTEGER)?(0,n.none)():(0,n.some)(new o(Number(O),Number(A)))}}Xe.RuneId=o;class c{constructor(w,T,O){this.id=w,this.amount=T,this.output=O}static from_integers(w,T,O,A){return A>4294967295n||A<0n||Number(A)>w.outs.length?(0,n.none)():(0,n.some)(new c(T,O,Number(A)))}}Xe.Edict=c;var a;(function(S){S[S.Etching=0]="Etching",S[S.Terms=1]="Terms",S[S.Turbo=2]="Turbo",S[S.Cenotaph=127]="Cenotaph"})(a||(Xe.Flag=a={}));var u;(function(S){S[S.Body=0]="Body",S[S.Flags=2]="Flags",S[S.Rune=4]="Rune",S[S.Premine=6]="Premine",S[S.Cap=8]="Cap",S[S.Amount=10]="Amount",S[S.HeightStart=12]="HeightStart",S[S.HeightEnd=14]="HeightEnd",S[S.OffsetStart=16]="OffsetStart",S[S.OffsetEnd=18]="OffsetEnd",S[S.Mint=20]="Mint",S[S.Pointer=22]="Pointer",S[S.Cenotaph=126]="Cenotaph",S[S.Divisibility=1]="Divisibility",S[S.Spacers=3]="Spacers",S[S.Symbol=5]="Symbol",S[S.Nop=127]="Nop"})(u||(Xe.Tag=u={}));var f;(function(S){S[S.EdictOutput=0]="EdictOutput",S[S.EdictRuneId=1]="EdictRuneId",S[S.InvalidScript=2]="InvalidScript",S[S.Opcode=3]="Opcode",S[S.SupplyOverflow=4]="SupplyOverflow",S[S.TrailingIntegers=5]="TrailingIntegers",S[S.TruncatedField=6]="TruncatedField",S[S.UnrecognizedEvenTag=7]="UnrecognizedEvenTag",S[S.UnrecognizedFlag=8]="UnrecognizedFlag",S[S.Varint=9]="Varint"})(f||(Xe.Flaw=f={}));class l{constructor(w,T){this.start=w,this.end=T}}Xe.Range=l;class d{constructor(w,T,O,A){this.amount=w,this.cap=T,this.height=O,this.offset=A}}Xe.Terms=d;class y{constructor(w){this.value=w}get name(){return y.toName(this.value)}static toName(w){return(0,t.base26Decode)(w)}static fromName(w){return new y((0,t.base26Encode)((0,s.removeSpacers)(w)))}toString(){return this.name}}Xe.Rune=y;class g{constructor(w,T,O,A,R,M,v){this.divisibility=w,this.premine=T,this.rune=O,this.spacers=A,this.symbol=R,this.terms=M,this.turbo=v}}Xe.Etching=g,g.MAX_DIVISIBILITY=38,g.MAX_SPACERS=134217727;class m{constructor(w=[],T,O,A){this.edicts=w,this.etching=T,this.mint=O,this.pointer=A}static create(w,T="etch"){if(T==="etch"){w=w;const O=y.fromName(w.name),A=new d(w.amount,w.cap,new l(w.startHeight?(0,n.some)(w.startHeight):(0,n.none)(),w.endHeight?(0,n.some)(w.endHeight):(0,n.none)()),new l(w.startOffset?(0,n.some)(w.startOffset):(0,n.none)(),w.endOffset?(0,n.some)(w.endOffset):(0,n.none)())),R=w.divisibility?(0,n.some)(w.divisibility):(0,n.none)(),M=w.premine?(0,n.some)(w.premine):(0,n.none)(),v=w.name.indexOf("•")>-1?(0,n.some)((0,s.getSpacersVal)(w.name)):(0,n.none)(),U=w.symbol?(0,n.some)(w.symbol):(0,n.none)(),V=typeof w.pointer=="number"?(0,n.some)(w.pointer):(0,n.none)(),K=new g(R,M,(0,n.some)(O),v,U,(0,n.some)(A),!0);return new m([],(0,n.some)(K),(0,n.none)(),V)}else if(T==="mint"){w=w;const O=typeof w.pointer=="number"?(0,n.some)(w.pointer):(0,n.none)();return new m([],(0,n.none)(),(0,n.some)(new o(w.block,w.txIdx)),O)}else throw new Error(`not ${T} support now`)}static decipher(w){const T=e.Transaction.fromHex(w),O=m.payload(T);if(O.isSome()){const A=m.integers(O.value()),R=E.from_integers(T,A.value()),M=R.getEtching(),v=R.getMint(),U=R.getPointer();return(0,n.some)(new m(R.edicts,M,v,U))}return(0,n.none)()}encipher(){const T=this.toMessage().toBuffer(),O=Buffer.from("6a5d","hex");let A;if(T.length<76)A=Buffer.alloc(1),A.writeUint8(T.length);else if(T.length<256)A=Buffer.alloc(2),A.writeUint8(76),A.writeUint8(T.length);else if(T.length<65536)A=Buffer.alloc(3),A.writeUint8(77),A.writeUint16LE(T.length);else if(T.length<4294967296)A=Buffer.alloc(5),A.writeUint8(78),A.writeUint32LE(T.length);else throw new Error("runestone too big!");return Buffer.concat([O,A,T])}static payload(w){for(const T of w.outs){const O=e.script.decompile(T.script);if(O[0]===e.script.OPS.OP_RETURN&&O[1]===m.MAGIC_NUMBER){for(let A=2;A<O.length;A++){const R=O[A];return R instanceof Uint8Array?(0,n.some)(Array.from(R)):(0,n.none)()}return(0,n.none)()}}return(0,n.none)()}static integers(w){let T=[],O=0;for(;O<w.length;){let{n:A,len:R}=(0,r.decodeLEB128)(w.slice(O));T.push(A),O+=R}return(0,n.some)(T)}toMessage(){let w=new Map;const T=this.etching.value();if(T){let R=1;if(T.terms.isSome()){let $=1<<a.Terms;R|=$}if(T.turbo){let $=1<<a.Turbo;R|=$}w.set(u.Flags,[BigInt(R)]);const M=T.rune.value();M!==null&&w.set(u.Rune,[BigInt(M.value)]);const v=T.divisibility.value();v!==null&&w.set(u.Divisibility,[BigInt(v)]);const U=T.spacers.value();U!==null&&w.set(u.Spacers,[BigInt(U)]);const V=T.symbol.value();V!==null&&w.set(u.Symbol,[BigInt(V.charCodeAt(0))]);const K=T.premine.value();K!==null&&w.set(u.Premine,[BigInt(K)]);const H=T.terms.value();if(H!==null){w.set(u.Amount,[BigInt(H.amount)]),w.set(u.Cap,[BigInt(H.cap)]);const $=H.height.start.value();$&&w.set(u.HeightStart,[BigInt($)]);const P=H.height.end.value();P&&w.set(u.HeightEnd,[BigInt(P)]);const D=H.offset.start.value();D&&w.set(u.OffsetStart,[BigInt(D)]);const F=H.offset.end.value();F&&w.set(u.OffsetEnd,[BigInt(F)])}}const O=this.mint.value();O!==null&&w.set(u.Mint,[BigInt(O.block),BigInt(O.idx)]);const A=this.pointer.value();return A!==null&&w.set(u.Pointer,[BigInt(A)]),new E(w,this.edicts,0)}}Xe.Runestone=m,m.MAGIC_NUMBER=93;class E{constructor(w=new Map,T=[],O=0){this.fields=w,this.edicts=T,this.flaws=O}static from_integers(w,T){let O=new Map,A=[],R=0,M=!1;for(let v=0;v<T.length;){let U=T[v];if(Number(U)===u.Body){M=!0,v+=1;continue}if(M){let V=new o(0,0);for(const K of(0,i.chunks)(T.slice(v),4)){if(K.length!=4){R|=f.TrailingIntegers;break}let H=V.next(K[0],K[1]);if(!H.isSome()){R|=f.EdictRuneId;break}const $=c.from_integers(w,H.value(),K[2],K[3]);if(!$.isSome()){R|=f.EdictOutput;break}V=H.value(),A.push($.value())}v+=4}else{let V=T[v+1];const K=O.get(Number(U))||[];K.push(V),O.set(Number(U),K),v+=2}}return new E(O,A,R)}addFieldVal(w,T){const O=this.fields.get(Number(w))||[];O.push(T),this.fields.set(Number(w),O)}addEdict(w){this.edicts.push(w)}toBuffer(){const w=[];for(const[T,O]of this.fields)for(const A of O){const R=Buffer.alloc(1);R.writeUInt8(T),w.push(R),w.push(Buffer.from((0,r.encodeLEB128)(A)))}if(this.edicts.length>0){w.push(Buffer.from("00","hex")),this.edicts.sort((A,R)=>A.id.block==R.id.block?A.id.idx-R.id.idx:A.id.block-R.id.block);let T=0n,O=0n;for(let A=0;A<this.edicts.length;A++){const R=this.edicts[A];if(A==0)T=BigInt(R.id.block),O=BigInt(R.id.idx),w.push(Buffer.from((0,r.encodeLEB128)(T))),w.push(Buffer.from((0,r.encodeLEB128)(O)));else{const M=BigInt(R.id.block),v=BigInt(R.id.idx);if(M==T){const U=v-O;O=v,w.push(Buffer.from((0,r.encodeLEB128)(0n))),w.push(Buffer.from((0,r.encodeLEB128)(U)))}else{const U=M-T;T=M,O=v,w.push(Buffer.from((0,r.encodeLEB128)(U))),w.push(Buffer.from((0,r.encodeLEB128)(v)))}}w.push(Buffer.from((0,r.encodeLEB128)(BigInt(R.amount)))),w.push(Buffer.from((0,r.encodeLEB128)(BigInt(R.output))))}}return Buffer.concat(w)}getFlags(){return Number(this.fields.get(u.Flags))}hasFlags(w){const T=this.getFlags(),O=1<<w;return(T&O)!=0}getMint(){if(!this.fields.has(u.Mint))return(0,n.none)();const[w,T]=this.fields.get(u.Mint);return(0,n.some)(new o(Number(w),Number(T)))}getEtching(){if(!this.hasFlags(a.Etching))return(0,n.none)();const w=this.getDivisibility(),T=this.getPremine(),O=this.getRune(),A=this.getSpacers(),R=this.getSymbol(),M=this.getTerms(),v=this.hasFlags(a.Turbo);return(0,n.some)(new g(w,T,O,A,R,M,v))}getDivisibility(){if(!this.fields.has(u.Divisibility))return(0,n.none)();const[w]=this.fields.get(u.Divisibility);if(w>g.MAX_DIVISIBILITY)throw new Error("invalid divisibility");return(0,n.some)(Number(w))}getPremine(){if(!this.fields.has(u.Premine))return(0,n.none)();const[w]=this.fields.get(u.Premine);return(0,n.some)(Number(w))}getRune(){if(!this.fields.has(u.Rune))return(0,n.none)();const[w]=this.fields.get(u.Rune);return(0,n.some)(new y(w))}getSpacers(){if(!this.fields.has(u.Spacers))return(0,n.none)();const[w]=this.fields.get(u.Spacers);if(w>g.MAX_SPACERS)throw new Error("invalid spacers");return(0,n.some)(Number(w))}getHeightStart(){if(!this.fields.has(u.HeightStart))return(0,n.none)();const[w]=this.fields.get(u.HeightStart);return(0,n.some)(Number(w))}getHeightEnd(){if(!this.fields.has(u.HeightEnd))return(0,n.none)();const[w]=this.fields.get(u.HeightEnd);return(0,n.some)(Number(w))}getOffsetStart(){if(!this.fields.has(u.OffsetStart))return(0,n.none)();const[w]=this.fields.get(u.OffsetStart);return(0,n.some)(Number(w))}getOffsetEnd(){if(!this.fields.has(u.OffsetEnd))return(0,n.none)();const[w]=this.fields.get(u.OffsetEnd);return(0,n.some)(Number(w))}getCap(){if(!this.fields.has(u.Cap))return(0,n.none)();const[w]=this.fields.get(u.Cap);return(0,n.some)(Number(w))}getAmount(){if(!this.fields.has(u.Amount))return(0,n.none)();const[w]=this.fields.get(u.Amount);return(0,n.some)(Number(w))}getSymbol(){if(!this.fields.has(u.Symbol))return(0,n.none)();const[w]=this.fields.get(u.Symbol);return(0,n.some)(String.fromCharCode(Number(w)))}getTerms(){if(!this.hasFlags(a.Terms))return(0,n.none)();const w=this.getCap();if(!w.isSome())throw new Error("no cap field");const T=this.getAmount();if(!T.isSome())throw new Error("no amount field");const O=this.getHeightStart(),A=this.getHeightEnd(),R=this.getOffsetStart(),M=this.getOffsetEnd(),v=new l(O,A),U=new l(R,M);return(0,n.some)(new d(T.value(),w.value(),v,U))}getPointer(){if(!this.fields.has(u.Pointer))return(0,n.none)();const[w]=this.fields.get(u.Pointer);return(0,n.some)(Number(w))}}Xe.Message=E;class _{constructor(w=new Map,T=Buffer.alloc(0)){this.fields=w,this.data=T}setContent(w,T){this.fields.set(1,Buffer.from(w,"utf8")),this.data=T}setRune(w){let O=(0,t.base26Encode)((0,s.removeSpacers)(w)).toString(16);O.length%2===1&&(O="0"+O),this.setField(_.Tag.RUNE,Buffer.from(O,"hex").reverse())}setField(w,T){this.fields.set(w,T)}static decipher(w,T){const R=e.Transaction.fromHex(w).ins[T].witness[1],M=e.script.decompile(R),v=new Map,U=[];let V=!1;for(let K=5;K<M.length-1;){const H=M[K];if(H===0){V=!0,K++;continue}else if(V)U.push(H),K++;else{const $=H-80,P=M[K+1];if(typeof P=="number"){const D=Buffer.alloc(1);D.writeUint8(P),v.set($,D)}else v.set($,P);K+=2}}return new _(v,Buffer.concat(U))}encipher(){const w=[];if(this.data&&this.data.length>0){w.push(Buffer.from("0063036f7264","hex")),Array.from(this.fields.entries()).sort((O,A)=>O[0]-A[0]).forEach(([O,A])=>{const R=Buffer.alloc(1);R.writeUInt8(O),w.push(Buffer.from("01","hex")),w.push(R),A.length!=1||A[0]!=0?w.push((0,i.toPushData)(A)):w.push(A)}),w.push(Buffer.from("00","hex"));const T=(0,i.chunks)(Array.from(this.data),520);for(const O of T)w.push((0,i.toPushData)(Buffer.from(O)))}else{w.push(Buffer.from("0063","hex"));const T=this.fields.get(_.Tag.RUNE);if(!T)throw new Error("No rune found!");w.push((0,i.toPushData)(T))}return w.push(Buffer.from("68","hex")),Buffer.concat(w)}}return Xe.EtchInscription=_,_.Tag={CONTENT_TYPE:1,POINTER:2,PARENT:3,METADATA:5,METAPROTOCOL:7,CONTENT_ENCODING:9,DELEGATE:11,RUNE:13},Xe}var dy;function UA(){return dy||(dy=1,(function(e){var t=Ei&&Ei.__createBinding||(Object.create?(function(s,o,c,a){a===void 0&&(a=c);var u=Object.getOwnPropertyDescriptor(o,c);(!u||("get"in u?!o.__esModule:u.writable||u.configurable))&&(u={enumerable:!0,get:function(){return o[c]}}),Object.defineProperty(s,a,u)}):(function(s,o,c,a){a===void 0&&(a=c),s[a]=o[c]})),n=Ei&&Ei.__exportStar||function(s,o){for(var c in s)c!=="default"&&!Object.prototype.hasOwnProperty.call(o,c)&&t(o,s,c)};Object.defineProperty(e,"__esModule",{value:!0}),e.removeSpacers=e.getSpacersVal=e.applySpacers=e.some=e.none=void 0,n(RA(),e);var r=Jw();Object.defineProperty(e,"none",{enumerable:!0,get:function(){return r.none}}),Object.defineProperty(e,"some",{enumerable:!0,get:function(){return r.some}});var i=Qw();Object.defineProperty(e,"applySpacers",{enumerable:!0,get:function(){return i.applySpacers}}),Object.defineProperty(e,"getSpacersVal",{enumerable:!0,get:function(){return i.getSpacersVal}}),Object.defineProperty(e,"removeSpacers",{enumerable:!0,get:function(){return i.removeSpacers}})})(Ei)),Ei}var fs=UA();function Eo(e){if(e.length%2!==0)throw new Error("Hex string must have even length");const t=new Uint8Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=parseInt(e.substr(n,2),16);return t}function Ih(e){return Array.from(e).map(t=>t.toString(16).padStart(2,"0")).join("")}function Oh(e){return e===Ns.Mainnet?Pn:Fy}function Bh(e,t=Ns.Testnet){const n=Oh(t);return Ag(e,n)}function si(e){const t=Pn,n=Fy,r=D1;let i,s,o=Jt.UNKNOWN;if(e.startsWith("bc1")||e.startsWith("tb1")||e.startsWith("bcrt1"))try{return s=kl(e),s.version===0?s.data.length===20?o=Jt.P2WPKH:o=Jt.P2WSH:o=Jt.P2TR,o}catch{return Jt.UNKNOWN}else try{return i=xg(e),i.version===t.pubKeyHash||i.version===n.pubKeyHash||i.version===r.pubKeyHash?o=Jt.P2PKH:(i.version===t.scriptHash||(i.version,n.scriptHash),o=Jt.P2SH_P2WPKH),o}catch{return Jt.UNKNOWN}}function CA(e,t,n){const r=Bh(e,n),i=t.coins?.[0];return{txid:t.txid,vout:t.vout,satoshis:t.sats.toString(),height:void 0,runes:i?[{id:i.id,amount:i.value.toString()}]:[],address:e,scriptPk:Ih(r)}}async function e1(e,t){try{const n=t===Ns.Mainnet?"https://mpc.omnity.network/utxo-status":"https://mpc.omnity.network/testnet4/utxo-status",r=await ht.post(n,e).then(c=>c.data);if(!r)return null;const i=JSON.stringify(r),o=new TextEncoder().encode(i);return Array.from(o)}catch{return null}}const HA=Object.freeze(Object.defineProperty({__proto__:null,bytesToHex:Ih,formatPoolUtxo:CA,getAddressType:si,getScriptByAddress:Bh,getUtxoProof:e1,hexToBytes:Eo,toBitcoinNetwork:Oh},Symbol.toStringTag,{value:"Module"})),FA="kqs64-paaaa-aaaar-qamza-cai",MA="hvyp5-5yaaa-aaaao-qjxha-cai",Qr=BigInt(546),on="0:0",qA="https://runescan-hasura-mainnet.omnity.network/v1/graphql",VA="https://runescan-hasura-testnet.omnity.network/v1/graphql",py={P2PKH:148,P2SH_P2WPKH:91,P2WPKH:68,P2WSH:140,P2SH:108,P2TR:58,UNKNOWN:110},yy={P2PKH:34,P2SH_P2WPKH:32,P2WPKH:31,P2WSH:43,P2SH:32,P2TR:43,UNKNOWN:34},LA=new Set(["P2WPKH","P2WSH","P2SH_P2WPKH","P2TR"]),$A=2;class oi{psbt;client;inputAddressTypes=[];outputAddressTypes=[];config;userInputUtxoDusts=BigInt(0);intentions=[];txFee=BigInt(0);additionalDustNeeded=BigInt(0);inputUtxos=[];constructor(t,n){this.config=t,this.psbt=new ma({network:Oh(t.network)}),this.client=n}addInput(t){if(this.inputUtxos.findIndex(i=>i.txid===t.txid&&i.vout===t.vout)>=0)return;const{address:n}=t;if(si(n)===Jt.P2TR){let i=t.pubkey;i||t.address===this.config.address&&this.config.publicKey&&(i=this.config.publicKey);const s=i?i.length===66?i.slice(2):i:void 0;s?this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:Eo(t.scriptPk)},tapInternalKey:Eo(s)}):this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:Eo(t.scriptPk)}})}else this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:Eo(t.scriptPk)}});this.inputAddressTypes.push(si(n)),this.inputUtxos.push(t),(n===this.config.address||n===this.config.paymentAddress)&&t.runes.length!==0&&(this.userInputUtxoDusts+=BigInt(t.satoshis))}addOutput(t,n){this.psbt.addOutput({address:t,value:n}),this.outputAddressTypes.push(si(t))}addScriptOutput(t){this.psbt.addOutput({script:t,value:BigInt(0)}),this.outputAddressTypes.push({OpReturn:BigInt(t.length)})}selectRuneUtxos(t,n,r){const i=[];if(r==BigInt(0))return i;for(const s of t)if(s.runes.length){const o=s.runes.find(c=>c.id==n);if(o&&BigInt(o.amount)==r){i.push(s);break}}if(i.length==0){let s=BigInt(0);for(const o of t)if(o.runes.forEach(c=>{c.id==n&&(s=s+BigInt(c.amount))}),i.push(o),s>=r)break;if(s<r)throw new Error("INSUFFICIENT_RUNE_UTXOs")}return i}selectBtcUtxos(t,n,r=!1){const i=[];if(n<=BigInt(0))return i;let s=BigInt(0);for(const o of t)if(!(o.runes.length&&!r)&&(s+=BigInt(o.satoshis),i.push(o),s>=n))break;if(s<n)throw new Error(`Insufficient BTC UTXOs: need ${n}, have ${s}`);return i}async addBtcAndFees(t,n){const r=this.config.paymentAddress,i=this.additionalDustNeeded,s=si(r),o=this.userInputUtxoDusts,c=this.config.feeRate;this.outputAddressTypes.push(s);let a=!0,u=BigInt(0),f=BigInt(0),l=[],d=BigInt(0),y=BigInt(0);const g=[...this.inputAddressTypes];do{if(u=f,c!==void 0){const _=oi.estimateTxVirtualSize(this.inputAddressTypes,this.outputAddressTypes);f=BigInt(Math.round(c*_))}else f=(await this.client.orchestrator.estimate_min_tx_fee({input_types:this.inputAddressTypes,pool_address:this.intentions.map(S=>S.poolAddress),output_types:this.outputAddressTypes}).catch(S=>{throw console.error("estimate_min_tx_fee failed:",S),S})).Ok;if(d=n+f+i-o,f>u&&d>0){const _=this.selectBtcUtxos(t,d);if(_.length===0)throw new Error("INSUFFICIENT_BTC_UTXOs");this.inputAddressTypes=g.concat(_.map(()=>s));const S=_.reduce((w,T)=>w+BigInt(T.satoshis),BigInt(0));S-d>0&&S-d>Qr||(this.outputAddressTypes.pop(),a=!1),l=_}}while(f>u&&d>0);this.inputAddressTypes=[...g],a&&this.outputAddressTypes.pop();let m=BigInt(0);l.forEach(_=>{this.addInput(_),m+=BigInt(_.satoshis)});const E=m-d;if(E<0)throw new Error("Insufficient UTXO(s)");E>Qr?this.addOutput(r,E):E>BigInt(0)&&(y=E),this.txFee=y+f}async getInvolvedAddressUtxos(){const t={},n={},r=new Map,i=this.intentions.map(o=>o.poolAddress);r.set(this.config.paymentAddress,{needBtc:!0,runeIds:new Set});const s=o=>{const c=o.trim();return r.has(c)||r.set(c,{needBtc:!1,runeIds:new Set}),r.get(c)};for(const o of this.intentions){for(const u of o.inputCoins){const f=s(u.from);u.coin.id===on?f.needBtc=!0:f.runeIds.add(u.coin.id)}for(const u of o.outputCoins){const f=s(u.to);u.coin.id===on?f.needBtc=!0:f.runeIds.add(u.coin.id)}const c=s(o.poolAddress),a=[...o.inputCoins.map(u=>u.coin.id),...o.outputCoins.map(u=>u.coin.id)];for(const u of a)u===on?c.needBtc=!0:c.runeIds.add(u)}return await Promise.all(Array.from(r.entries()).map(async([o,c])=>{if(c.needBtc)try{t[o]=await this.client.getBtcUtxos(o,!i.includes(o))}catch{t[o]=[]}c.runeIds.size>0&&(n[o]={},await Promise.all(Array.from(c.runeIds).map(async a=>{try{n[o][a]=await this.client.getRuneUtxos(o,a)}catch{n[o][a]=[]}})))})),{btc:t,rune:n}}addInputsAndCalculateOutputs(t){if(!this.intentions.length)throw new Error("No intentions added");const n=this.intentions.map(a=>a.poolAddress),r={},i={};let s=BigInt(0);const o=new Map,c=new Set;this.intentions.forEach(({poolAddress:a,inputCoins:u,outputCoins:f,poolUtxos:l})=>{const d=[...u.filter(({from:g})=>!n.includes(g))],y=[...f];if(d.forEach(({coin:g,from:m})=>{!f.find(E=>E.coin.id===g.id)&&!(n.includes(m)&&m!==a)&&y.push({coin:g,to:a})}),y.forEach(({coin:g})=>{u.find(m=>m.coin.id===g.id)||d.push({coin:g,from:a})}),d.length===0&&y.length===0&&l?.length){const g=o.get(a);o.set(a,g?g.concat(l):[...l]),c.add(a);return}d.forEach(({coin:g,from:m})=>{r[m]??={},r[m][g.id]=(r[m][g.id]??BigInt(0))+BigInt(g.value)}),y.forEach(({coin:g,to:m})=>{i[m]??={},i[m][g.id]=(i[m][g.id]??BigInt(0))+BigInt(g.value)})});for(const[a,u]of o.entries()){if(!u.length)continue;i[a]??={};const f=i[a];u.forEach(l=>{this.addInput(l),f[on]=(f[on]??BigInt(0))+BigInt(l.satoshis),l.runes.forEach(d=>{f[d.id]=(f[d.id]??BigInt(0))+BigInt(d.amount)})})}for(const[a,u]of Object.entries(r))for(const[f,l]of Object.entries(u))if(f===on){if(a===this.config.paymentAddress){s+=l;continue}const d=t.btc[a]||[],y=this.selectBtcUtxos(d,l,n.includes(a)),m=y.reduce((E,_)=>E+BigInt(_.satoshis),BigInt(0))-l;m>BigInt(0)&&(i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+m),y.forEach(E=>{this.addInput(E),n.includes(a)&&E.runes.forEach(_=>{(r[a]?.[_.id]??BigInt(0))>BigInt(0)||(i[a]??={},i[a][_.id]=(i[a][_.id]??BigInt(0))+BigInt(_.amount))})})}else{const d=t.rune[a]?.[f]||[],y=this.selectRuneUtxos(d,f,l),g=y.reduce((_,S)=>{const w=S.runes.find(T=>T.id===f);return _+BigInt(w?.amount??0)},BigInt(0)),m=y.reduce((_,S)=>_+BigInt(S.satoshis),BigInt(0)),E=g-l;if(n.includes(a)){i[a]??={};const _=i[a],S=(r[a]?.[on]??BigInt(0))>BigInt(0);m>BigInt(0)&&!S&&(_[on]=(_[on]??BigInt(0))+m),E>BigInt(0)&&(_[f]=(_[f]??BigInt(0))+E)}else E>BigInt(0)&&(i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+E);y.forEach(_=>this.addInput(_))}for(const[a,u]of Object.entries(i))if(!(r[a]||!n.includes(a)||c.has(a)))for(const[f]of Object.entries(u))if(f===on){const l=t.btc[a]||[],d=l.reduce((y,g)=>y+BigInt(g.satoshis),BigInt(0));i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+d,l.forEach(y=>{this.addInput(y),y.runes.forEach(g=>{i[a]??={},i[a][g.id]=(i[a][g.id]??BigInt(0))+BigInt(g.amount)})})}else{const l=t.rune[a]?.[f]||[],d=l.reduce((y,g)=>{const m=g.runes.find(E=>E.id===f);return y+BigInt(m?.amount??0)},BigInt(0));i[a]??={},i[a][f]=(i[a][f]??BigInt(0))+d,l.forEach(y=>this.addInput(y))}return{addressOutputCoinAmounts:i,paymentBtcRequired:s}}addOutputs(t){const n=this.config.mergeSelfRuneBtcOutputs===!0,r=new Set;for(const[,s]of Object.entries(t))for(const o of Object.keys(s))o!==on&&r.add(o);const i=Array.from(r);if(i.length>0){const s=[],o=[];let c=1;i.forEach(u=>{const f=new fs.RuneId(Number(u.split(":")[0]),Number(u.split(":")[1]));for(const[l,d]of Object.entries(t)){const y=d[u]??BigInt(0);y>BigInt(0)&&(s.push(new fs.Edict(f,y,c)),o.push(l),c++)}});const a=new fs.Runestone(s,fs.none(),fs.none(),fs.none());this.addScriptOutput(new Uint8Array(a.encipher())),o.forEach(u=>{const f=t[u]?.[on]??BigInt(0),l=u===this.config.address,d=f>BigInt(0)&&(!l||n),y=d&&f>Qr?f:Qr;this.addOutput(u,y),d?(f<Qr&&(this.additionalDustNeeded+=Qr-f),delete t[u][on]):this.additionalDustNeeded+=Qr})}for(const[s,o]of Object.entries(t)){const c=o[on]??BigInt(0);c>BigInt(0)&&this.addOutput(s,c)}}addIntention(t){this.intentions.push(t)}async build(){const t=await this.getInvolvedAddressUtxos();for(const f of this.intentions){const l=f.poolUtxos;if(!l)continue;t.btc[f.poolAddress]=l,t.rune[f.poolAddress]={};const d=t.rune[f.poolAddress];for(const y of l)for(const g of y.runes)(d[g.id]??=[]).push(y)}const{addressOutputCoinAmounts:n,paymentBtcRequired:r}=this.addInputsAndCalculateOutputs(t);this.addOutputs(n);const i=this.config.paymentAddress,s=t.btc[i]??[];await this.addBtcAndFees(s,r);const c=this.psbt.__CACHE.__TX.clone(),a=[];for(let f=0;f<this.inputUtxos.length;f++){const l=this.inputUtxos[f],d=l.address;if(d!==this.config.paymentAddress||d!==this.config.address)continue;const y=this.psbt.data.inputs[f].redeemScript,g=si(d);if(a.push({index:f,...g===Jt.P2TR?{address:d,disableTweakSigner:!1}:{publicKey:l.pubkey,disableTweakSigner:!0}}),y&&g===Jt.P2SH_P2WPKH){const m=nn([y]);c.setInputScript(f,m)}}const u=c.getId();return{psbt:this.psbt,txid:u,fee:this.txFee,toSignInputs:a}}static estimateTxVirtualSize(t,n){const r=t.length,i=n.length;let s=8+oi.varIntSize(r)+oi.varIntSize(i),o=!1;for(const c of t){const a=oi.parseAddressType(c);if(a.key==="OpReturn")continue;const u=py[a.key]??py.UNKNOWN;s+=u,LA.has(a.key)&&(o=!0)}for(const c of n){const a=oi.parseAddressType(c);if(a.key==="OpReturn"){const f=Math.max(0,a.opReturnLength??0);s+=11+f;continue}const u=yy[a.key]??yy.UNKNOWN;s+=u}return o&&(s+=1),s+$A}static parseAddressType(t){if("OpReturn"in t){const r=t.OpReturn!==void 0?Number(t.OpReturn):0;return{key:"OpReturn",opReturnLength:Number.isFinite(r)?r:0}}const n=["P2PKH","P2SH_P2WPKH","P2WPKH","P2WSH","P2SH","P2TR"];for(const r of n)if(r in t)return{key:r};return{key:"UNKNOWN"}}static varIntSize(t){return t<253?1:t<=65535?3:t<=4294967295?5:9}async send(t){if(!this.intentions.length)throw new Error("No itentions added");const n=this.inputUtxos.filter(i=>i.address===this.config.paymentAddress||i.address===this.config.address),r=await e1(n,this.config.network);if(!r)throw new Error("Failed to get utxo proof");return this.client.orchestrator.invoke({intention_set:{tx_fee_in_sats:this.txFee,initiator_address:this.config.paymentAddress,intentions:this.intentions.map(({action:i,actionParams:s,poolAddress:o,inputCoins:c,outputCoins:a,exchangeId:u,nonce:f})=>({exchange_id:u??this.config.exchangeId,input_coins:c.filter(l=>l.from!==o),output_coins:a,pool_address:o,action:i,action_params:s??"",pool_utxo_spent:[],pool_utxo_received:[],nonce:f}))},initiator_utxo_proof:r,psbt_hex:t,client_info:[this.config.clientInfo??""]}).then(i=>{if(i?.Ok)return i.Ok;{const s=i?.Err??{},o=Object.keys(s)[0],c=s[o];throw new Error(c?o==="ErrorOccurredDuringExecution"?`${o}: ${c.execution_steps?.[0]?.result?.Err??"Unknown Error"}`:`Invoke Error: ${JSON.stringify(i)}`:`Invoke Error: ${JSON.stringify(i)}`)}})}}class Is extends Error{response;request;constructor(t,n){const r=`${Is.extractMessage(t)}: ${JSON.stringify({response:t,request:n})}`;super(r),Object.setPrototypeOf(this,Is.prototype),this.response=t,this.request=n,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,Is)}static extractMessage(t){return t.errors?.[0]?.message??`GraphQL Error (Code: ${String(t.status)})`}}const gy=e=>e.toUpperCase(),Uf=e=>typeof e=="function"?e():e,t1=(e,t)=>e.map((n,r)=>[n,t[r]]),ls=e=>{let t={};return e instanceof Headers?t=DA(e):Array.isArray(e)?e.forEach(([n,r])=>{n&&r!==void 0&&(t[n]=r)}):e&&(t=e),t},DA=e=>{const t={};return e.forEach((n,r)=>{t[r]=n}),t},jA=e=>{try{const t=e();return KA(t)?t.catch(n=>my(n)):t}catch(t){return my(t)}},my=e=>e instanceof Error?e:new Error(String(e)),KA=e=>typeof e=="object"&&e!==null&&"then"in e&&typeof e.then=="function"&&"catch"in e&&typeof e.catch=="function"&&"finally"in e&&typeof e.finally=="function",Nh=e=>{throw new Error(`Unhandled case: ${String(e)}`)},ra=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),GA=(e,t)=>e.documents?e:{documents:e,requestHeaders:t,signal:void 0},WA=(e,t,n)=>e.query?e:{query:e,variables:t,requestHeaders:n,signal:void 0};function ia(e,t){if(!!!e)throw new Error(t)}function XA(e){return typeof e=="object"&&e!==null}function zA(e,t){if(!!!e)throw new Error("Unexpected invariant triggered.")}const YA=/\r\n|[\n\r]/g;function pl(e,t){let n=0,r=1;for(const i of e.body.matchAll(YA)){if(typeof i.index=="number"||zA(!1),i.index>=t)break;n=i.index+i[0].length,r+=1}return{line:r,column:t+1-n}}function ZA(e){return n1(e.source,pl(e.source,e.start))}function n1(e,t){const n=e.locationOffset.column-1,r="".padStart(n)+e.body,i=t.line-1,s=e.locationOffset.line-1,o=t.line+s,c=t.line===1?n:0,a=t.column+c,u=`${e.name}:${o}:${a}
77
77
  `,f=r.split(/\r\n|[\n\r]/g),l=f[i];if(l.length>120){const d=Math.floor(a/80),y=a%80,g=[];for(let m=0;m<l.length;m+=80)g.push(l.slice(m,m+80));return u+wy([[`${o} |`,g[0]],...g.slice(1,d+1).map(m=>["|",m]),["|","^".padStart(y)],["|",g[d+1]]])}return u+wy([[`${o-1} |`,f[i-1]],[`${o} |`,l],["|","^".padStart(a)],[`${o+1} |`,f[i+1]]])}function wy(e){const t=e.filter(([r,i])=>i!==void 0),n=Math.max(...t.map(([r])=>r.length));return t.map(([r,i])=>r.padStart(n)+(i?" "+i:"")).join(`
78
78
  `)}function JA(e){const t=e[0];return t==null||"kind"in t||"length"in t?{nodes:t,source:e[1],positions:e[2],path:e[3],originalError:e[4],extensions:e[5]}:t}class kh extends Error{constructor(t,...n){var r,i,s;const{nodes:o,source:c,positions:a,path:u,originalError:f,extensions:l}=JA(n);super(t),this.name="GraphQLError",this.path=u??void 0,this.originalError=f??void 0,this.nodes=by(Array.isArray(o)?o:o?[o]:void 0);const d=by((r=this.nodes)===null||r===void 0?void 0:r.map(g=>g.loc).filter(g=>g!=null));this.source=c??(d==null||(i=d[0])===null||i===void 0?void 0:i.source),this.positions=a??d?.map(g=>g.start),this.locations=a&&c?a.map(g=>pl(c,g)):d?.map(g=>pl(g.source,g.start));const y=XA(f?.extensions)?f?.extensions:void 0;this.extensions=(s=l??y)!==null&&s!==void 0?s:Object.create(null),Object.defineProperties(this,{message:{writable:!0,enumerable:!0},name:{enumerable:!1},nodes:{enumerable:!1},source:{enumerable:!1},positions:{enumerable:!1},originalError:{enumerable:!1}}),f!=null&&f.stack?Object.defineProperty(this,"stack",{value:f.stack,writable:!0,configurable:!0}):Error.captureStackTrace?Error.captureStackTrace(this,kh):Object.defineProperty(this,"stack",{value:Error().stack,writable:!0,configurable:!0})}get[Symbol.toStringTag](){return"GraphQLError"}toString(){let t=this.message;if(this.nodes)for(const n of this.nodes)n.loc&&(t+=`
79
79