@omnity/ree-client-ts-sdk 0.3.4 → 0.3.6

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.
@@ -1,33 +1,33 @@
1
- "use strict";var Hh=e=>{throw TypeError(e)};var Fh=(e,t,n)=>t.has(e)||Hh("Cannot "+n);var Me=(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),Yt=(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){Yt(e,t,i,n)},get _(){return Me(e,t,r)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O1=require("react/jsx-runtime"),Ae=require("react");function B1(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 Ny(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var vu={},Xs={},Lh;function N1(){if(Lh)return Xs;Lh=1,Xs.byteLength=c,Xs.toByteArray=u,Xs.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],S=m[1],_=new n(a(y,E,S)),w=0,T=S>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)],_[w++]=g>>16&255,_[w++]=g>>8&255,_[w++]=g&255;return S===2&&(g=t[y.charCodeAt(O)]<<2|t[y.charCodeAt(O+1)]>>4,_[w++]=g&255),S===1&&(g=t[y.charCodeAt(O)]<<10|t[y.charCodeAt(O+1)]<<4|t[y.charCodeAt(O+2)]>>2,_[w++]=g>>8&255,_[w++]=g&255),_}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;_<m;_+=3)E=(y[_]<<16&16711680)+(y[_+1]<<8&65280)+(y[_+2]&255),S.push(f(E));return S.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+_>T?T:w+_));return E===1?(g=y[m-1],S.push(e[g>>2]+e[g<<4&63]+"==")):E===2&&(g=(y[m-2]<<8)+y[m-1],S.push(e[g>>10]+e[g>>4&63]+e[g<<2&63]+"=")),S.join("")}return Xs}var _c={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var qh;function k1(){return qh||(qh=1,_c.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)},_c.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}),_c}/*!
1
+ "use strict";var Hh=e=>{throw TypeError(e)};var Fh=(e,t,n)=>t.has(e)||Hh("Cannot "+n);var Me=(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),Yt=(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){Yt(e,t,i,n)},get _(){return Me(e,t,r)}});Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const O1=require("react/jsx-runtime"),Ae=require("react");function B1(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 Ny(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var vu={},zs={},Lh;function N1(){if(Lh)return zs;Lh=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],S=m[1],_=new n(a(y,E,S)),w=0,T=S>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)],_[w++]=g>>16&255,_[w++]=g>>8&255,_[w++]=g&255;return S===2&&(g=t[y.charCodeAt(O)]<<2|t[y.charCodeAt(O+1)]>>4,_[w++]=g&255),S===1&&(g=t[y.charCodeAt(O)]<<10|t[y.charCodeAt(O+1)]<<4|t[y.charCodeAt(O+2)]>>2,_[w++]=g>>8&255,_[w++]=g&255),_}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;_<m;_+=3)E=(y[_]<<16&16711680)+(y[_+1]<<8&65280)+(y[_+2]&255),S.push(f(E));return S.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+_>T?T:w+_));return E===1?(g=y[m-1],S.push(e[g>>2]+e[g<<4&63]+"==")):E===2&&(g=(y[m-2]<<8)+y[m-1],S.push(e[g>>10]+e[g>>4&63]+e[g<<2&63]+"=")),S.join("")}return zs}var _c={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */var qh;function k1(){return qh||(qh=1,_c.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)},_c.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}),_c}/*!
2
2
  * The buffer module from node.js, for the browser.
3
3
  *
4
4
  * @author Feross Aboukhadijeh <https://feross.org>
5
5
  * @license MIT
6
- */var Vh;function ec(){return Vh||(Vh=1,(function(e){const t=N1(),n=k1(),r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=c,e.SlowBuffer=_,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:S(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:S(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=S(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"||He(k.length)?o(0):y(k);if(k.type==="Buffer"&&Array.isArray(k.data))return y(k.data)}function S(k){if(k>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return k|0}function _(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 U=0,j=Math.min(b,I);U<j;++U)if(p[U]!==h[U]){b=p[U],I=h[U];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 U=0;for(b=0;b<p.length;++b){let j=p[b];if(it(j,Uint8Array))U+j.length>I.length?(c.isBuffer(j)||(j=c.from(j)),j.copy(I,U)):Uint8Array.prototype.set.call(I,j,U);else if(c.isBuffer(j))j.copy(I,U);else throw new TypeError('"list" argument must be an Array of Buffers');U+=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 ut(k).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return h*2;case"hex":return h>>>1;case"base64":return Be(k).length;default:if(I)return b?-1:ut(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 D(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 L(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?D(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,U){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),U===void 0&&(U=this.length),h<0||b>p.length||I<0||U>this.length)throw new RangeError("out of range index");if(I>=U&&h>=b)return 0;if(I>=U)return-1;if(h>=b)return 1;if(h>>>=0,b>>>=0,I>>>=0,U>>>=0,this===p)return 0;let j=U-I,W=b-h;const ie=Math.min(j,W),Q=this.slice(I,U),fe=p.slice(h,b);for(let le=0;le<ie;++le)if(Q[le]!==fe[le]){j=Q[le],W=fe[le];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,He(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 U=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;U=2,j/=2,W/=2,h/=2}function ie(fe,le){return U===1?fe[le]:fe.readUInt16BE(le*U)}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*U}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 le=0;le<W;le++)if(ie(k,Q+le)!==ie(p,le)){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 U=p.length;b>U/2&&(b=U/2);let j;for(j=0;j<b;++j){const W=parseInt(p.substr(j*2,2),16);if(He(W))return j;k[h+j]=W}return j}function v(k,p,h,b){return gn(ut(p,k.length-h),k,h,b)}function C(k,p,h,b){return gn(bt(p),k,h,b)}function q(k,p,h,b){return gn(Be(p),k,h,b)}function K(k,p,h,b){return gn(Ot(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 U=this.length-h;if((b===void 0||b>U)&&(b=U),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 C(this,p,h,b);case"base64":return q(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 D(k,p,h){h=Math.min(k.length,h);const b=[];let I=p;for(;I<h;){const U=k[I];let j=null,W=U>239?4:U>223?3:U>191?2:1;if(I+W<=h){let ie,Q,fe,le;switch(W){case 1:U<128&&(j=U);break;case 2:ie=k[I+1],(ie&192)===128&&(le=(U&31)<<6|ie&63,le>127&&(j=le));break;case 3:ie=k[I+1],Q=k[I+2],(ie&192)===128&&(Q&192)===128&&(le=(U&15)<<12|(ie&63)<<6|Q&63,le>2047&&(le<55296||le>57343)&&(j=le));break;case 4:ie=k[I+1],Q=k[I+2],fe=k[I+3],(ie&192)===128&&(Q&192)===128&&(fe&192)===128&&(le=(U&15)<<18|(ie&63)<<12|(Q&63)<<6|fe&63,le>65535&&le<1114112&&(j=le))}}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 $(b)}const P=4096;function $(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 U=p;U<h;++U)I+=oe[k[U]];return I}function L(k,p,h){const b=k.slice(p,h);let I="";for(let U=0;U<b.length-1;U+=2)I+=String.fromCharCode(b[U]+b[U+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],U=1,j=0;for(;++j<h&&(U*=256);)I+=this[p+j]*U;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],U=1;for(;h>0&&(U*=256);)I+=this[p+--h]*U;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)&&he(p,this.length-8);const I=h+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,U=this[++p]+this[++p]*2**8+this[++p]*2**16+b*2**24;return BigInt(I)+(BigInt(U)<<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)&&he(p,this.length-8);const I=h*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],U=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+b;return(BigInt(I)<<BigInt(32))+BigInt(U)}),c.prototype.readIntLE=function(p,h,b){p=p>>>0,h=h>>>0,b||N(p,h,this.length);let I=this[p],U=1,j=0;for(;++j<h&&(U*=256);)I+=this[p+j]*U;return U*=128,I>=U&&(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,U=1,j=this[p+--I];for(;I>0&&(U*=256);)j+=this[p+--I]*U;return U*=128,j>=U&&(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)&&he(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)&&he(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 V(k,p,h,b,I,U){if(!c.isBuffer(k))throw new TypeError('"buffer" argument must be a Buffer instance');if(p>I||p<U)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;V(this,p,h,b,W,0)}let U=1,j=0;for(this[h]=p&255;++j<b&&(U*=256);)this[h+j]=p/U&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;V(this,p,h,b,W,0)}let U=b-1,j=1;for(this[h+U]=p&255;--U>=0&&(j*=256);)this[h+U]=p/j&255;return h+b},c.prototype.writeUint8=c.prototype.writeUInt8=function(p,h,b){return p=+p,h=h>>>0,b||V(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||V(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||V(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||V(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||V(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){ge(p,b,I,k,h,7);let U=Number(p&BigInt(4294967295));k[h++]=U,U=U>>8,k[h++]=U,U=U>>8,k[h++]=U,U=U>>8,k[h++]=U;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){ge(p,b,I,k,h,7);let U=Number(p&BigInt(4294967295));k[h+7]=U,U=U>>8,k[h+6]=U,U=U>>8,k[h+5]=U,U=U>>8,k[h+4]=U;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);V(this,p,h,b,ie-1,-ie)}let U=0,j=1,W=0;for(this[h]=p&255;++U<b&&(j*=256);)p<0&&W===0&&this[h+U-1]!==0&&(W=1),this[h+U]=(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);V(this,p,h,b,ie-1,-ie)}let U=b-1,j=1,W=0;for(this[h+U]=p&255;--U>=0&&(j*=256);)p<0&&W===0&&this[h+U+1]!==0&&(W=1),this[h+U]=(p/j>>0)-W&255;return h+b},c.prototype.writeInt8=function(p,h,b){return p=+p,h=h>>>0,b||V(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||V(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||V(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||V(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||V(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,U){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 U=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),U},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 U;if(typeof p=="number")for(U=h;U<b;++U)this[U]=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(U=0;U<b-h;++U)this[U+h]=j[U%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)&&he(p,k.length-(h+1))}function ge(k,p,h,b,I,U){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} ** ${(U+1)*8}${j}`:W=`>= -(2${j} ** ${(U+1)*8-1}${j}) and < 2 ** ${(U+1)*8-1}${j}`,new te.ERR_OUT_OF_RANGE("value",W,k)}we(b,I,U)}function J(k,p){if(typeof k!="number")throw new te.ERR_INVALID_ARG_TYPE(p,"number",k)}function he(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 Oe=/[^+/0-9A-Za-z-_]/g;function De(k){if(k=k.split("=")[0],k=k.trim().replace(Oe,""),k.length<2)return"";for(;k.length%4!==0;)k=k+"=";return k}function ut(k,p){p=p||1/0;let h;const b=k.length;let I=null;const U=[];for(let j=0;j<b;++j){if(h=k.charCodeAt(j),h>55295&&h<57344){if(!I){if(h>56319){(p-=3)>-1&&U.push(239,191,189);continue}else if(j+1===b){(p-=3)>-1&&U.push(239,191,189);continue}I=h;continue}if(h<56320){(p-=3)>-1&&U.push(239,191,189),I=h;continue}h=(I-55296<<10|h-56320)+65536}else I&&(p-=3)>-1&&U.push(239,191,189);if(I=null,h<128){if((p-=1)<0)break;U.push(h)}else if(h<2048){if((p-=2)<0)break;U.push(h>>6|192,h&63|128)}else if(h<65536){if((p-=3)<0)break;U.push(h>>12|224,h>>6&63|128,h&63|128)}else if(h<1114112){if((p-=4)<0)break;U.push(h>>18|240,h>>12&63|128,h>>6&63|128,h&63|128)}else throw new Error("Invalid code point")}return U}function bt(k){const p=[];for(let h=0;h<k.length;++h)p.push(k.charCodeAt(h)&255);return p}function Ot(k,p){let h,b,I;const U=[];for(let j=0;j<k.length&&!((p-=2)<0);++j)h=k.charCodeAt(j),b=h>>8,I=h%256,U.push(I),U.push(b);return U}function Be(k){return t.toByteArray(De(k))}function gn(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 He(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 P1=ec(),Iu={exports:{}},Dh;function R1(){if(Dh)return Iu.exports;Dh=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 S=1;S<arguments.length;S++)E[S-1]=arguments[S];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 C1=R1();const U1=Ny(C1);typeof globalThis>"u"&&(globalThis.global=globalThis);typeof globalThis.Buffer>"u"&&(globalThis.Buffer=P1.Buffer);typeof globalThis.process>"u"&&(globalThis.process=U1);var st={},Ou={},Xe={},qt={},Bu={},zs={},$h;function H1(){return $h||($h=1,Object.defineProperty(zs,"__esModule",{value:!0}),zs.crypto=void 0,zs.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0),zs}var jh;function ai(){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=_,e.hexToBytes=O,e.asyncLoop=R,e.utf8ToBytes=M,e.bytesToUtf8=v,e.toBytes=C,e.kdfInputToBytes=q,e.concatBytes=K,e.checkOpts=H,e.createHasher=P,e.createOptHasher=$,e.createXOFer=F,e.randomBytes=x;const t=H1();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,...L){if(!n(B))throw new Error("Uint8Array expected");if(L.length>0&&!L.includes(B.length))throw new Error("Uint8Array expected of length "+L+", 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,L=!0){if(B.destroyed)throw new Error("Hash instance has been destroyed");if(L&&B.finished)throw new Error("Hash#digest() has already been called")}function c(B,L){i(B);const N=L.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 L=0;L<B.length;L++)B[L].fill(0)}function l(B){return new DataView(B.buffer,B.byteOffset,B.byteLength)}function d(B,L){return B<<32-L|B>>>L}function y(B,L){return B<<L|B>>>32-L>>>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 L=0;L<B.length;L++)B[L]=g(B[L]);return B}e.swap32IfBE=e.isLE?B=>B:m;const E=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S=Array.from({length:256},(B,L)=>L.toString(16).padStart(2,"0"));function _(B){if(i(B),E)return B.toHex();let L="";for(let N=0;N<B.length;N++)L+=S[B[N]];return L}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 L=B.length,N=L/2;if(L%2)throw new Error("hex string expected, got unpadded hex of length "+L);const V=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)}V[G]=Y*16+ce}return V}const A=async()=>{};e.nextTick=A;async function R(B,L,N){let V=Date.now();for(let G=0;G<B;G++){N(G);const X=Date.now()-V;X>=0&&X<L||(await(0,e.nextTick)(),V+=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 C(B){return typeof B=="string"&&(B=M(B)),i(B),B}function q(B){return typeof B=="string"&&(B=M(B)),i(B),B}function K(...B){let L=0;for(let V=0;V<B.length;V++){const G=B[V];i(G),L+=G.length}const N=new Uint8Array(L);for(let V=0,G=0;V<B.length;V++){const X=B[V];N.set(X,G),G+=X.length}return N}function H(B,L){if(L!==void 0&&{}.toString.call(L)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(B,L)}class D{}e.Hash=D;function P(B){const L=V=>B().update(C(V)).digest(),N=B();return L.outputLen=N.outputLen,L.blockLen=N.blockLen,L.create=()=>B(),L}function $(B){const L=(V,G)=>B(G).update(C(V)).digest(),N=B({});return L.outputLen=N.outputLen,L.blockLen=N.blockLen,L.create=V=>B(V),L}function F(B){const L=(V,G)=>B(G).update(C(V)).digest(),N=B({});return L.outputLen=N.outputLen,L.blockLen=N.blockLen,L.create=V=>B(V),L}e.wrapConstructor=P,e.wrapConstructorWithOpts=$,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 ky(){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=ai();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 F1(){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=S,Ie.fromBig=n,Ie.split=r;const e=BigInt(2**32-1),t=BigInt(32);function n(v,C=!1){return C?{h:Number(v&e),l:Number(v>>t&e)}:{h:Number(v>>t&e)|0,l:Number(v&e)|0}}function r(v,C=!1){const q=v.length;let K=new Uint32Array(q),H=new Uint32Array(q);for(let D=0;D<q;D++){const{h:P,l:$}=n(v[D],C);[K[D],H[D]]=[P,$]}return[K,H]}const i=(v,C)=>BigInt(v>>>0)<<t|BigInt(C>>>0);Ie.toBig=i;const s=(v,C,q)=>v>>>q;Ie.shrSH=s;const o=(v,C,q)=>v<<32-q|C>>>q;Ie.shrSL=o;const c=(v,C,q)=>v>>>q|C<<32-q;Ie.rotrSH=c;const a=(v,C,q)=>v<<32-q|C>>>q;Ie.rotrSL=a;const u=(v,C,q)=>v<<64-q|C>>>q-32;Ie.rotrBH=u;const f=(v,C,q)=>v>>>q-32|C<<64-q;Ie.rotrBL=f;const l=(v,C)=>C;Ie.rotr32H=l;const d=(v,C)=>v;Ie.rotr32L=d;const y=(v,C,q)=>v<<q|C>>>32-q;Ie.rotlSH=y;const g=(v,C,q)=>C<<q|v>>>32-q;Ie.rotlSL=g;const m=(v,C,q)=>C<<q-32|v>>>64-q;Ie.rotlBH=m;const E=(v,C,q)=>v<<q-32|C>>>64-q;Ie.rotlBL=E;function S(v,C,q,K){const H=(C>>>0)+(K>>>0);return{h:v+q+(H/2**32|0)|0,l:H|0}}const _=(v,C,q)=>(v>>>0)+(C>>>0)+(q>>>0);Ie.add3L=_;const w=(v,C,q,K)=>C+q+K+(v/2**32|0)|0;Ie.add3H=w;const T=(v,C,q,K)=>(v>>>0)+(C>>>0)+(q>>>0)+(K>>>0);Ie.add4L=T;const O=(v,C,q,K,H)=>C+q+K+H+(v/2**32|0)|0;Ie.add4H=O;const A=(v,C,q,K,H)=>(v>>>0)+(C>>>0)+(q>>>0)+(K>>>0)+(H>>>0);Ie.add5L=A;const R=(v,C,q,K,H,D)=>C+q+K+H+D+(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:S,add3L:_,add3H:w,add4L:T,add4H:O,add5H:R,add5L:A};return Ie.default=M,Ie}var Wh;function Py(){if(Wh)return Xe;Wh=1,Object.defineProperty(Xe,"__esModule",{value:!0}),Xe.sha512_224=Xe.sha512_256=Xe.sha384=Xe.sha512=Xe.sha224=Xe.sha256=Xe.SHA512_256=Xe.SHA512_224=Xe.SHA384=Xe.SHA512=Xe.SHA224=Xe.SHA256=void 0;const e=ky(),t=F1(),n=ai(),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:C}=this;return[w,T,O,A,R,M,v,C]}set(w,T,O,A,R,M,v,C){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=C|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 D=i[H-15],P=i[H-2],$=(0,n.rotr)(D,7)^(0,n.rotr)(D,18)^D>>>3,F=(0,n.rotr)(P,17)^(0,n.rotr)(P,19)^P>>>10;i[H]=F+i[H-7]+$+i[H-16]|0}let{A:O,B:A,C:R,D:M,E:v,F:C,G:q,H:K}=this;for(let H=0;H<64;H++){const D=(0,n.rotr)(v,6)^(0,n.rotr)(v,11)^(0,n.rotr)(v,25),P=K+D+(0,e.Chi)(v,C,q)+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=q,q=C,C=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,C=C+this.F|0,q=q+this.G|0,K=K+this.H|0,this.set(O,A,R,M,v,C,q,K)}roundClean(){(0,n.clean)(i)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,n.clean)(this.buffer)}}Xe.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}}Xe.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(_=>BigInt(_))),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:C,Eh:q,El:K,Fh:H,Fl:D,Gh:P,Gl:$,Hh:F,Hl:x}=this;return[w,T,O,A,R,M,v,C,q,K,H,D,P,$,F,x]}set(w,T,O,A,R,M,v,C,q,K,H,D,P,$,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=C|0,this.Eh=q|0,this.El=K|0,this.Fh=H|0,this.Fl=D|0,this.Gh=P|0,this.Gl=$|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 V=f[N-15]|0,G=l[N-15]|0,X=t.rotrSH(V,G,1)^t.rotrSH(V,G,8)^t.shrSH(V,G,7),Y=t.rotrSL(V,G,1)^t.rotrSL(V,G,8)^t.shrSL(V,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:C,Dh:q,Dl:K,Eh:H,El:D,Fh:P,Fl:$,Gh:F,Gl:x,Hh:B,Hl:L}=this;for(let N=0;N<80;N++){const V=t.rotrSH(H,D,14)^t.rotrSH(H,D,18)^t.rotrBH(H,D,41),G=t.rotrSL(H,D,14)^t.rotrSL(H,D,18)^t.rotrBL(H,D,41),X=H&P^~H&F,Y=D&$^~D&x,ce=t.add5L(L,G,Y,u[N],l[N]),ue=t.add5H(ce,B,V,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,ge=A&M^A&C^M&C;B=F|0,L=x|0,F=P|0,x=$|0,P=H|0,$=D|0,{h:H,l:D}=t.add(q|0,K|0,ue|0,te|0),q=v|0,K=C|0,v=R|0,C=M|0,R=O|0,M=A|0;const J=t.add3L(te,ae,ge);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:C}=t.add(this.Ch|0,this.Cl|0,v|0,C|0),{h:q,l:K}=t.add(this.Dh|0,this.Dl|0,q|0,K|0),{h:H,l:D}=t.add(this.Eh|0,this.El|0,H|0,D|0),{h:P,l:$}=t.add(this.Fh|0,this.Fl|0,P|0,$|0),{h:F,l:x}=t.add(this.Gh|0,this.Gl|0,F|0,x|0),{h:B,l:L}=t.add(this.Hh|0,this.Hl|0,B|0,L|0),this.set(O,A,R,M,v,C,q,K,H,D,P,$,F,x,B,L)}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)}}Xe.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}}Xe.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}}Xe.SHA512_224=E;class S 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 Xe.SHA512_256=S,Xe.sha256=(0,n.createHasher)(()=>new s),Xe.sha224=(0,n.createHasher)(()=>new o),Xe.sha512=(0,n.createHasher)(()=>new d),Xe.sha384=(0,n.createHasher)(()=>new y),Xe.sha512_256=(0,n.createHasher)(()=>new S),Xe.sha512_224=(0,n.createHasher)(()=>new E),Xe}var Ys={},Nu={},ku={},Xh;function M1(){return Xh||(Xh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.hmac=e.HMAC=void 0;const t=ai();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 Fs(){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=S,e.asciiToBytes=_,e.inRange=T,e.aInRange=O,e.bitLen=A,e.bitGet=R,e.bitSet=M,e.createHmacDrbg=C,e.validateObject=K,e.isHash=H,e._validateObject=D,e.memoized=$;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=ai();var n=ai();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 L=(0,t.isBytes)(F),N=F?.length,V=x!==void 0;if(!L||V&&N!==x){const G=B&&`"${B}" `,X=V?` of length ${x}`:"",Y=L?`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 L;if(typeof x=="string")try{L=(0,t.hexToBytes)(x)}catch(V){throw new Error(F+" must be hex string or Uint8Array, cause: "+V)}else if((0,t.isBytes)(x))L=Uint8Array.from(x);else throw new Error(F+" must be hex string or Uint8Array");const N=L.length;if(typeof B=="number"&&N!==B)throw new Error(F+" of length "+B+" expected, got "+N);return L}function E(F,x){if(F.length!==x.length)return!1;let B=0;for(let L=0;L<F.length;L++)B|=F[L]^x[L];return B===0}function S(F){return Uint8Array.from(F)}function _(F){return Uint8Array.from(F,(x,B)=>{const L=x.charCodeAt(0);if(x.length!==1||L>127)throw new Error(`string contains non-ASCII character "${F[B]}" with code ${L} at position ${B}`);return L})}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,L){if(!T(x,B,L))throw new Error("expected valid "+F+": "+B+" <= n < "+L+", 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 C(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 L=ae=>new Uint8Array(ae),N=ae=>Uint8Array.of(ae);let V=L(F),G=L(F),X=0;const Y=()=>{V.fill(1),G.fill(0),X=0},ce=(...ae)=>B(G,V,...ae),ue=(ae=L(0))=>{G=ce(N(0),ae),V=ce(),ae.length!==0&&(G=ce(N(1),ae),V=ce())},te=()=>{if(X++>=1e3)throw new Error("drbg: tried 1000 values");let ae=0;const we=[];for(;ae<x;){V=ce();const ge=V.slice();we.push(ge),ae+=V.length}return(0,t.concatBytes)(...we)};return(ae,we)=>{Y(),ue(ae);let ge;for(;!(ge=we(te()));)ue();return Y(),ge}}const q={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 L=(N,V,G)=>{const X=q[V];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 "+V+", got "+Y)};for(const[N,V]of Object.entries(x))L(N,V,!1);for(const[N,V]of Object.entries(B))L(N,V,!0);return F}function H(F){return typeof F=="function"&&Number.isSafeInteger(F.outputLen)}function D(F,x,B={}){if(!F||typeof F!="object")throw new Error("expected valid options object");function L(N,V,G){const X=F[N];if(G&&X===void 0)return;const Y=typeof X;if(Y!==V||X===null)throw new Error(`param "${N}" is invalid: expected ${V}, got ${Y}`)}Object.entries(x).forEach(([N,V])=>L(N,V,!1)),Object.entries(B).forEach(([N,V])=>L(N,V,!0))}const P=()=>{throw new Error("not implemented")};e.notImplemented=P;function $(F){const x=new WeakMap;return(B,...L)=>{const N=x.get(B);if(N!==void 0)return N;const V=F(B,...L);return x.set(B,V),V}}})(Pu)),Pu}var _n={},Qe={},Yh;function tc(){if(Yh)return Qe;Yh=1,Object.defineProperty(Qe,"__esModule",{value:!0}),Qe.isNegativeLE=void 0,Qe.mod=l,Qe.pow=d,Qe.pow2=y,Qe.invert=g,Qe.tonelliShanks=w,Qe.FpSqrt=T,Qe.validateField=R,Qe.FpPow=M,Qe.FpInvertBatch=v,Qe.FpDiv=C,Qe.FpLegendre=q,Qe.FpIsSquare=K,Qe.nLength=H,Qe.Field=D,Qe.FpSqrtOdd=P,Qe.FpSqrtEven=$,Qe.hashToPrivateScalar=F,Qe.getFieldBytesLength=x,Qe.getMinHashLength=B,Qe.mapHashToField=L;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const e=Fs(),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,V){const G=N%V;return G>=t?G:V+G}function d(N,V,G){return M(D(G),N,V)}function y(N,V,G){let X=N;for(;V-- >t;)X*=X,X%=G;return X}function g(N,V){if(N===t)throw new Error("invert: expected non-zero number");if(V<=t)throw new Error("invert: expected positive modulus, got "+V);let G=l(N,V),X=V,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,V)}function m(N,V,G){if(!N.eql(N.sqr(V),G))throw new Error("Cannot find square root")}function E(N,V){const G=(N.ORDER+n)/s,X=N.pow(V,G);return m(N,X,V),X}function S(N,V){const G=(N.ORDER-o)/a,X=N.mul(V,r),Y=N.pow(X,G),ce=N.mul(V,Y),ue=N.mul(N.mul(ce,r),Y),te=N.mul(ce,N.sub(ue,N.ONE));return m(N,te,V),te}function _(N){const V=D(N),G=w(N),X=G(V,V.neg(V.ONE)),Y=G(V,X),ce=G(V,V.neg(X)),ue=(N+c)/f;return(te,Z)=>{let ae=te.pow(Z,ue),we=te.mul(ae,X);const ge=te.mul(ae,Y),J=te.mul(ae,ce),he=te.eql(te.sqr(we),Z),Oe=te.eql(te.sqr(ge),Z);ae=te.cmov(ae,we,he),we=te.cmov(J,ge,Oe);const De=te.eql(te.sqr(we),Z),ut=te.cmov(ae,we,De);return m(te,ut,Z),ut}}function w(N){if(N<i)throw new Error("sqrt is not defined for small field");let V=N-n,G=0;for(;V%r===t;)V/=r,G++;let X=r;const Y=D(N);for(;q(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,V);const ue=(V+n)/r;return function(Z,ae){if(Z.is0(ae))return ae;if(q(Z,ae)!==1)throw new Error("Cannot find square root");let we=G,ge=Z.mul(Z.ONE,ce),J=Z.pow(ae,V),he=Z.pow(ae,ue);for(;!Z.eql(J,Z.ONE);){if(Z.is0(J))return Z.ZERO;let Oe=1,De=Z.sqr(J);for(;!Z.eql(De,Z.ONE);)if(Oe++,De=Z.sqr(De),Oe===we)throw new Error("Cannot find square root");const ut=n<<BigInt(we-Oe-1),bt=Z.pow(ge,ut);we=Oe,ge=Z.sqr(bt),J=Z.mul(J,ge),he=Z.mul(he,bt)}return he}}function T(N){return N%s===i?E:N%a===o?S:N%f===u?_(N):w(N)}const O=(N,V)=>(l(N,V)&n)===n;Qe.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 V={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},G=A.reduce((X,Y)=>(X[Y]="function",X),V);return(0,e._validateObject)(N,G),N}function M(N,V,G){if(G<t)throw new Error("invalid exponent, negatives unsupported");if(G===t)return N.ONE;if(G===n)return V;let X=N.ONE,Y=V;for(;G>t;)G&n&&(X=N.mul(X,Y)),Y=N.sqr(Y),G>>=n;return X}function v(N,V,G=!1){const X=new Array(V.length).fill(G?N.ZERO:void 0),Y=V.reduce((ue,te,Z)=>N.is0(te)?ue:(X[Z]=ue,N.mul(ue,te)),N.ONE),ce=N.inv(Y);return V.reduceRight((ue,te,Z)=>N.is0(te)?ue:(X[Z]=N.mul(ue,X[Z]),N.mul(ue,te)),ce),X}function C(N,V,G){return N.mul(V,typeof G=="bigint"?g(G,N.ORDER):N.inv(G))}function q(N,V){const G=(N.ORDER-n)/r,X=N.pow(V,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,V){return q(N,V)===1}function H(N,V){V!==void 0&&(0,e.anumber)(V);const G=V!==void 0?V:N.toString(2).length,X=Math.ceil(G/8);return{nBitLength:G,nByteLength:X}}function D(N,V,G=!1,X={}){if(N<=t)throw new Error("invalid field: expected ORDER > 0, got "+N);let Y,ce,ue=!1,te;if(typeof V=="object"&&V!=null){if(X.sqrt||G)throw new Error("cannot specify opts in two arguments");const J=V;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 V=="number"&&(Y=V),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 ge=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=>!ge.is0(J)&&ge.isValid(J),isOdd:J=>(J&n)===n,neg:J=>l(-J,N),eql:(J,he)=>J===he,sqr:J=>l(J*J,N),add:(J,he)=>l(J+he,N),sub:(J,he)=>l(J-he,N),mul:(J,he)=>l(J*he,N),pow:(J,he)=>M(ge,J,he),div:(J,he)=>l(J*g(he,N),N),sqrN:J=>J*J,addN:(J,he)=>J+he,subN:(J,he)=>J-he,mulN:(J,he)=>J*he,inv:J=>g(J,N),sqrt:ce||(J=>(we||(we=T(N)),we(ge,J))),toBytes:J=>G?(0,e.numberToBytesLE)(J,ae):(0,e.numberToBytesBE)(J,ae),fromBytes:(J,he=!0)=>{if(te){if(!te.includes(J.length)||J.length>ae)throw new Error("Field.fromBytes: expected "+te+" bytes, got "+J.length);const De=new Uint8Array(ae);De.set(J,G?0:De.length-J.length),J=De}if(J.length!==ae)throw new Error("Field.fromBytes: expected "+ae+" bytes, got "+J.length);let Oe=G?(0,e.bytesToNumberLE)(J):(0,e.bytesToNumberBE)(J);if(ue&&(Oe=l(Oe,N)),!he&&!ge.isValid(Oe))throw new Error("invalid field element: outside of range 0..ORDER");return Oe},invertBatch:J=>v(ge,J),cmov:(J,he,Oe)=>Oe?he:J});return Object.freeze(ge)}function P(N,V){if(!N.isOdd)throw new Error("Field doesn't have isOdd");const G=N.sqrt(V);return N.isOdd(G)?G:N.neg(G)}function $(N,V){if(!N.isOdd)throw new Error("Field doesn't have isOdd");const G=N.sqrt(V);return N.isOdd(G)?N.neg(G):G}function F(N,V,G=!1){N=(0,e.ensureBytes)("privateHash",N);const X=N.length,Y=H(V).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,V-n)+n}function x(N){if(typeof N!="bigint")throw new Error("field order must be bigint");const V=N.toString(2).length;return Math.ceil(V/8)}function B(N){const V=x(N);return V+Math.ceil(V/2)}function L(N,V,G=!1){const X=N.length,Y=x(V),ce=B(V);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,V-n)+n;return G?(0,e.numberToBytesLE)(te,Y):(0,e.numberToBytesBE)(te,Y)}return Qe}var Zh;function L1(){if(Zh)return _n;Zh=1,Object.defineProperty(_n,"__esModule",{value:!0}),_n.wNAF=void 0,_n.negateCt=i,_n.normalizeZ=s,_n.mulEndoUnsafe=E,_n.pippenger=S,_n.precomputeMSMUnsafe=_,_n.validateBasic=w,_n._createCurveFields=O;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const e=Fs(),t=tc(),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,C)=>A.fromAffine(v.toAffine(M[C])))}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),C=2**A,q=(0,e.bitMask)(A),K=BigInt(A);return{windows:M,windowSize:v,mask:q,maxNumber:C,shiftBy:K}}function a(A,R,M){const{windowSize:v,mask:C,maxNumber:q,shiftBy:K}=M;let H=Number(A&C),D=A>>K;H>v&&(H-=q,D+=r);const P=R*v,$=P+Math.abs(H)-1,F=H===0,x=H<0,B=R%2!==0;return{nextN:D,offset:$,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 C=R;for(;M>n;)M&r&&(v=v.add(C)),C=C.double(),M>>=r;return v}precomputeWindow(R,M){const{windows:v,windowSize:C}=c(M,this.bits),q=[];let K=R,H=K;for(let D=0;D<v;D++){H=K,q.push(H);for(let P=1;P<C;P++)H=H.add(K),q.push(H);K=H.double()}return q}wNAF(R,M,v){if(!this.Fn.isValid(v))throw new Error("invalid scalar");let C=this.ZERO,q=this.BASE;const K=c(R,this.bits);for(let H=0;H<K.windows;H++){const{nextN:D,offset:P,isZero:$,isNeg:F,isNegF:x,offsetF:B}=a(v,H,K);v=D,$?q=q.add(i(x,M[B])):C=C.add(i(F,M[P]))}return g(v),{p:C,f:q}}wNAFUnsafe(R,M,v,C=this.ZERO){const q=c(R,this.bits);for(let K=0;K<q.windows&&v!==n;K++){const{nextN:H,offset:D,isZero:P,isNeg:$}=a(v,K,q);if(v=H,!P){const F=M[D];C=C.add($?F.negate():F)}}return g(v),C}getPrecomputes(R,M,v){let C=l.get(M);return C||(C=this.precomputeWindow(M,R),R!==1&&(typeof v=="function"&&(C=v(C)),l.set(M,C))),C}cached(R,M,v){const C=y(R);return this.wNAF(C,this.getPrecomputes(C,R,v),M)}unsafe(R,M,v,C){const q=y(R);return q===1?this._unsafeLadder(R,M,C):this.wNAFUnsafe(q,this.getPrecomputes(q,R,v),M,C)}createCache(R,M){o(M,this.bits),d.set(R,M),l.delete(R)}hasCache(R){return y(R)!==1}}_n.wNAF=m;function E(A,R,M,v){let C=R,q=A.ZERO,K=A.ZERO;for(;M>n||v>n;)M&r&&(q=q.add(C)),v&r&&(K=K.add(C)),C=C.double(),M>>=r,v>>=r;return{p1:q,p2:K}}function S(A,R,M,v){u(M,A),f(v,R);const C=M.length,q=v.length;if(C!==q)throw new Error("arrays of points and scalars must have equal length");const K=A.ZERO,H=(0,e.bitLen)(BigInt(C));let D=1;H>12?D=H-3:H>4?D=H-2:H>0&&(D=2);const P=(0,e.bitMask)(D),$=new Array(Number(P)+1).fill(K),F=Math.floor((R.BITS-1)/D)*D;let x=K;for(let B=F;B>=0;B-=D){$.fill(K);for(let N=0;N<q;N++){const V=v[N],G=Number(V>>BigInt(B)&P);$[G]=$[G].add(M[N])}let L=K;for(let N=$.length-1,V=K;N>0;N--)V=V.add($[N]),L=L.add(V);if(x=x.add(L),B!==0)for(let N=0;N<D;N++)x=x.double()}return x}function _(A,R,M,v){o(v,R.BITS),u(M,A);const C=A.ZERO,q=2**v-1,K=Math.ceil(R.BITS/v),H=(0,e.bitMask)(v),D=M.map(P=>{const $=[];for(let F=0,x=P;F<q;F++)$.push(x),x=x.add(P);return $});return P=>{if(f(P,R),P.length>M.length)throw new Error("array of scalars must be smaller than array of points");let $=C;for(let F=0;F<K;F++){if($!==C)for(let B=0;B<v;B++)$=$.double();const x=BigInt(K*v-(F+1)*v);for(let B=0;B<P.length;B++){const L=P[B],N=Number(L>>x&H);N&&($=$.add(D[B][N-1]))}}return $}}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 D of["p","n","h"]){const P=R[D];if(!(typeof P=="bigint"&&P>n))throw new Error(`CURVE.${D} must be positive bigint`)}const C=T(R.p,M.Fp,v),q=T(R.n,M.Fn,v),H=["Gx","Gy","a",A==="weierstrass"?"b":"d"];for(const D of H)if(!C.isValid(R[D]))throw new Error(`CURVE.${D} must be valid field element of CURVE.Fp`);return R=Object.freeze(Object.assign({},R)),{CURVE:R,Fp:C,Fn:q}}return _n}var Jh;function Ry(){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=S,e.SWUFpSqrtRatio=w,e.mapToCurveSimpleSWU=T,e.ecdh=A,e.ecdsa=R,e.weierstrassPoints=M,e._legacyHelperEquat=q,e.weierstrass=D;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=M1(),n=ai(),r=Fs(),i=L1(),s=tc(),o=(P,$)=>(P+(P>=0?$:-$)/y)/$;function c(P,$,F){const[[x,B],[L,N]]=$,V=o(N*P,F),G=o(-B*P,F);let X=P-V*x-G*L,Y=-V*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,$){const F={};for(let x of Object.keys($))F[x]=P[x]===void 0?$[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($=""){super($)}}e.DERErr=f,e.DER={Err:f,_tlv:{encode:(P,$)=>{const{Err:F}=e.DER;if(P<0||P>256)throw new F("tlv.encode: wrong tag");if($.length&1)throw new F("tlv.encode: unpadded data");const x=$.length/2,B=(0,r.numberToHexUnpadded)(x);if(B.length/2&128)throw new F("tlv.encode: long form length too big");const L=x>127?(0,r.numberToHexUnpadded)(B.length/2|128):"";return(0,r.numberToHexUnpadded)(P)+L+B+$},decode(P,$){const{Err:F}=e.DER;let x=0;if(P<0||P>256)throw new F("tlv.encode: wrong tag");if($.length<2||$[x++]!==P)throw new F("tlv.decode: wrong tlv");const B=$[x++],L=!!(B&128);let N=0;if(!L)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=$.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 V=$.subarray(x,x+N);if(V.length!==N)throw new F("tlv.decode: wrong value length");return{v:V,l:$.subarray(x+N)}}},_int:{encode(P){const{Err:$}=e.DER;if(P<l)throw new $("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 $("unexpected DER parsing assertion: unpadded hex");return F},decode(P){const{Err:$}=e.DER;if(P[0]&128)throw new $("invalid signature integer: negative");if(P[0]===0&&!(P[1]&128))throw new $("invalid signature integer: unnecessary leading zero");return(0,r.bytesToNumberBE)(P)}},toSig(P){const{Err:$,_int:F,_tlv:x}=e.DER,B=(0,r.ensureBytes)("signature",P),{v:L,l:N}=x.decode(48,B);if(N.length)throw new $("invalid signature: left bytes after parsing");const{v:V,l:G}=x.decode(2,L),{v:X,l:Y}=x.decode(2,G);if(Y.length)throw new $("invalid signature: left bytes after parsing");return{r:F.decode(V),s:F.decode(X)}},hexFromSig(P){const{_tlv:$,_int:F}=e.DER,x=$.encode(2,F.encode(P.r)),B=$.encode(2,F.encode(P.s)),L=x+B;return $.encode(48,L)}};const l=BigInt(0),d=BigInt(1),y=BigInt(2),g=BigInt(3),m=BigInt(4);function E(P,$){const{BYTES:F}=P;let x;if(typeof $=="bigint")x=$;else{let B=(0,r.ensureBytes)("private key",$);try{x=P.fromBytes(B)}catch{throw new Error(`invalid private key: expected ui8a of size ${F}, got ${typeof $}`)}}if(!P.isValidNot0(x))throw new Error("invalid private key: out of range [1..N-1]");return x}function S(P,$={}){const F=(0,i._createCurveFields)("weierstrass",P,$),{Fp:x,Fn:B}=F;let L=F.CURVE;const{h:N,n:V}=L;(0,r._validateObject)($,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:G}=$;if(G&&(!x.is0(L.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(He,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)(_(h),p)}else return(0,r.concatBytes)(Uint8Array.of(4),p,x.toBytes(k))}function ue(He){(0,r._abytes2)(He,void 0,"Point");const{publicKey:oe,publicKeyUncompressed:ne}=X,re=He.length,k=He[0],p=He.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 U=x.isOdd(I);return(k&1)===1!==U&&(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=$.toBytes||ce,Z=$.fromBytes||ue;function ae(He){const oe=x.sqr(He),ne=x.mul(oe,He);return x.add(x.add(ne,x.mul(He,L.a)),L.b)}function we(He,oe){const ne=x.sqr(oe),re=ae(He);return x.eql(ne,re)}if(!we(L.Gx,L.Gy))throw new Error("bad curve params: generator point");const ge=x.mul(x.pow(L.a,g),m),J=x.mul(x.sqr(L.b),BigInt(27));if(x.is0(x.add(ge,J)))throw new Error("bad curve params: a or b");function he(He,oe,ne=!1){if(!x.isValid(oe)||ne&&x.is0(oe))throw new Error(`bad point coordinate ${He}`);return oe}function Oe(He){if(!(He instanceof Be))throw new Error("ProjectivePoint expected")}function De(He){if(!G||!G.basises)throw new Error("no endo");return c(He,G.basises,B.ORDER)}const ut=(0,r.memoized)((He,oe)=>{const{X:ne,Y:re,Z:k}=He;if(x.eql(k,x.ONE))return{x:ne,y:re};const p=He.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}}),bt=(0,r.memoized)(He=>{if(He.is0()){if($.allowInfinityPoint&&!x.is0(He.Y))return;throw new Error("bad point: ZERO")}const{x:oe,y:ne}=He.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(!He.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Ot(He,oe,ne,re,k){return ne=new Be(x.mul(ne.X,He),ne.Y,ne.Z),oe=(0,i.negateCt)(re,oe),ne=(0,i.negateCt)(k,ne),oe.add(ne)}class Be{constructor(oe,ne,re){this.X=he("x",oe),this.Y=he("y",ne,!0),this.Z=he("z",re),Object.freeze(this)}static CURVE(){return L}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 Be)throw new Error("projective point not allowed");return x.is0(ne)&&x.is0(re)?Be.ZERO:new Be(ne,re,x.ONE)}static fromBytes(oe){const ne=Be.fromAffine(Z((0,r._abytes2)(oe,void 0,"point")));return ne.assertValidity(),ne}static fromHex(oe){return Be.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(){bt(this)}hasEvenY(){const{y:oe}=this.toAffine();if(!x.isOdd)throw new Error("Field doesn't support isOdd");return!x.isOdd(oe)}equals(oe){Oe(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)),U=x.eql(x.mul(re,b),x.mul(h,k));return I&&U}negate(){return new Be(this.X,x.neg(this.Y),this.Z)}double(){const{a:oe,b:ne}=L,re=x.mul(ne,g),{X:k,Y:p,Z:h}=this;let b=x.ZERO,I=x.ZERO,U=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),U=x.mul(k,h),U=x.add(U,U),b=x.mul(oe,U),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),U=x.mul(re,U),ie=x.mul(oe,ie),Q=x.sub(j,ie),Q=x.mul(oe,Q),Q=x.add(Q,U),U=x.add(j,j),j=x.add(U,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),U=x.mul(ie,W),U=x.add(U,U),U=x.add(U,U),new Be(b,I,U)}add(oe){Oe(oe);const{X:ne,Y:re,Z:k}=this,{X:p,Y:h,Z:b}=oe;let I=x.ZERO,U=x.ZERO,j=x.ZERO;const W=L.a,ie=x.mul(L.b,g);let Q=x.mul(ne,p),fe=x.mul(re,h),le=x.mul(k,b),ke=x.add(ne,re),Re=x.add(p,h);ke=x.mul(ke,Re),Re=x.add(Q,fe),ke=x.sub(ke,Re),Re=x.add(ne,k);let nt=x.add(p,b);return Re=x.mul(Re,nt),nt=x.add(Q,le),Re=x.sub(Re,nt),nt=x.add(re,k),I=x.add(h,b),nt=x.mul(nt,I),I=x.add(fe,le),nt=x.sub(nt,I),j=x.mul(W,Re),I=x.mul(ie,le),j=x.add(I,j),I=x.sub(fe,j),j=x.add(fe,j),U=x.mul(I,j),fe=x.add(Q,Q),fe=x.add(fe,Q),le=x.mul(W,le),Re=x.mul(ie,Re),fe=x.add(fe,le),le=x.sub(Q,le),le=x.mul(W,le),Re=x.add(Re,le),Q=x.mul(fe,Re),U=x.add(U,Q),Q=x.mul(nt,Re),I=x.mul(ke,I),I=x.sub(I,Q),Q=x.mul(ke,fe),j=x.mul(nt,j),j=x.add(j,Q),new Be(I,U,j)}subtract(oe){return this.add(oe.negate())}is0(){return this.equals(Be.ZERO)}multiply(oe){const{endo:ne}=$;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)(Be,b));if(ne){const{k1neg:h,k1:b,k2neg:I,k2:U}=De(oe),{p:j,f:W}=p(b),{p:ie,f:Q}=p(U);k=W.add(Q),re=Ot(ne.beta,j,ie,h,I)}else{const{p:h,f:b}=p(oe);re=h,k=b}return(0,i.normalizeZ)(Be,[re,k])[0]}multiplyUnsafe(oe){const{endo:ne}=$,re=this;if(!B.isValid(oe))throw new Error("invalid scalar: out of range");if(oe===l||re.is0())return Be.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}=De(oe),{p1:I,p2:U}=(0,i.mulEndoUnsafe)(Be,re,p,b);return Ot(ne.beta,I,U,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 ut(this,oe)}isTorsionFree(){const{isTorsionFree:oe}=$;return N===d?!0:oe?oe(Be,this):it.unsafe(this,V).is0()}clearCofactor(){const{clearCofactor:oe}=$;return N===d?this:oe?oe(Be,this):this.multiplyUnsafe(N)}isSmallOrder(){return this.multiplyUnsafe(N).is0()}toBytes(oe=!0){return(0,r._abool2)(oe,"isCompressed"),this.assertValidity(),te(Be,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)(Be,oe)}static msm(oe,ne){return(0,i.pippenger)(Be,B,oe,ne)}static fromPrivateKey(oe){return Be.BASE.multiply(E(B,oe))}}Be.BASE=new Be(L.Gx,L.Gy,x.ONE),Be.ZERO=new Be(x.ZERO,x.ONE,x.ZERO),Be.Fp=x,Be.Fn=B;const gn=B.BITS,it=new i.wNAF(Be,$.endo?Math.ceil(gn/2):gn);return Be.BASE.precompute(8),Be}function _(P){return Uint8Array.of(P?2:3)}function w(P,$){const F=P.ORDER;let x=l;for(let Z=F-d;Z%y===l;Z/=y)x+=d;const B=x,L=y<<B-d-d,N=L*y,V=(F-d)/N,G=(V-d)/y,X=N-d,Y=L,ce=P.pow($,V),ue=P.pow($,(V+d)/y);let te=(Z,ae)=>{let we=ce,ge=P.pow(ae,X),J=P.sqr(ge);J=P.mul(J,ae);let he=P.mul(Z,J);he=P.pow(he,G),he=P.mul(he,ge),ge=P.mul(he,ae),J=P.mul(he,Z);let Oe=P.mul(J,ge);he=P.pow(Oe,Y);let De=P.eql(he,P.ONE);ge=P.mul(J,ue),he=P.mul(Oe,we),J=P.cmov(ge,J,De),Oe=P.cmov(he,Oe,De);for(let ut=B;ut>d;ut--){let bt=ut-y;bt=y<<bt-d;let Ot=P.pow(Oe,bt);const Be=P.eql(Ot,P.ONE);ge=P.mul(J,we),we=P.mul(we,we),Ot=P.mul(Oe,we),J=P.cmov(ge,J,Be),Oe=P.cmov(Ot,Oe,Be)}return{isValid:De,value:J}};if(P.ORDER%m===g){const Z=(P.ORDER-g)/m,ae=P.sqrt(P.neg($));te=(we,ge)=>{let J=P.sqr(ge);const he=P.mul(we,ge);J=P.mul(J,he);let Oe=P.pow(J,Z);Oe=P.mul(Oe,he);const De=P.mul(Oe,ae),ut=P.mul(P.sqr(Oe),ge),bt=P.eql(ut,we);let Ot=P.cmov(De,Oe,bt);return{isValid:bt,value:Ot}}}return te}function T(P,$){(0,s.validateField)(P);const{A:F,B:x,Z:B}=$;if(!P.isValid(F)||!P.isValid(x)||!P.isValid(B))throw new Error("mapToCurveSimpleSWU: invalid opts");const L=w(P,B);if(!P.isOdd)throw new Error("Field does not have .isOdd()");return N=>{let V,G,X,Y,ce,ue,te,Z;V=P.sqr(N),V=P.mul(V,B),G=P.sqr(V),G=P.add(G,V),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(V,X);const{isValid:ae,value:we}=L(G,ue);Z=P.mul(V,N),Z=P.mul(Z,we),te=P.cmov(te,X,ae),Z=P.cmov(Z,we,ae);const ge=P.isOdd(N)===P.isOdd(Z);Z=P.cmov(P.neg(Z),Z,ge);const J=(0,s.FpInvertBatch)(P,[Y],!0)[0];return te=P.mul(te,J),{x:te,y:Z}}}function O(P,$){return{secretKey:$.BYTES,publicKey:1+P.BYTES,publicKeyUncompressed:1+2*P.BYTES,publicKeyHasPrefix:!0,signature:2*$.BYTES}}function A(P,$={}){const{Fn:F}=P,x=$.randomBytes||r.randomBytes,B=Object.assign(O(P.Fp,F),{seed:(0,s.getMinHashLength)(F.ORDER)});function L(te){try{return!!E(F,te)}catch{return!1}}function N(te,Z){const{publicKey:ae,publicKeyUncompressed:we}=B;try{const ge=te.length;return Z===!0&&ge!==ae||Z===!1&&ge!==we?!1:!!P.fromBytes(te)}catch{return!1}}function V(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=V(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 ge=(0,r.ensureBytes)("key",te).length;return ge===ae||ge===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:L,isValidPublicKey:N,randomSecretKey:V,isValidPrivateKey:L,randomPrivateKey:V,normPrivateKeyToScalar:te=>E(F,te),precompute(te=8,Z=P.BASE){return Z.precompute(te,!1)}},lengths:B})}function R(P,$,F={}){(0,n.ahash)($),(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)($,ne,(0,r.concatBytes)(...re))),{Fp:L,Fn:N}=P,{ORDER:V,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=V>>d;return ne>re}function ge(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 he{constructor(re,k,p){this.r=ge("r",re),this.s=ge("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:U,s:j}=e.DER.toSig((0,r._abytes2)(re));return new he(U,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 he(N.fromBytes(b),N.fromBytes(I),p)}static fromHex(re,k){return this.fromBytes((0,r.hexToBytes)(re),k)}addRecoveryBit(re){return new he(this.r,this.s,re)}recoverPublicKey(re){const k=L.ORDER,{r:p,s:h,recovery:b}=this;if(b==null||![0,1,2,3].includes(b))throw new Error("recovery id invalid");if(V*y<k&&b>1)throw new Error("recovery id is ambiguous for h>1 curve");const U=b===2||b===3?p+V:p;if(!L.isValid(U))throw new Error("recovery id 2 or 3 invalid");const j=L.toBytes(U),W=P.fromBytes((0,r.concatBytes)(_((b&1)===0),j)),ie=N.inv(U),Q=De((0,r.ensureBytes)("msgHash",re)),fe=N.create(-Q*ie),le=N.create(h*ie),ke=P.BASE.multiplyUnsafe(fe).add(W.multiplyUnsafe(le));if(ke.is0())throw new Error("point at infinify");return ke.assertValidity(),ke}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 he.fromBytes((0,r.ensureBytes)("sig",re),"compact")}static fromDER(re){return he.fromBytes((0,r.ensureBytes)("sig",re),"der")}normalizeS(){return this.hasHighS()?new he(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 Oe=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},De=F.bits2int_modN||function(re){return N.create(Oe(re))},ut=(0,r.bitMask)(G);function bt(ne){return(0,r.aInRange)("num < 2^"+G,ne,l,ut),N.toBytes(ne)}function Ot(ne,re){return(0,r._abytes2)(ne,void 0,"message"),re?(0,r._abytes2)($(ne),void 0,"prehashed message"):ne}function Be(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=Ot(ne,h);const I=De(ne),U=E(N,re),j=[bt(U),bt(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 le=Oe(fe);if(!N.isValidNot0(le))return;const ke=N.inv(le),Re=P.BASE.multiply(le).toAffine(),nt=N.create(Re.x);if(nt===l)return;const Ke=N.create(ke*N.create(ie+nt*U));if(Ke===l)return;let Xn=(Re.x===nt?0:2)|Number(Re.y&d),Uh=Ke;return p&&we(Ke)&&(Uh=N.neg(Ke),Xn^=1),new he(nt,Uh,Xn)}return{seed:W,k2sig:Q}}function gn(ne,re,k={}){ne=(0,r.ensureBytes)("message",ne);const{seed:p,k2sig:h}=Be(ne,re,k);return(0,r.createHmacDrbg)($.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 he(ne.r,ne.s);else if(k){try{re=he.fromBytes((0,r.ensureBytes)("sig",ne),"der")}catch(h){if(!(h instanceof e.DER.Err))throw h}if(!re)try{re=he.fromBytes((0,r.ensureBytes)("sig",ne),"compact")}catch{return!1}}return re||!1}function He(ne,re,k,p={}){const{lowS:h,prehash:b,format:I}=u(p,Z);if(k=(0,r.ensureBytes)("publicKey",k),re=Ot((0,r.ensureBytes)("message",re),b),"strict"in p)throw new Error("options.strict was renamed to lowS");const U=I===void 0?it(ne):he.fromBytes((0,r.ensureBytes)("sig",ne),I);if(U===!1)return!1;try{const j=P.fromBytes(k);if(h&&U.hasHighS())return!1;const{r:W,s:ie}=U,Q=De(re),fe=N.inv(ie),le=N.create(Q*fe),ke=N.create(W*fe),Re=P.BASE.multiplyUnsafe(le).add(j.multiplyUnsafe(ke));return Re.is0()?!1:N.create(Re.x)===W}catch{return!1}}function oe(ne,re,k={}){const{prehash:p}=u(k,Z);return re=Ot(re,p),he.fromBytes(ne,"recovered").recoverPublicKey(re).toBytes()}return Object.freeze({keygen:X,getPublicKey:Y,getSharedSecret:ce,utils:ue,lengths:te,Point:P,sign:gn,verify:He,recoverPublicKey:oe,Signature:he,hash:$})}function M(P){const{CURVE:$,curveOpts:F}=v(P),x=S($,F);return K(P,x)}function v(P){const $={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)($.n,{BITS:P.nBitLength,allowedLengths:x,modFromBytes:P.wrapPrivateKey}),L={Fp:F,Fn:B,allowInfinityPoint:P.allowInfinityPoint,endo:P.endo,isTorsionFree:P.isTorsionFree,clearCofactor:P.clearCofactor,fromBytes:P.fromBytes,toBytes:P.toBytes};return{CURVE:$,curveOpts:L}}function C(P){const{CURVE:$,curveOpts:F}=v(P),x={hmac:P.hmac,randomBytes:P.randomBytes,lowS:P.lowS,bits2int:P.bits2int,bits2int_modN:P.bits2int_modN};return{CURVE:$,curveOpts:F,hash:P.hash,ecdsaOpts:x}}function q(P,$,F){function x(B){const L=P.sqr(B),N=P.mul(L,B);return P.add(P.add(N,P.mul(B,$)),F)}return x}function K(P,$){const{Fp:F,Fn:x}=$;function B(N){return(0,r.inRange)(N,d,x.ORDER)}const L=q(F,P.a,P.b);return Object.assign({},{CURVE:P,Point:$,ProjectivePoint:$,normPrivateKeyToScalar:N=>E(x,N),weierstrassEquation:L,isWithinCurveOrder:B})}function H(P,$){const F=$.Point;return Object.assign({},$,{ProjectivePoint:F,CURVE:Object.assign({},P,(0,s.nLength)(F.Fn.ORDER,F.Fn.BITS))})}function D(P){const{CURVE:$,curveOpts:F,hash:x,ecdsaOpts:B}=C(P),L=S($,F),N=R(L,x,B);return H(P,N)}})(Nu)),Nu}var Qh;function q1(){if(Qh)return Ys;Qh=1,Object.defineProperty(Ys,"__esModule",{value:!0}),Ys.getHash=t,Ys.createCurve=n;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const e=Ry();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 Ys}var Ru={},ed;function V1(){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=Fs(),n=tc(),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:S,blockLen:_}=E,w=Math.ceil(m/S);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,_),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 C=1;C<=w;C++){const q=[s(M,R[C-1]),i(C+1,1),T];R[C]=E((0,t.concatBytes)(...q))}return(0,t.concatBytes)(...R).slice(0,m)}function u(y,g,m,E,S){if((0,t.abytes)(y),o(m),g=c(g),g.length>255){const _=Math.ceil(2*E/8);g=S.create({dkLen:_}).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 S.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:S,m:_,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+S)/8),M=g*_*R;let v;if(T==="xmd")v=a(y,O,M,w);else if(T==="xof")v=u(y,O,M,S,w);else if(T==="_internal_pass")v=y;else throw new Error('expand must be "xmd" or "xof"');const C=new Array(g);for(let q=0;q<g;q++){const K=new Array(_);for(let H=0;H<_;H++){const D=R*(H+q*_),P=v.subarray(D,D+R);K[H]=(0,n.mod)(r(P),E)}C[q]=K}return C}function l(y,g){const m=g.map(E=>Array.from(E).reverse());return(E,S)=>{const[_,w,T,O]=m.map(M=>M.reduce((v,C)=>y.add(y.mul(v,E),C))),[A,R]=(0,n.FpInvertBatch)(y,[w,O],!0);return E=y.mul(_,A),S=y.mul(S,y.mul(T,R)),{x:E,y:S}}}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(_){return y.fromAffine(g(_))}function S(_){const w=_.clearCofactor();return w.equals(y.ZERO)?y.ZERO:(w.assertValidity(),w)}return{defaults:m,hashToCurve(_,w){const T=Object.assign({},m,w),O=f(_,2,T),A=E(O[0]),R=E(O[1]);return S(A.add(R))},encodeToCurve(_,w){const T=m.encodeDST?{DST:m.encodeDST}:{},O=Object.assign({},m,T,w),A=f(_,1,O),R=E(A[0]);return S(R)},mapToCurve(_){if(!Array.isArray(_))throw new Error("expected array of bigints");for(const w of _)if(typeof w!="bigint")throw new Error("expected array of bigints");return S(E(_))},hashToScalar(_,w){const T=y.Fn.ORDER,O=Object.assign({},m,{p:T,m:1,DST:e._DST_scalar},w);return f(_,1,O)[0][0]}}}})(Ru)),Ru}var td;function D1(){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=Py(),n=ai(),r=q1(),i=V1(),s=tc(),o=Ry(),c=Fs(),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 D=a.p,P=BigInt(3),$=BigInt(6),F=BigInt(11),x=BigInt(22),B=BigInt(23),L=BigInt(44),N=BigInt(88),V=H*H*H%D,G=V*V*H%D,X=(0,s.pow2)(G,P,D)*G%D,Y=(0,s.pow2)(X,P,D)*G%D,ce=(0,s.pow2)(Y,d,D)*V%D,ue=(0,s.pow2)(ce,F,D)*ce%D,te=(0,s.pow2)(ue,x,D)*ue%D,Z=(0,s.pow2)(te,L,D)*te%D,ae=(0,s.pow2)(Z,N,D)*Z%D,we=(0,s.pow2)(ae,L,D)*te%D,ge=(0,s.pow2)(we,P,D)*G%D,J=(0,s.pow2)(ge,B,D)*ue%D,he=(0,s.pow2)(J,$,D)*V%D,Oe=(0,s.pow2)(he,d,D);if(!g.eql(g.sqr(Oe),H))throw new Error("Cannot find square root");return Oe}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,...D){let P=m[H];if(P===void 0){const $=(0,t.sha256)((0,c.utf8ToBytes)(H));P=(0,c.concatBytes)($,$),m[H]=P}return(0,t.sha256)((0,c.concatBytes)(P,...D))}const S=H=>H.toBytes(!0).slice(1),_=e.secp256k1.Point,w=H=>H%d===f;function T(H){const{Fn:D,BASE:P}=_,$=(0,o._normFnElement)(D,H),F=P.multiply($);return{scalar:w(F.y)?$:D.neg($),bytes:S(F)}}function O(H){const D=g;if(!D.isValidNot0(H))throw new Error("invalid x: Fail if x ≥ p");const P=D.create(H*H),$=D.create(P*H+BigInt(7));let F=D.sqrt($);w(F)||(F=D.neg(F));const x=_.fromAffine({x:H,y:F});return x.assertValidity(),x}const A=c.bytesToNumberBE;function R(...H){return _.Fn.create(A(E("BIP0340/challenge",...H)))}function M(H){return T(H).bytes}function v(H,D,P=(0,n.randomBytes)(32)){const{Fn:$}=_,F=(0,c.ensureBytes)("message",H),{bytes:x,scalar:B}=T(D),L=(0,c.ensureBytes)("auxRand",P,32),N=$.toBytes(B^A(E("BIP0340/aux",L))),V=E("BIP0340/nonce",N,x,F),{bytes:G,scalar:X}=T(V),Y=R(G,x,F),ce=new Uint8Array(64);if(ce.set(G,0),ce.set($.toBytes($.create(X+Y*B)),32),!C(ce,F,x))throw new Error("sign: Invalid signature produced");return ce}function C(H,D,P){const{Fn:$,BASE:F}=_,x=(0,c.ensureBytes)("signature",H,64),B=(0,c.ensureBytes)("message",D),L=(0,c.ensureBytes)("publicKey",P,32);try{const N=O(A(L)),V=A(x.subarray(0,32));if(!(0,c.inRange)(V,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($.toBytes(V),S(N),B),Y=F.multiplyUnsafe(G).add(N.multiplyUnsafe($.neg(X))),{x:ce,y:ue}=Y.toAffine();return!(Y.is0()||!w(ue)||ce!==V)}catch{return!1}}e.schnorr=(()=>{const P=(F=(0,n.randomBytes)(48))=>(0,s.mapHashToField)(F,a.n);e.secp256k1.utils.randomSecretKey;function $(F){const x=P(F);return{secretKey:x,publicKey:M(x)}}return{keygen:$,getPublicKey:M,sign:v,verify:C,Point:_,utils:{randomSecretKey:P,randomPrivateKey:P,taggedHash:E,lift_x:O,pointToBytes:S,numberToBytesBE:c.numberToBytesBE,bytesToNumberBE:c.bytesToNumberBE,mod:s.mod},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();const q=(0,i.isogenyMap)(g,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(H=>H.map(D=>BigInt(D)))),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:D,y:P}=K(g.create(H[0]));return q(D,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 $1(){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=Fs();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 j1(){if(rd)return st;rd=1;var e=D1(),t=tc(),n=$1();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,S=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]),_=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,S)>=0)}function C(p){return p instanceof Uint8Array&&p.length===64&&R(p.subarray(0,32),S)<0&&R(p.subarray(32,64),S)<0}function q(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 D(p){return p===void 0||p instanceof Uint8Array&&p.length===_}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 $(p){return e.secp256k1.utils.normPrivateKeyToScalar(p)}function F(p,h){const b=$(p),I=P(h),U=s.numberToBytesBE(i.mod(b+I,e.secp256k1.CURVE.n),32);return e.secp256k1.utils.isValidPrivateKey(U)?U:null}function x(p,h){const b=$(p),I=P(h),U=s.numberToBytesBE(i.mod(b-I,e.secp256k1.CURVE.n),32);return e.secp256k1.utils.isValidPrivateKey(U)?U:null}function B(p){const h=$(p),b=s.numberToBytesBE(e.secp256k1.CURVE.n-h,32);return e.secp256k1.utils.isValidPrivateKey(b)?b:null}function L(p,h,b){const I=Y(p),U=P(h),j=o.BASE.multiplyAndAddUnsafe(I,U,O);if(!j)throw new Error("Tweaked point at infinity");return j.toRawBytes(b)}function N(p,h,b){const I=Y(p),U=typeof h=="string"?h:s.bytesToHex(h),j=s.hexToNumber(U);return I.multiply(j).toRawBytes(b)}function V(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=L(p,h,!0);return{parity:b[0]%2===1?1:0,xOnlyPubkey:b.slice(1)}})}function ge(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,V(h)))}function he(p){if(!Z(p))throw new Error(c);return ge(J(p))}function Oe(p,h){if(!ue(p))throw new Error(a);return Y(p).toRawBytes(V(h,p))}function De(p,h,b){if(!ue(p))throw new Error(a);if(!v(h))throw new Error(u);return G(()=>N(p,h,V(b,p)))}function ut(p,h,b){if(!ue(p)||!ue(h))throw new Error(a);return G(()=>{const I=Y(p),U=Y(h);return I.equals(U.negate())?null:I.add(U).toRawBytes(V(b,p))})}function bt(p,h,b){if(!ue(p))throw new Error(a);if(!v(h))throw new Error(u);return G(()=>L(p,h,V(b,p)))}function Ot(p,h){if(!Z(p))throw new Error(c);if(!v(h))throw new Error(u);return G(()=>F(p,h))}function Be(p,h){if(!Z(p))throw new Error(c);if(!v(h))throw new Error(u);return G(()=>x(p,h))}function gn(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(!D(b))throw new Error(d);return e.secp256k1.sign(p,h,{extraEntropy:b}).toCompactRawBytes()}function He(p,h,b){if(!Z(h))throw new Error(c);if(!H(p))throw new Error(y);if(!D(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(!D(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(!C(h)||!K(h))throw new Error(l);if(b&2&&!q(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(V(I))}function re(p,h,b,I){if(!ue(h))throw new Error(a);if(!C(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(!C(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=ut,st.pointAddScalar=bt,st.pointCompress=Oe,st.pointFromScalar=J,st.pointMultiply=De,st.privateAdd=Ot,st.privateNegate=gn,st.privateSub=Be,st.recover=ne,st.sign=it,st.signRecoverable=He,st.signSchnorr=oe,st.verify=re,st.verifySchnorr=k,st.xOnlyPointAddTweak=we,st.xOnlyPointFromPoint=ge,st.xOnlyPointFromScalar=he,st}var Cy=j1();const K1=Ny(Cy),G1=B1({__proto__:null,default:K1},[Cy]),Pn={messagePrefix:`Bitcoin Signed Message:
6
+ */var Vh;function ec(){return Vh||(Vh=1,(function(e){const t=N1(),n=k1(),r=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=c,e.SlowBuffer=_,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:S(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:S(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=S(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"||He(k.length)?o(0):y(k);if(k.type==="Buffer"&&Array.isArray(k.data))return y(k.data)}function S(k){if(k>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return k|0}function _(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 U=0,j=Math.min(b,I);U<j;++U)if(p[U]!==h[U]){b=p[U],I=h[U];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 U=0;for(b=0;b<p.length;++b){let j=p[b];if(it(j,Uint8Array))U+j.length>I.length?(c.isBuffer(j)||(j=c.from(j)),j.copy(I,U)):Uint8Array.prototype.set.call(I,j,U);else if(c.isBuffer(j))j.copy(I,U);else throw new TypeError('"list" argument must be an Array of Buffers');U+=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 ut(k).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return h*2;case"hex":return h>>>1;case"base64":return Be(k).length;default:if(I)return b?-1:ut(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 D(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 L(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?D(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,U){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),U===void 0&&(U=this.length),h<0||b>p.length||I<0||U>this.length)throw new RangeError("out of range index");if(I>=U&&h>=b)return 0;if(I>=U)return-1;if(h>=b)return 1;if(h>>>=0,b>>>=0,I>>>=0,U>>>=0,this===p)return 0;let j=U-I,W=b-h;const ie=Math.min(j,W),Q=this.slice(I,U),fe=p.slice(h,b);for(let le=0;le<ie;++le)if(Q[le]!==fe[le]){j=Q[le],W=fe[le];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,He(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 U=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;U=2,j/=2,W/=2,h/=2}function ie(fe,le){return U===1?fe[le]:fe.readUInt16BE(le*U)}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*U}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 le=0;le<W;le++)if(ie(k,Q+le)!==ie(p,le)){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 U=p.length;b>U/2&&(b=U/2);let j;for(j=0;j<b;++j){const W=parseInt(p.substr(j*2,2),16);if(He(W))return j;k[h+j]=W}return j}function v(k,p,h,b){return gn(ut(p,k.length-h),k,h,b)}function C(k,p,h,b){return gn(bt(p),k,h,b)}function q(k,p,h,b){return gn(Be(p),k,h,b)}function K(k,p,h,b){return gn(Ot(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 U=this.length-h;if((b===void 0||b>U)&&(b=U),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 C(this,p,h,b);case"base64":return q(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 D(k,p,h){h=Math.min(k.length,h);const b=[];let I=p;for(;I<h;){const U=k[I];let j=null,W=U>239?4:U>223?3:U>191?2:1;if(I+W<=h){let ie,Q,fe,le;switch(W){case 1:U<128&&(j=U);break;case 2:ie=k[I+1],(ie&192)===128&&(le=(U&31)<<6|ie&63,le>127&&(j=le));break;case 3:ie=k[I+1],Q=k[I+2],(ie&192)===128&&(Q&192)===128&&(le=(U&15)<<12|(ie&63)<<6|Q&63,le>2047&&(le<55296||le>57343)&&(j=le));break;case 4:ie=k[I+1],Q=k[I+2],fe=k[I+3],(ie&192)===128&&(Q&192)===128&&(fe&192)===128&&(le=(U&15)<<18|(ie&63)<<12|(Q&63)<<6|fe&63,le>65535&&le<1114112&&(j=le))}}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 $(b)}const P=4096;function $(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 U=p;U<h;++U)I+=oe[k[U]];return I}function L(k,p,h){const b=k.slice(p,h);let I="";for(let U=0;U<b.length-1;U+=2)I+=String.fromCharCode(b[U]+b[U+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],U=1,j=0;for(;++j<h&&(U*=256);)I+=this[p+j]*U;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],U=1;for(;h>0&&(U*=256);)I+=this[p+--h]*U;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)&&he(p,this.length-8);const I=h+this[++p]*2**8+this[++p]*2**16+this[++p]*2**24,U=this[++p]+this[++p]*2**8+this[++p]*2**16+b*2**24;return BigInt(I)+(BigInt(U)<<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)&&he(p,this.length-8);const I=h*2**24+this[++p]*2**16+this[++p]*2**8+this[++p],U=this[++p]*2**24+this[++p]*2**16+this[++p]*2**8+b;return(BigInt(I)<<BigInt(32))+BigInt(U)}),c.prototype.readIntLE=function(p,h,b){p=p>>>0,h=h>>>0,b||N(p,h,this.length);let I=this[p],U=1,j=0;for(;++j<h&&(U*=256);)I+=this[p+j]*U;return U*=128,I>=U&&(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,U=1,j=this[p+--I];for(;I>0&&(U*=256);)j+=this[p+--I]*U;return U*=128,j>=U&&(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)&&he(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)&&he(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 V(k,p,h,b,I,U){if(!c.isBuffer(k))throw new TypeError('"buffer" argument must be a Buffer instance');if(p>I||p<U)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;V(this,p,h,b,W,0)}let U=1,j=0;for(this[h]=p&255;++j<b&&(U*=256);)this[h+j]=p/U&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;V(this,p,h,b,W,0)}let U=b-1,j=1;for(this[h+U]=p&255;--U>=0&&(j*=256);)this[h+U]=p/j&255;return h+b},c.prototype.writeUint8=c.prototype.writeUInt8=function(p,h,b){return p=+p,h=h>>>0,b||V(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||V(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||V(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||V(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||V(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){ge(p,b,I,k,h,7);let U=Number(p&BigInt(4294967295));k[h++]=U,U=U>>8,k[h++]=U,U=U>>8,k[h++]=U,U=U>>8,k[h++]=U;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){ge(p,b,I,k,h,7);let U=Number(p&BigInt(4294967295));k[h+7]=U,U=U>>8,k[h+6]=U,U=U>>8,k[h+5]=U,U=U>>8,k[h+4]=U;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);V(this,p,h,b,ie-1,-ie)}let U=0,j=1,W=0;for(this[h]=p&255;++U<b&&(j*=256);)p<0&&W===0&&this[h+U-1]!==0&&(W=1),this[h+U]=(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);V(this,p,h,b,ie-1,-ie)}let U=b-1,j=1,W=0;for(this[h+U]=p&255;--U>=0&&(j*=256);)p<0&&W===0&&this[h+U+1]!==0&&(W=1),this[h+U]=(p/j>>0)-W&255;return h+b},c.prototype.writeInt8=function(p,h,b){return p=+p,h=h>>>0,b||V(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||V(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||V(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||V(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||V(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,U){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 U=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),U},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 U;if(typeof p=="number")for(U=h;U<b;++U)this[U]=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(U=0;U<b-h;++U)this[U+h]=j[U%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)&&he(p,k.length-(h+1))}function ge(k,p,h,b,I,U){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} ** ${(U+1)*8}${j}`:W=`>= -(2${j} ** ${(U+1)*8-1}${j}) and < 2 ** ${(U+1)*8-1}${j}`,new te.ERR_OUT_OF_RANGE("value",W,k)}we(b,I,U)}function J(k,p){if(typeof k!="number")throw new te.ERR_INVALID_ARG_TYPE(p,"number",k)}function he(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 Oe=/[^+/0-9A-Za-z-_]/g;function De(k){if(k=k.split("=")[0],k=k.trim().replace(Oe,""),k.length<2)return"";for(;k.length%4!==0;)k=k+"=";return k}function ut(k,p){p=p||1/0;let h;const b=k.length;let I=null;const U=[];for(let j=0;j<b;++j){if(h=k.charCodeAt(j),h>55295&&h<57344){if(!I){if(h>56319){(p-=3)>-1&&U.push(239,191,189);continue}else if(j+1===b){(p-=3)>-1&&U.push(239,191,189);continue}I=h;continue}if(h<56320){(p-=3)>-1&&U.push(239,191,189),I=h;continue}h=(I-55296<<10|h-56320)+65536}else I&&(p-=3)>-1&&U.push(239,191,189);if(I=null,h<128){if((p-=1)<0)break;U.push(h)}else if(h<2048){if((p-=2)<0)break;U.push(h>>6|192,h&63|128)}else if(h<65536){if((p-=3)<0)break;U.push(h>>12|224,h>>6&63|128,h&63|128)}else if(h<1114112){if((p-=4)<0)break;U.push(h>>18|240,h>>12&63|128,h>>6&63|128,h&63|128)}else throw new Error("Invalid code point")}return U}function bt(k){const p=[];for(let h=0;h<k.length;++h)p.push(k.charCodeAt(h)&255);return p}function Ot(k,p){let h,b,I;const U=[];for(let j=0;j<k.length&&!((p-=2)<0);++j)h=k.charCodeAt(j),b=h>>8,I=h%256,U.push(I),U.push(b);return U}function Be(k){return t.toByteArray(De(k))}function gn(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 He(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 P1=ec(),Iu={exports:{}},Dh;function R1(){if(Dh)return Iu.exports;Dh=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 S=1;S<arguments.length;S++)E[S-1]=arguments[S];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 C1=R1();const U1=Ny(C1);typeof globalThis>"u"&&(globalThis.global=globalThis);typeof globalThis.Buffer>"u"&&(globalThis.Buffer=P1.Buffer);typeof globalThis.process>"u"&&(globalThis.process=U1);var st={},Ou={},Xe={},qt={},Bu={},Ys={},$h;function H1(){return $h||($h=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 ai(){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=_,e.hexToBytes=O,e.asyncLoop=R,e.utf8ToBytes=M,e.bytesToUtf8=v,e.toBytes=C,e.kdfInputToBytes=q,e.concatBytes=K,e.checkOpts=H,e.createHasher=P,e.createOptHasher=$,e.createXOFer=F,e.randomBytes=x;const t=H1();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,...L){if(!n(B))throw new Error("Uint8Array expected");if(L.length>0&&!L.includes(B.length))throw new Error("Uint8Array expected of length "+L+", 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,L=!0){if(B.destroyed)throw new Error("Hash instance has been destroyed");if(L&&B.finished)throw new Error("Hash#digest() has already been called")}function c(B,L){i(B);const N=L.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 L=0;L<B.length;L++)B[L].fill(0)}function l(B){return new DataView(B.buffer,B.byteOffset,B.byteLength)}function d(B,L){return B<<32-L|B>>>L}function y(B,L){return B<<L|B>>>32-L>>>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 L=0;L<B.length;L++)B[L]=g(B[L]);return B}e.swap32IfBE=e.isLE?B=>B:m;const E=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",S=Array.from({length:256},(B,L)=>L.toString(16).padStart(2,"0"));function _(B){if(i(B),E)return B.toHex();let L="";for(let N=0;N<B.length;N++)L+=S[B[N]];return L}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 L=B.length,N=L/2;if(L%2)throw new Error("hex string expected, got unpadded hex of length "+L);const V=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)}V[G]=Y*16+ce}return V}const A=async()=>{};e.nextTick=A;async function R(B,L,N){let V=Date.now();for(let G=0;G<B;G++){N(G);const X=Date.now()-V;X>=0&&X<L||(await(0,e.nextTick)(),V+=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 C(B){return typeof B=="string"&&(B=M(B)),i(B),B}function q(B){return typeof B=="string"&&(B=M(B)),i(B),B}function K(...B){let L=0;for(let V=0;V<B.length;V++){const G=B[V];i(G),L+=G.length}const N=new Uint8Array(L);for(let V=0,G=0;V<B.length;V++){const X=B[V];N.set(X,G),G+=X.length}return N}function H(B,L){if(L!==void 0&&{}.toString.call(L)!=="[object Object]")throw new Error("options should be object or undefined");return Object.assign(B,L)}class D{}e.Hash=D;function P(B){const L=V=>B().update(C(V)).digest(),N=B();return L.outputLen=N.outputLen,L.blockLen=N.blockLen,L.create=()=>B(),L}function $(B){const L=(V,G)=>B(G).update(C(V)).digest(),N=B({});return L.outputLen=N.outputLen,L.blockLen=N.blockLen,L.create=V=>B(V),L}function F(B){const L=(V,G)=>B(G).update(C(V)).digest(),N=B({});return L.outputLen=N.outputLen,L.blockLen=N.blockLen,L.create=V=>B(V),L}e.wrapConstructor=P,e.wrapConstructorWithOpts=$,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 ky(){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=ai();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 F1(){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=S,Ie.fromBig=n,Ie.split=r;const e=BigInt(2**32-1),t=BigInt(32);function n(v,C=!1){return C?{h:Number(v&e),l:Number(v>>t&e)}:{h:Number(v>>t&e)|0,l:Number(v&e)|0}}function r(v,C=!1){const q=v.length;let K=new Uint32Array(q),H=new Uint32Array(q);for(let D=0;D<q;D++){const{h:P,l:$}=n(v[D],C);[K[D],H[D]]=[P,$]}return[K,H]}const i=(v,C)=>BigInt(v>>>0)<<t|BigInt(C>>>0);Ie.toBig=i;const s=(v,C,q)=>v>>>q;Ie.shrSH=s;const o=(v,C,q)=>v<<32-q|C>>>q;Ie.shrSL=o;const c=(v,C,q)=>v>>>q|C<<32-q;Ie.rotrSH=c;const a=(v,C,q)=>v<<32-q|C>>>q;Ie.rotrSL=a;const u=(v,C,q)=>v<<64-q|C>>>q-32;Ie.rotrBH=u;const f=(v,C,q)=>v>>>q-32|C<<64-q;Ie.rotrBL=f;const l=(v,C)=>C;Ie.rotr32H=l;const d=(v,C)=>v;Ie.rotr32L=d;const y=(v,C,q)=>v<<q|C>>>32-q;Ie.rotlSH=y;const g=(v,C,q)=>C<<q|v>>>32-q;Ie.rotlSL=g;const m=(v,C,q)=>C<<q-32|v>>>64-q;Ie.rotlBH=m;const E=(v,C,q)=>v<<q-32|C>>>64-q;Ie.rotlBL=E;function S(v,C,q,K){const H=(C>>>0)+(K>>>0);return{h:v+q+(H/2**32|0)|0,l:H|0}}const _=(v,C,q)=>(v>>>0)+(C>>>0)+(q>>>0);Ie.add3L=_;const w=(v,C,q,K)=>C+q+K+(v/2**32|0)|0;Ie.add3H=w;const T=(v,C,q,K)=>(v>>>0)+(C>>>0)+(q>>>0)+(K>>>0);Ie.add4L=T;const O=(v,C,q,K,H)=>C+q+K+H+(v/2**32|0)|0;Ie.add4H=O;const A=(v,C,q,K,H)=>(v>>>0)+(C>>>0)+(q>>>0)+(K>>>0)+(H>>>0);Ie.add5L=A;const R=(v,C,q,K,H,D)=>C+q+K+H+D+(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:S,add3L:_,add3H:w,add4L:T,add4H:O,add5H:R,add5L:A};return Ie.default=M,Ie}var Wh;function Py(){if(Wh)return Xe;Wh=1,Object.defineProperty(Xe,"__esModule",{value:!0}),Xe.sha512_224=Xe.sha512_256=Xe.sha384=Xe.sha512=Xe.sha224=Xe.sha256=Xe.SHA512_256=Xe.SHA512_224=Xe.SHA384=Xe.SHA512=Xe.SHA224=Xe.SHA256=void 0;const e=ky(),t=F1(),n=ai(),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:C}=this;return[w,T,O,A,R,M,v,C]}set(w,T,O,A,R,M,v,C){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=C|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 D=i[H-15],P=i[H-2],$=(0,n.rotr)(D,7)^(0,n.rotr)(D,18)^D>>>3,F=(0,n.rotr)(P,17)^(0,n.rotr)(P,19)^P>>>10;i[H]=F+i[H-7]+$+i[H-16]|0}let{A:O,B:A,C:R,D:M,E:v,F:C,G:q,H:K}=this;for(let H=0;H<64;H++){const D=(0,n.rotr)(v,6)^(0,n.rotr)(v,11)^(0,n.rotr)(v,25),P=K+D+(0,e.Chi)(v,C,q)+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=q,q=C,C=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,C=C+this.F|0,q=q+this.G|0,K=K+this.H|0,this.set(O,A,R,M,v,C,q,K)}roundClean(){(0,n.clean)(i)}destroy(){this.set(0,0,0,0,0,0,0,0),(0,n.clean)(this.buffer)}}Xe.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}}Xe.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(_=>BigInt(_))),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:C,Eh:q,El:K,Fh:H,Fl:D,Gh:P,Gl:$,Hh:F,Hl:x}=this;return[w,T,O,A,R,M,v,C,q,K,H,D,P,$,F,x]}set(w,T,O,A,R,M,v,C,q,K,H,D,P,$,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=C|0,this.Eh=q|0,this.El=K|0,this.Fh=H|0,this.Fl=D|0,this.Gh=P|0,this.Gl=$|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 V=f[N-15]|0,G=l[N-15]|0,X=t.rotrSH(V,G,1)^t.rotrSH(V,G,8)^t.shrSH(V,G,7),Y=t.rotrSL(V,G,1)^t.rotrSL(V,G,8)^t.shrSL(V,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:C,Dh:q,Dl:K,Eh:H,El:D,Fh:P,Fl:$,Gh:F,Gl:x,Hh:B,Hl:L}=this;for(let N=0;N<80;N++){const V=t.rotrSH(H,D,14)^t.rotrSH(H,D,18)^t.rotrBH(H,D,41),G=t.rotrSL(H,D,14)^t.rotrSL(H,D,18)^t.rotrBL(H,D,41),X=H&P^~H&F,Y=D&$^~D&x,ce=t.add5L(L,G,Y,u[N],l[N]),ue=t.add5H(ce,B,V,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,ge=A&M^A&C^M&C;B=F|0,L=x|0,F=P|0,x=$|0,P=H|0,$=D|0,{h:H,l:D}=t.add(q|0,K|0,ue|0,te|0),q=v|0,K=C|0,v=R|0,C=M|0,R=O|0,M=A|0;const J=t.add3L(te,ae,ge);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:C}=t.add(this.Ch|0,this.Cl|0,v|0,C|0),{h:q,l:K}=t.add(this.Dh|0,this.Dl|0,q|0,K|0),{h:H,l:D}=t.add(this.Eh|0,this.El|0,H|0,D|0),{h:P,l:$}=t.add(this.Fh|0,this.Fl|0,P|0,$|0),{h:F,l:x}=t.add(this.Gh|0,this.Gl|0,F|0,x|0),{h:B,l:L}=t.add(this.Hh|0,this.Hl|0,B|0,L|0),this.set(O,A,R,M,v,C,q,K,H,D,P,$,F,x,B,L)}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)}}Xe.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}}Xe.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}}Xe.SHA512_224=E;class S 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 Xe.SHA512_256=S,Xe.sha256=(0,n.createHasher)(()=>new s),Xe.sha224=(0,n.createHasher)(()=>new o),Xe.sha512=(0,n.createHasher)(()=>new d),Xe.sha384=(0,n.createHasher)(()=>new y),Xe.sha512_256=(0,n.createHasher)(()=>new S),Xe.sha512_224=(0,n.createHasher)(()=>new E),Xe}var Zs={},Nu={},ku={},Xh;function M1(){return Xh||(Xh=1,(function(e){Object.defineProperty(e,"__esModule",{value:!0}),e.hmac=e.HMAC=void 0;const t=ai();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=S,e.asciiToBytes=_,e.inRange=T,e.aInRange=O,e.bitLen=A,e.bitGet=R,e.bitSet=M,e.createHmacDrbg=C,e.validateObject=K,e.isHash=H,e._validateObject=D,e.memoized=$;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=ai();var n=ai();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 L=(0,t.isBytes)(F),N=F?.length,V=x!==void 0;if(!L||V&&N!==x){const G=B&&`"${B}" `,X=V?` of length ${x}`:"",Y=L?`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 L;if(typeof x=="string")try{L=(0,t.hexToBytes)(x)}catch(V){throw new Error(F+" must be hex string or Uint8Array, cause: "+V)}else if((0,t.isBytes)(x))L=Uint8Array.from(x);else throw new Error(F+" must be hex string or Uint8Array");const N=L.length;if(typeof B=="number"&&N!==B)throw new Error(F+" of length "+B+" expected, got "+N);return L}function E(F,x){if(F.length!==x.length)return!1;let B=0;for(let L=0;L<F.length;L++)B|=F[L]^x[L];return B===0}function S(F){return Uint8Array.from(F)}function _(F){return Uint8Array.from(F,(x,B)=>{const L=x.charCodeAt(0);if(x.length!==1||L>127)throw new Error(`string contains non-ASCII character "${F[B]}" with code ${L} at position ${B}`);return L})}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,L){if(!T(x,B,L))throw new Error("expected valid "+F+": "+B+" <= n < "+L+", 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 C(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 L=ae=>new Uint8Array(ae),N=ae=>Uint8Array.of(ae);let V=L(F),G=L(F),X=0;const Y=()=>{V.fill(1),G.fill(0),X=0},ce=(...ae)=>B(G,V,...ae),ue=(ae=L(0))=>{G=ce(N(0),ae),V=ce(),ae.length!==0&&(G=ce(N(1),ae),V=ce())},te=()=>{if(X++>=1e3)throw new Error("drbg: tried 1000 values");let ae=0;const we=[];for(;ae<x;){V=ce();const ge=V.slice();we.push(ge),ae+=V.length}return(0,t.concatBytes)(...we)};return(ae,we)=>{Y(),ue(ae);let ge;for(;!(ge=we(te()));)ue();return Y(),ge}}const q={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 L=(N,V,G)=>{const X=q[V];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 "+V+", got "+Y)};for(const[N,V]of Object.entries(x))L(N,V,!1);for(const[N,V]of Object.entries(B))L(N,V,!0);return F}function H(F){return typeof F=="function"&&Number.isSafeInteger(F.outputLen)}function D(F,x,B={}){if(!F||typeof F!="object")throw new Error("expected valid options object");function L(N,V,G){const X=F[N];if(G&&X===void 0)return;const Y=typeof X;if(Y!==V||X===null)throw new Error(`param "${N}" is invalid: expected ${V}, got ${Y}`)}Object.entries(x).forEach(([N,V])=>L(N,V,!1)),Object.entries(B).forEach(([N,V])=>L(N,V,!0))}const P=()=>{throw new Error("not implemented")};e.notImplemented=P;function $(F){const x=new WeakMap;return(B,...L)=>{const N=x.get(B);if(N!==void 0)return N;const V=F(B,...L);return x.set(B,V),V}}})(Pu)),Pu}var Sn={},Qe={},Yh;function tc(){if(Yh)return Qe;Yh=1,Object.defineProperty(Qe,"__esModule",{value:!0}),Qe.isNegativeLE=void 0,Qe.mod=l,Qe.pow=d,Qe.pow2=y,Qe.invert=g,Qe.tonelliShanks=w,Qe.FpSqrt=T,Qe.validateField=R,Qe.FpPow=M,Qe.FpInvertBatch=v,Qe.FpDiv=C,Qe.FpLegendre=q,Qe.FpIsSquare=K,Qe.nLength=H,Qe.Field=D,Qe.FpSqrtOdd=P,Qe.FpSqrtEven=$,Qe.hashToPrivateScalar=F,Qe.getFieldBytesLength=x,Qe.getMinHashLength=B,Qe.mapHashToField=L;/*! 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,V){const G=N%V;return G>=t?G:V+G}function d(N,V,G){return M(D(G),N,V)}function y(N,V,G){let X=N;for(;V-- >t;)X*=X,X%=G;return X}function g(N,V){if(N===t)throw new Error("invert: expected non-zero number");if(V<=t)throw new Error("invert: expected positive modulus, got "+V);let G=l(N,V),X=V,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,V)}function m(N,V,G){if(!N.eql(N.sqr(V),G))throw new Error("Cannot find square root")}function E(N,V){const G=(N.ORDER+n)/s,X=N.pow(V,G);return m(N,X,V),X}function S(N,V){const G=(N.ORDER-o)/a,X=N.mul(V,r),Y=N.pow(X,G),ce=N.mul(V,Y),ue=N.mul(N.mul(ce,r),Y),te=N.mul(ce,N.sub(ue,N.ONE));return m(N,te,V),te}function _(N){const V=D(N),G=w(N),X=G(V,V.neg(V.ONE)),Y=G(V,X),ce=G(V,V.neg(X)),ue=(N+c)/f;return(te,Z)=>{let ae=te.pow(Z,ue),we=te.mul(ae,X);const ge=te.mul(ae,Y),J=te.mul(ae,ce),he=te.eql(te.sqr(we),Z),Oe=te.eql(te.sqr(ge),Z);ae=te.cmov(ae,we,he),we=te.cmov(J,ge,Oe);const De=te.eql(te.sqr(we),Z),ut=te.cmov(ae,we,De);return m(te,ut,Z),ut}}function w(N){if(N<i)throw new Error("sqrt is not defined for small field");let V=N-n,G=0;for(;V%r===t;)V/=r,G++;let X=r;const Y=D(N);for(;q(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,V);const ue=(V+n)/r;return function(Z,ae){if(Z.is0(ae))return ae;if(q(Z,ae)!==1)throw new Error("Cannot find square root");let we=G,ge=Z.mul(Z.ONE,ce),J=Z.pow(ae,V),he=Z.pow(ae,ue);for(;!Z.eql(J,Z.ONE);){if(Z.is0(J))return Z.ZERO;let Oe=1,De=Z.sqr(J);for(;!Z.eql(De,Z.ONE);)if(Oe++,De=Z.sqr(De),Oe===we)throw new Error("Cannot find square root");const ut=n<<BigInt(we-Oe-1),bt=Z.pow(ge,ut);we=Oe,ge=Z.sqr(bt),J=Z.mul(J,ge),he=Z.mul(he,bt)}return he}}function T(N){return N%s===i?E:N%a===o?S:N%f===u?_(N):w(N)}const O=(N,V)=>(l(N,V)&n)===n;Qe.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 V={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},G=A.reduce((X,Y)=>(X[Y]="function",X),V);return(0,e._validateObject)(N,G),N}function M(N,V,G){if(G<t)throw new Error("invalid exponent, negatives unsupported");if(G===t)return N.ONE;if(G===n)return V;let X=N.ONE,Y=V;for(;G>t;)G&n&&(X=N.mul(X,Y)),Y=N.sqr(Y),G>>=n;return X}function v(N,V,G=!1){const X=new Array(V.length).fill(G?N.ZERO:void 0),Y=V.reduce((ue,te,Z)=>N.is0(te)?ue:(X[Z]=ue,N.mul(ue,te)),N.ONE),ce=N.inv(Y);return V.reduceRight((ue,te,Z)=>N.is0(te)?ue:(X[Z]=N.mul(ue,X[Z]),N.mul(ue,te)),ce),X}function C(N,V,G){return N.mul(V,typeof G=="bigint"?g(G,N.ORDER):N.inv(G))}function q(N,V){const G=(N.ORDER-n)/r,X=N.pow(V,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,V){return q(N,V)===1}function H(N,V){V!==void 0&&(0,e.anumber)(V);const G=V!==void 0?V:N.toString(2).length,X=Math.ceil(G/8);return{nBitLength:G,nByteLength:X}}function D(N,V,G=!1,X={}){if(N<=t)throw new Error("invalid field: expected ORDER > 0, got "+N);let Y,ce,ue=!1,te;if(typeof V=="object"&&V!=null){if(X.sqrt||G)throw new Error("cannot specify opts in two arguments");const J=V;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 V=="number"&&(Y=V),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 ge=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=>!ge.is0(J)&&ge.isValid(J),isOdd:J=>(J&n)===n,neg:J=>l(-J,N),eql:(J,he)=>J===he,sqr:J=>l(J*J,N),add:(J,he)=>l(J+he,N),sub:(J,he)=>l(J-he,N),mul:(J,he)=>l(J*he,N),pow:(J,he)=>M(ge,J,he),div:(J,he)=>l(J*g(he,N),N),sqrN:J=>J*J,addN:(J,he)=>J+he,subN:(J,he)=>J-he,mulN:(J,he)=>J*he,inv:J=>g(J,N),sqrt:ce||(J=>(we||(we=T(N)),we(ge,J))),toBytes:J=>G?(0,e.numberToBytesLE)(J,ae):(0,e.numberToBytesBE)(J,ae),fromBytes:(J,he=!0)=>{if(te){if(!te.includes(J.length)||J.length>ae)throw new Error("Field.fromBytes: expected "+te+" bytes, got "+J.length);const De=new Uint8Array(ae);De.set(J,G?0:De.length-J.length),J=De}if(J.length!==ae)throw new Error("Field.fromBytes: expected "+ae+" bytes, got "+J.length);let Oe=G?(0,e.bytesToNumberLE)(J):(0,e.bytesToNumberBE)(J);if(ue&&(Oe=l(Oe,N)),!he&&!ge.isValid(Oe))throw new Error("invalid field element: outside of range 0..ORDER");return Oe},invertBatch:J=>v(ge,J),cmov:(J,he,Oe)=>Oe?he:J});return Object.freeze(ge)}function P(N,V){if(!N.isOdd)throw new Error("Field doesn't have isOdd");const G=N.sqrt(V);return N.isOdd(G)?G:N.neg(G)}function $(N,V){if(!N.isOdd)throw new Error("Field doesn't have isOdd");const G=N.sqrt(V);return N.isOdd(G)?N.neg(G):G}function F(N,V,G=!1){N=(0,e.ensureBytes)("privateHash",N);const X=N.length,Y=H(V).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,V-n)+n}function x(N){if(typeof N!="bigint")throw new Error("field order must be bigint");const V=N.toString(2).length;return Math.ceil(V/8)}function B(N){const V=x(N);return V+Math.ceil(V/2)}function L(N,V,G=!1){const X=N.length,Y=x(V),ce=B(V);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,V-n)+n;return G?(0,e.numberToBytesLE)(te,Y):(0,e.numberToBytesBE)(te,Y)}return Qe}var Zh;function L1(){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=S,Sn.precomputeMSMUnsafe=_,Sn.validateBasic=w,Sn._createCurveFields=O;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const e=Ms(),t=tc(),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,C)=>A.fromAffine(v.toAffine(M[C])))}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),C=2**A,q=(0,e.bitMask)(A),K=BigInt(A);return{windows:M,windowSize:v,mask:q,maxNumber:C,shiftBy:K}}function a(A,R,M){const{windowSize:v,mask:C,maxNumber:q,shiftBy:K}=M;let H=Number(A&C),D=A>>K;H>v&&(H-=q,D+=r);const P=R*v,$=P+Math.abs(H)-1,F=H===0,x=H<0,B=R%2!==0;return{nextN:D,offset:$,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 C=R;for(;M>n;)M&r&&(v=v.add(C)),C=C.double(),M>>=r;return v}precomputeWindow(R,M){const{windows:v,windowSize:C}=c(M,this.bits),q=[];let K=R,H=K;for(let D=0;D<v;D++){H=K,q.push(H);for(let P=1;P<C;P++)H=H.add(K),q.push(H);K=H.double()}return q}wNAF(R,M,v){if(!this.Fn.isValid(v))throw new Error("invalid scalar");let C=this.ZERO,q=this.BASE;const K=c(R,this.bits);for(let H=0;H<K.windows;H++){const{nextN:D,offset:P,isZero:$,isNeg:F,isNegF:x,offsetF:B}=a(v,H,K);v=D,$?q=q.add(i(x,M[B])):C=C.add(i(F,M[P]))}return g(v),{p:C,f:q}}wNAFUnsafe(R,M,v,C=this.ZERO){const q=c(R,this.bits);for(let K=0;K<q.windows&&v!==n;K++){const{nextN:H,offset:D,isZero:P,isNeg:$}=a(v,K,q);if(v=H,!P){const F=M[D];C=C.add($?F.negate():F)}}return g(v),C}getPrecomputes(R,M,v){let C=l.get(M);return C||(C=this.precomputeWindow(M,R),R!==1&&(typeof v=="function"&&(C=v(C)),l.set(M,C))),C}cached(R,M,v){const C=y(R);return this.wNAF(C,this.getPrecomputes(C,R,v),M)}unsafe(R,M,v,C){const q=y(R);return q===1?this._unsafeLadder(R,M,C):this.wNAFUnsafe(q,this.getPrecomputes(q,R,v),M,C)}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 C=R,q=A.ZERO,K=A.ZERO;for(;M>n||v>n;)M&r&&(q=q.add(C)),v&r&&(K=K.add(C)),C=C.double(),M>>=r,v>>=r;return{p1:q,p2:K}}function S(A,R,M,v){u(M,A),f(v,R);const C=M.length,q=v.length;if(C!==q)throw new Error("arrays of points and scalars must have equal length");const K=A.ZERO,H=(0,e.bitLen)(BigInt(C));let D=1;H>12?D=H-3:H>4?D=H-2:H>0&&(D=2);const P=(0,e.bitMask)(D),$=new Array(Number(P)+1).fill(K),F=Math.floor((R.BITS-1)/D)*D;let x=K;for(let B=F;B>=0;B-=D){$.fill(K);for(let N=0;N<q;N++){const V=v[N],G=Number(V>>BigInt(B)&P);$[G]=$[G].add(M[N])}let L=K;for(let N=$.length-1,V=K;N>0;N--)V=V.add($[N]),L=L.add(V);if(x=x.add(L),B!==0)for(let N=0;N<D;N++)x=x.double()}return x}function _(A,R,M,v){o(v,R.BITS),u(M,A);const C=A.ZERO,q=2**v-1,K=Math.ceil(R.BITS/v),H=(0,e.bitMask)(v),D=M.map(P=>{const $=[];for(let F=0,x=P;F<q;F++)$.push(x),x=x.add(P);return $});return P=>{if(f(P,R),P.length>M.length)throw new Error("array of scalars must be smaller than array of points");let $=C;for(let F=0;F<K;F++){if($!==C)for(let B=0;B<v;B++)$=$.double();const x=BigInt(K*v-(F+1)*v);for(let B=0;B<P.length;B++){const L=P[B],N=Number(L>>x&H);N&&($=$.add(D[B][N-1]))}}return $}}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 D of["p","n","h"]){const P=R[D];if(!(typeof P=="bigint"&&P>n))throw new Error(`CURVE.${D} must be positive bigint`)}const C=T(R.p,M.Fp,v),q=T(R.n,M.Fn,v),H=["Gx","Gy","a",A==="weierstrass"?"b":"d"];for(const D of H)if(!C.isValid(R[D]))throw new Error(`CURVE.${D} must be valid field element of CURVE.Fp`);return R=Object.freeze(Object.assign({},R)),{CURVE:R,Fp:C,Fn:q}}return Sn}var Jh;function Ry(){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=S,e.SWUFpSqrtRatio=w,e.mapToCurveSimpleSWU=T,e.ecdh=A,e.ecdsa=R,e.weierstrassPoints=M,e._legacyHelperEquat=q,e.weierstrass=D;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t=M1(),n=ai(),r=Ms(),i=L1(),s=tc(),o=(P,$)=>(P+(P>=0?$:-$)/y)/$;function c(P,$,F){const[[x,B],[L,N]]=$,V=o(N*P,F),G=o(-B*P,F);let X=P-V*x-G*L,Y=-V*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,$){const F={};for(let x of Object.keys($))F[x]=P[x]===void 0?$[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($=""){super($)}}e.DERErr=f,e.DER={Err:f,_tlv:{encode:(P,$)=>{const{Err:F}=e.DER;if(P<0||P>256)throw new F("tlv.encode: wrong tag");if($.length&1)throw new F("tlv.encode: unpadded data");const x=$.length/2,B=(0,r.numberToHexUnpadded)(x);if(B.length/2&128)throw new F("tlv.encode: long form length too big");const L=x>127?(0,r.numberToHexUnpadded)(B.length/2|128):"";return(0,r.numberToHexUnpadded)(P)+L+B+$},decode(P,$){const{Err:F}=e.DER;let x=0;if(P<0||P>256)throw new F("tlv.encode: wrong tag");if($.length<2||$[x++]!==P)throw new F("tlv.decode: wrong tlv");const B=$[x++],L=!!(B&128);let N=0;if(!L)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=$.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 V=$.subarray(x,x+N);if(V.length!==N)throw new F("tlv.decode: wrong value length");return{v:V,l:$.subarray(x+N)}}},_int:{encode(P){const{Err:$}=e.DER;if(P<l)throw new $("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 $("unexpected DER parsing assertion: unpadded hex");return F},decode(P){const{Err:$}=e.DER;if(P[0]&128)throw new $("invalid signature integer: negative");if(P[0]===0&&!(P[1]&128))throw new $("invalid signature integer: unnecessary leading zero");return(0,r.bytesToNumberBE)(P)}},toSig(P){const{Err:$,_int:F,_tlv:x}=e.DER,B=(0,r.ensureBytes)("signature",P),{v:L,l:N}=x.decode(48,B);if(N.length)throw new $("invalid signature: left bytes after parsing");const{v:V,l:G}=x.decode(2,L),{v:X,l:Y}=x.decode(2,G);if(Y.length)throw new $("invalid signature: left bytes after parsing");return{r:F.decode(V),s:F.decode(X)}},hexFromSig(P){const{_tlv:$,_int:F}=e.DER,x=$.encode(2,F.encode(P.r)),B=$.encode(2,F.encode(P.s)),L=x+B;return $.encode(48,L)}};const l=BigInt(0),d=BigInt(1),y=BigInt(2),g=BigInt(3),m=BigInt(4);function E(P,$){const{BYTES:F}=P;let x;if(typeof $=="bigint")x=$;else{let B=(0,r.ensureBytes)("private key",$);try{x=P.fromBytes(B)}catch{throw new Error(`invalid private key: expected ui8a of size ${F}, got ${typeof $}`)}}if(!P.isValidNot0(x))throw new Error("invalid private key: out of range [1..N-1]");return x}function S(P,$={}){const F=(0,i._createCurveFields)("weierstrass",P,$),{Fp:x,Fn:B}=F;let L=F.CURVE;const{h:N,n:V}=L;(0,r._validateObject)($,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:G}=$;if(G&&(!x.is0(L.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(He,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)(_(h),p)}else return(0,r.concatBytes)(Uint8Array.of(4),p,x.toBytes(k))}function ue(He){(0,r._abytes2)(He,void 0,"Point");const{publicKey:oe,publicKeyUncompressed:ne}=X,re=He.length,k=He[0],p=He.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 U=x.isOdd(I);return(k&1)===1!==U&&(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=$.toBytes||ce,Z=$.fromBytes||ue;function ae(He){const oe=x.sqr(He),ne=x.mul(oe,He);return x.add(x.add(ne,x.mul(He,L.a)),L.b)}function we(He,oe){const ne=x.sqr(oe),re=ae(He);return x.eql(ne,re)}if(!we(L.Gx,L.Gy))throw new Error("bad curve params: generator point");const ge=x.mul(x.pow(L.a,g),m),J=x.mul(x.sqr(L.b),BigInt(27));if(x.is0(x.add(ge,J)))throw new Error("bad curve params: a or b");function he(He,oe,ne=!1){if(!x.isValid(oe)||ne&&x.is0(oe))throw new Error(`bad point coordinate ${He}`);return oe}function Oe(He){if(!(He instanceof Be))throw new Error("ProjectivePoint expected")}function De(He){if(!G||!G.basises)throw new Error("no endo");return c(He,G.basises,B.ORDER)}const ut=(0,r.memoized)((He,oe)=>{const{X:ne,Y:re,Z:k}=He;if(x.eql(k,x.ONE))return{x:ne,y:re};const p=He.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}}),bt=(0,r.memoized)(He=>{if(He.is0()){if($.allowInfinityPoint&&!x.is0(He.Y))return;throw new Error("bad point: ZERO")}const{x:oe,y:ne}=He.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(!He.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function Ot(He,oe,ne,re,k){return ne=new Be(x.mul(ne.X,He),ne.Y,ne.Z),oe=(0,i.negateCt)(re,oe),ne=(0,i.negateCt)(k,ne),oe.add(ne)}class Be{constructor(oe,ne,re){this.X=he("x",oe),this.Y=he("y",ne,!0),this.Z=he("z",re),Object.freeze(this)}static CURVE(){return L}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 Be)throw new Error("projective point not allowed");return x.is0(ne)&&x.is0(re)?Be.ZERO:new Be(ne,re,x.ONE)}static fromBytes(oe){const ne=Be.fromAffine(Z((0,r._abytes2)(oe,void 0,"point")));return ne.assertValidity(),ne}static fromHex(oe){return Be.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(){bt(this)}hasEvenY(){const{y:oe}=this.toAffine();if(!x.isOdd)throw new Error("Field doesn't support isOdd");return!x.isOdd(oe)}equals(oe){Oe(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)),U=x.eql(x.mul(re,b),x.mul(h,k));return I&&U}negate(){return new Be(this.X,x.neg(this.Y),this.Z)}double(){const{a:oe,b:ne}=L,re=x.mul(ne,g),{X:k,Y:p,Z:h}=this;let b=x.ZERO,I=x.ZERO,U=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),U=x.mul(k,h),U=x.add(U,U),b=x.mul(oe,U),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),U=x.mul(re,U),ie=x.mul(oe,ie),Q=x.sub(j,ie),Q=x.mul(oe,Q),Q=x.add(Q,U),U=x.add(j,j),j=x.add(U,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),U=x.mul(ie,W),U=x.add(U,U),U=x.add(U,U),new Be(b,I,U)}add(oe){Oe(oe);const{X:ne,Y:re,Z:k}=this,{X:p,Y:h,Z:b}=oe;let I=x.ZERO,U=x.ZERO,j=x.ZERO;const W=L.a,ie=x.mul(L.b,g);let Q=x.mul(ne,p),fe=x.mul(re,h),le=x.mul(k,b),ke=x.add(ne,re),Re=x.add(p,h);ke=x.mul(ke,Re),Re=x.add(Q,fe),ke=x.sub(ke,Re),Re=x.add(ne,k);let nt=x.add(p,b);return Re=x.mul(Re,nt),nt=x.add(Q,le),Re=x.sub(Re,nt),nt=x.add(re,k),I=x.add(h,b),nt=x.mul(nt,I),I=x.add(fe,le),nt=x.sub(nt,I),j=x.mul(W,Re),I=x.mul(ie,le),j=x.add(I,j),I=x.sub(fe,j),j=x.add(fe,j),U=x.mul(I,j),fe=x.add(Q,Q),fe=x.add(fe,Q),le=x.mul(W,le),Re=x.mul(ie,Re),fe=x.add(fe,le),le=x.sub(Q,le),le=x.mul(W,le),Re=x.add(Re,le),Q=x.mul(fe,Re),U=x.add(U,Q),Q=x.mul(nt,Re),I=x.mul(ke,I),I=x.sub(I,Q),Q=x.mul(ke,fe),j=x.mul(nt,j),j=x.add(j,Q),new Be(I,U,j)}subtract(oe){return this.add(oe.negate())}is0(){return this.equals(Be.ZERO)}multiply(oe){const{endo:ne}=$;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)(Be,b));if(ne){const{k1neg:h,k1:b,k2neg:I,k2:U}=De(oe),{p:j,f:W}=p(b),{p:ie,f:Q}=p(U);k=W.add(Q),re=Ot(ne.beta,j,ie,h,I)}else{const{p:h,f:b}=p(oe);re=h,k=b}return(0,i.normalizeZ)(Be,[re,k])[0]}multiplyUnsafe(oe){const{endo:ne}=$,re=this;if(!B.isValid(oe))throw new Error("invalid scalar: out of range");if(oe===l||re.is0())return Be.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}=De(oe),{p1:I,p2:U}=(0,i.mulEndoUnsafe)(Be,re,p,b);return Ot(ne.beta,I,U,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 ut(this,oe)}isTorsionFree(){const{isTorsionFree:oe}=$;return N===d?!0:oe?oe(Be,this):it.unsafe(this,V).is0()}clearCofactor(){const{clearCofactor:oe}=$;return N===d?this:oe?oe(Be,this):this.multiplyUnsafe(N)}isSmallOrder(){return this.multiplyUnsafe(N).is0()}toBytes(oe=!0){return(0,r._abool2)(oe,"isCompressed"),this.assertValidity(),te(Be,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)(Be,oe)}static msm(oe,ne){return(0,i.pippenger)(Be,B,oe,ne)}static fromPrivateKey(oe){return Be.BASE.multiply(E(B,oe))}}Be.BASE=new Be(L.Gx,L.Gy,x.ONE),Be.ZERO=new Be(x.ZERO,x.ONE,x.ZERO),Be.Fp=x,Be.Fn=B;const gn=B.BITS,it=new i.wNAF(Be,$.endo?Math.ceil(gn/2):gn);return Be.BASE.precompute(8),Be}function _(P){return Uint8Array.of(P?2:3)}function w(P,$){const F=P.ORDER;let x=l;for(let Z=F-d;Z%y===l;Z/=y)x+=d;const B=x,L=y<<B-d-d,N=L*y,V=(F-d)/N,G=(V-d)/y,X=N-d,Y=L,ce=P.pow($,V),ue=P.pow($,(V+d)/y);let te=(Z,ae)=>{let we=ce,ge=P.pow(ae,X),J=P.sqr(ge);J=P.mul(J,ae);let he=P.mul(Z,J);he=P.pow(he,G),he=P.mul(he,ge),ge=P.mul(he,ae),J=P.mul(he,Z);let Oe=P.mul(J,ge);he=P.pow(Oe,Y);let De=P.eql(he,P.ONE);ge=P.mul(J,ue),he=P.mul(Oe,we),J=P.cmov(ge,J,De),Oe=P.cmov(he,Oe,De);for(let ut=B;ut>d;ut--){let bt=ut-y;bt=y<<bt-d;let Ot=P.pow(Oe,bt);const Be=P.eql(Ot,P.ONE);ge=P.mul(J,we),we=P.mul(we,we),Ot=P.mul(Oe,we),J=P.cmov(ge,J,Be),Oe=P.cmov(Ot,Oe,Be)}return{isValid:De,value:J}};if(P.ORDER%m===g){const Z=(P.ORDER-g)/m,ae=P.sqrt(P.neg($));te=(we,ge)=>{let J=P.sqr(ge);const he=P.mul(we,ge);J=P.mul(J,he);let Oe=P.pow(J,Z);Oe=P.mul(Oe,he);const De=P.mul(Oe,ae),ut=P.mul(P.sqr(Oe),ge),bt=P.eql(ut,we);let Ot=P.cmov(De,Oe,bt);return{isValid:bt,value:Ot}}}return te}function T(P,$){(0,s.validateField)(P);const{A:F,B:x,Z:B}=$;if(!P.isValid(F)||!P.isValid(x)||!P.isValid(B))throw new Error("mapToCurveSimpleSWU: invalid opts");const L=w(P,B);if(!P.isOdd)throw new Error("Field does not have .isOdd()");return N=>{let V,G,X,Y,ce,ue,te,Z;V=P.sqr(N),V=P.mul(V,B),G=P.sqr(V),G=P.add(G,V),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(V,X);const{isValid:ae,value:we}=L(G,ue);Z=P.mul(V,N),Z=P.mul(Z,we),te=P.cmov(te,X,ae),Z=P.cmov(Z,we,ae);const ge=P.isOdd(N)===P.isOdd(Z);Z=P.cmov(P.neg(Z),Z,ge);const J=(0,s.FpInvertBatch)(P,[Y],!0)[0];return te=P.mul(te,J),{x:te,y:Z}}}function O(P,$){return{secretKey:$.BYTES,publicKey:1+P.BYTES,publicKeyUncompressed:1+2*P.BYTES,publicKeyHasPrefix:!0,signature:2*$.BYTES}}function A(P,$={}){const{Fn:F}=P,x=$.randomBytes||r.randomBytes,B=Object.assign(O(P.Fp,F),{seed:(0,s.getMinHashLength)(F.ORDER)});function L(te){try{return!!E(F,te)}catch{return!1}}function N(te,Z){const{publicKey:ae,publicKeyUncompressed:we}=B;try{const ge=te.length;return Z===!0&&ge!==ae||Z===!1&&ge!==we?!1:!!P.fromBytes(te)}catch{return!1}}function V(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=V(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 ge=(0,r.ensureBytes)("key",te).length;return ge===ae||ge===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:L,isValidPublicKey:N,randomSecretKey:V,isValidPrivateKey:L,randomPrivateKey:V,normPrivateKeyToScalar:te=>E(F,te),precompute(te=8,Z=P.BASE){return Z.precompute(te,!1)}},lengths:B})}function R(P,$,F={}){(0,n.ahash)($),(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)($,ne,(0,r.concatBytes)(...re))),{Fp:L,Fn:N}=P,{ORDER:V,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=V>>d;return ne>re}function ge(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 he{constructor(re,k,p){this.r=ge("r",re),this.s=ge("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:U,s:j}=e.DER.toSig((0,r._abytes2)(re));return new he(U,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 he(N.fromBytes(b),N.fromBytes(I),p)}static fromHex(re,k){return this.fromBytes((0,r.hexToBytes)(re),k)}addRecoveryBit(re){return new he(this.r,this.s,re)}recoverPublicKey(re){const k=L.ORDER,{r:p,s:h,recovery:b}=this;if(b==null||![0,1,2,3].includes(b))throw new Error("recovery id invalid");if(V*y<k&&b>1)throw new Error("recovery id is ambiguous for h>1 curve");const U=b===2||b===3?p+V:p;if(!L.isValid(U))throw new Error("recovery id 2 or 3 invalid");const j=L.toBytes(U),W=P.fromBytes((0,r.concatBytes)(_((b&1)===0),j)),ie=N.inv(U),Q=De((0,r.ensureBytes)("msgHash",re)),fe=N.create(-Q*ie),le=N.create(h*ie),ke=P.BASE.multiplyUnsafe(fe).add(W.multiplyUnsafe(le));if(ke.is0())throw new Error("point at infinify");return ke.assertValidity(),ke}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 he.fromBytes((0,r.ensureBytes)("sig",re),"compact")}static fromDER(re){return he.fromBytes((0,r.ensureBytes)("sig",re),"der")}normalizeS(){return this.hasHighS()?new he(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 Oe=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},De=F.bits2int_modN||function(re){return N.create(Oe(re))},ut=(0,r.bitMask)(G);function bt(ne){return(0,r.aInRange)("num < 2^"+G,ne,l,ut),N.toBytes(ne)}function Ot(ne,re){return(0,r._abytes2)(ne,void 0,"message"),re?(0,r._abytes2)($(ne),void 0,"prehashed message"):ne}function Be(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=Ot(ne,h);const I=De(ne),U=E(N,re),j=[bt(U),bt(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 le=Oe(fe);if(!N.isValidNot0(le))return;const ke=N.inv(le),Re=P.BASE.multiply(le).toAffine(),nt=N.create(Re.x);if(nt===l)return;const Ke=N.create(ke*N.create(ie+nt*U));if(Ke===l)return;let Xn=(Re.x===nt?0:2)|Number(Re.y&d),Uh=Ke;return p&&we(Ke)&&(Uh=N.neg(Ke),Xn^=1),new he(nt,Uh,Xn)}return{seed:W,k2sig:Q}}function gn(ne,re,k={}){ne=(0,r.ensureBytes)("message",ne);const{seed:p,k2sig:h}=Be(ne,re,k);return(0,r.createHmacDrbg)($.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 he(ne.r,ne.s);else if(k){try{re=he.fromBytes((0,r.ensureBytes)("sig",ne),"der")}catch(h){if(!(h instanceof e.DER.Err))throw h}if(!re)try{re=he.fromBytes((0,r.ensureBytes)("sig",ne),"compact")}catch{return!1}}return re||!1}function He(ne,re,k,p={}){const{lowS:h,prehash:b,format:I}=u(p,Z);if(k=(0,r.ensureBytes)("publicKey",k),re=Ot((0,r.ensureBytes)("message",re),b),"strict"in p)throw new Error("options.strict was renamed to lowS");const U=I===void 0?it(ne):he.fromBytes((0,r.ensureBytes)("sig",ne),I);if(U===!1)return!1;try{const j=P.fromBytes(k);if(h&&U.hasHighS())return!1;const{r:W,s:ie}=U,Q=De(re),fe=N.inv(ie),le=N.create(Q*fe),ke=N.create(W*fe),Re=P.BASE.multiplyUnsafe(le).add(j.multiplyUnsafe(ke));return Re.is0()?!1:N.create(Re.x)===W}catch{return!1}}function oe(ne,re,k={}){const{prehash:p}=u(k,Z);return re=Ot(re,p),he.fromBytes(ne,"recovered").recoverPublicKey(re).toBytes()}return Object.freeze({keygen:X,getPublicKey:Y,getSharedSecret:ce,utils:ue,lengths:te,Point:P,sign:gn,verify:He,recoverPublicKey:oe,Signature:he,hash:$})}function M(P){const{CURVE:$,curveOpts:F}=v(P),x=S($,F);return K(P,x)}function v(P){const $={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)($.n,{BITS:P.nBitLength,allowedLengths:x,modFromBytes:P.wrapPrivateKey}),L={Fp:F,Fn:B,allowInfinityPoint:P.allowInfinityPoint,endo:P.endo,isTorsionFree:P.isTorsionFree,clearCofactor:P.clearCofactor,fromBytes:P.fromBytes,toBytes:P.toBytes};return{CURVE:$,curveOpts:L}}function C(P){const{CURVE:$,curveOpts:F}=v(P),x={hmac:P.hmac,randomBytes:P.randomBytes,lowS:P.lowS,bits2int:P.bits2int,bits2int_modN:P.bits2int_modN};return{CURVE:$,curveOpts:F,hash:P.hash,ecdsaOpts:x}}function q(P,$,F){function x(B){const L=P.sqr(B),N=P.mul(L,B);return P.add(P.add(N,P.mul(B,$)),F)}return x}function K(P,$){const{Fp:F,Fn:x}=$;function B(N){return(0,r.inRange)(N,d,x.ORDER)}const L=q(F,P.a,P.b);return Object.assign({},{CURVE:P,Point:$,ProjectivePoint:$,normPrivateKeyToScalar:N=>E(x,N),weierstrassEquation:L,isWithinCurveOrder:B})}function H(P,$){const F=$.Point;return Object.assign({},$,{ProjectivePoint:F,CURVE:Object.assign({},P,(0,s.nLength)(F.Fn.ORDER,F.Fn.BITS))})}function D(P){const{CURVE:$,curveOpts:F,hash:x,ecdsaOpts:B}=C(P),L=S($,F),N=R(L,x,B);return H(P,N)}})(Nu)),Nu}var Qh;function q1(){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=Ry();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 V1(){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=tc(),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:S,blockLen:_}=E,w=Math.ceil(m/S);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,_),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 C=1;C<=w;C++){const q=[s(M,R[C-1]),i(C+1,1),T];R[C]=E((0,t.concatBytes)(...q))}return(0,t.concatBytes)(...R).slice(0,m)}function u(y,g,m,E,S){if((0,t.abytes)(y),o(m),g=c(g),g.length>255){const _=Math.ceil(2*E/8);g=S.create({dkLen:_}).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 S.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:S,m:_,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+S)/8),M=g*_*R;let v;if(T==="xmd")v=a(y,O,M,w);else if(T==="xof")v=u(y,O,M,S,w);else if(T==="_internal_pass")v=y;else throw new Error('expand must be "xmd" or "xof"');const C=new Array(g);for(let q=0;q<g;q++){const K=new Array(_);for(let H=0;H<_;H++){const D=R*(H+q*_),P=v.subarray(D,D+R);K[H]=(0,n.mod)(r(P),E)}C[q]=K}return C}function l(y,g){const m=g.map(E=>Array.from(E).reverse());return(E,S)=>{const[_,w,T,O]=m.map(M=>M.reduce((v,C)=>y.add(y.mul(v,E),C))),[A,R]=(0,n.FpInvertBatch)(y,[w,O],!0);return E=y.mul(_,A),S=y.mul(S,y.mul(T,R)),{x:E,y:S}}}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(_){return y.fromAffine(g(_))}function S(_){const w=_.clearCofactor();return w.equals(y.ZERO)?y.ZERO:(w.assertValidity(),w)}return{defaults:m,hashToCurve(_,w){const T=Object.assign({},m,w),O=f(_,2,T),A=E(O[0]),R=E(O[1]);return S(A.add(R))},encodeToCurve(_,w){const T=m.encodeDST?{DST:m.encodeDST}:{},O=Object.assign({},m,T,w),A=f(_,1,O),R=E(A[0]);return S(R)},mapToCurve(_){if(!Array.isArray(_))throw new Error("expected array of bigints");for(const w of _)if(typeof w!="bigint")throw new Error("expected array of bigints");return S(E(_))},hashToScalar(_,w){const T=y.Fn.ORDER,O=Object.assign({},m,{p:T,m:1,DST:e._DST_scalar},w);return f(_,1,O)[0][0]}}}})(Ru)),Ru}var td;function D1(){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=Py(),n=ai(),r=q1(),i=V1(),s=tc(),o=Ry(),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 D=a.p,P=BigInt(3),$=BigInt(6),F=BigInt(11),x=BigInt(22),B=BigInt(23),L=BigInt(44),N=BigInt(88),V=H*H*H%D,G=V*V*H%D,X=(0,s.pow2)(G,P,D)*G%D,Y=(0,s.pow2)(X,P,D)*G%D,ce=(0,s.pow2)(Y,d,D)*V%D,ue=(0,s.pow2)(ce,F,D)*ce%D,te=(0,s.pow2)(ue,x,D)*ue%D,Z=(0,s.pow2)(te,L,D)*te%D,ae=(0,s.pow2)(Z,N,D)*Z%D,we=(0,s.pow2)(ae,L,D)*te%D,ge=(0,s.pow2)(we,P,D)*G%D,J=(0,s.pow2)(ge,B,D)*ue%D,he=(0,s.pow2)(J,$,D)*V%D,Oe=(0,s.pow2)(he,d,D);if(!g.eql(g.sqr(Oe),H))throw new Error("Cannot find square root");return Oe}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,...D){let P=m[H];if(P===void 0){const $=(0,t.sha256)((0,c.utf8ToBytes)(H));P=(0,c.concatBytes)($,$),m[H]=P}return(0,t.sha256)((0,c.concatBytes)(P,...D))}const S=H=>H.toBytes(!0).slice(1),_=e.secp256k1.Point,w=H=>H%d===f;function T(H){const{Fn:D,BASE:P}=_,$=(0,o._normFnElement)(D,H),F=P.multiply($);return{scalar:w(F.y)?$:D.neg($),bytes:S(F)}}function O(H){const D=g;if(!D.isValidNot0(H))throw new Error("invalid x: Fail if x ≥ p");const P=D.create(H*H),$=D.create(P*H+BigInt(7));let F=D.sqrt($);w(F)||(F=D.neg(F));const x=_.fromAffine({x:H,y:F});return x.assertValidity(),x}const A=c.bytesToNumberBE;function R(...H){return _.Fn.create(A(E("BIP0340/challenge",...H)))}function M(H){return T(H).bytes}function v(H,D,P=(0,n.randomBytes)(32)){const{Fn:$}=_,F=(0,c.ensureBytes)("message",H),{bytes:x,scalar:B}=T(D),L=(0,c.ensureBytes)("auxRand",P,32),N=$.toBytes(B^A(E("BIP0340/aux",L))),V=E("BIP0340/nonce",N,x,F),{bytes:G,scalar:X}=T(V),Y=R(G,x,F),ce=new Uint8Array(64);if(ce.set(G,0),ce.set($.toBytes($.create(X+Y*B)),32),!C(ce,F,x))throw new Error("sign: Invalid signature produced");return ce}function C(H,D,P){const{Fn:$,BASE:F}=_,x=(0,c.ensureBytes)("signature",H,64),B=(0,c.ensureBytes)("message",D),L=(0,c.ensureBytes)("publicKey",P,32);try{const N=O(A(L)),V=A(x.subarray(0,32));if(!(0,c.inRange)(V,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($.toBytes(V),S(N),B),Y=F.multiplyUnsafe(G).add(N.multiplyUnsafe($.neg(X))),{x:ce,y:ue}=Y.toAffine();return!(Y.is0()||!w(ue)||ce!==V)}catch{return!1}}e.schnorr=(()=>{const P=(F=(0,n.randomBytes)(48))=>(0,s.mapHashToField)(F,a.n);e.secp256k1.utils.randomSecretKey;function $(F){const x=P(F);return{secretKey:x,publicKey:M(x)}}return{keygen:$,getPublicKey:M,sign:v,verify:C,Point:_,utils:{randomSecretKey:P,randomPrivateKey:P,taggedHash:E,lift_x:O,pointToBytes:S,numberToBytesBE:c.numberToBytesBE,bytesToNumberBE:c.bytesToNumberBE,mod:s.mod},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:64,seed:48}}})();const q=(0,i.isogenyMap)(g,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(H=>H.map(D=>BigInt(D)))),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:D,y:P}=K(g.create(H[0]));return q(D,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 $1(){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 j1(){if(rd)return st;rd=1;var e=D1(),t=tc(),n=$1();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,S=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]),_=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,S)>=0)}function C(p){return p instanceof Uint8Array&&p.length===64&&R(p.subarray(0,32),S)<0&&R(p.subarray(32,64),S)<0}function q(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 D(p){return p===void 0||p instanceof Uint8Array&&p.length===_}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 $(p){return e.secp256k1.utils.normPrivateKeyToScalar(p)}function F(p,h){const b=$(p),I=P(h),U=s.numberToBytesBE(i.mod(b+I,e.secp256k1.CURVE.n),32);return e.secp256k1.utils.isValidPrivateKey(U)?U:null}function x(p,h){const b=$(p),I=P(h),U=s.numberToBytesBE(i.mod(b-I,e.secp256k1.CURVE.n),32);return e.secp256k1.utils.isValidPrivateKey(U)?U:null}function B(p){const h=$(p),b=s.numberToBytesBE(e.secp256k1.CURVE.n-h,32);return e.secp256k1.utils.isValidPrivateKey(b)?b:null}function L(p,h,b){const I=Y(p),U=P(h),j=o.BASE.multiplyAndAddUnsafe(I,U,O);if(!j)throw new Error("Tweaked point at infinity");return j.toRawBytes(b)}function N(p,h,b){const I=Y(p),U=typeof h=="string"?h:s.bytesToHex(h),j=s.hexToNumber(U);return I.multiply(j).toRawBytes(b)}function V(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=L(p,h,!0);return{parity:b[0]%2===1?1:0,xOnlyPubkey:b.slice(1)}})}function ge(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,V(h)))}function he(p){if(!Z(p))throw new Error(c);return ge(J(p))}function Oe(p,h){if(!ue(p))throw new Error(a);return Y(p).toRawBytes(V(h,p))}function De(p,h,b){if(!ue(p))throw new Error(a);if(!v(h))throw new Error(u);return G(()=>N(p,h,V(b,p)))}function ut(p,h,b){if(!ue(p)||!ue(h))throw new Error(a);return G(()=>{const I=Y(p),U=Y(h);return I.equals(U.negate())?null:I.add(U).toRawBytes(V(b,p))})}function bt(p,h,b){if(!ue(p))throw new Error(a);if(!v(h))throw new Error(u);return G(()=>L(p,h,V(b,p)))}function Ot(p,h){if(!Z(p))throw new Error(c);if(!v(h))throw new Error(u);return G(()=>F(p,h))}function Be(p,h){if(!Z(p))throw new Error(c);if(!v(h))throw new Error(u);return G(()=>x(p,h))}function gn(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(!D(b))throw new Error(d);return e.secp256k1.sign(p,h,{extraEntropy:b}).toCompactRawBytes()}function He(p,h,b){if(!Z(h))throw new Error(c);if(!H(p))throw new Error(y);if(!D(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(!D(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(!C(h)||!K(h))throw new Error(l);if(b&2&&!q(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(V(I))}function re(p,h,b,I){if(!ue(h))throw new Error(a);if(!C(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(!C(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=ut,st.pointAddScalar=bt,st.pointCompress=Oe,st.pointFromScalar=J,st.pointMultiply=De,st.privateAdd=Ot,st.privateNegate=gn,st.privateSub=Be,st.recover=ne,st.sign=it,st.signRecoverable=He,st.signSchnorr=oe,st.verify=re,st.verifySchnorr=k,st.xOnlyPointAddTweak=we,st.xOnlyPointFromPoint=ge,st.xOnlyPointFromScalar=he,st}var Cy=j1();const K1=Ny(Cy),G1=B1({__proto__:null,default:K1},[Cy]),Pn={messagePrefix:`Bitcoin Signed Message:
7
7
  `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},W1={messagePrefix:`Bitcoin Signed Message:
8
8
  `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},Uy={messagePrefix:`Bitcoin Signed Message:
9
- `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239};function X1(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 z1(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 Y1(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 We={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},Hy={};for(const e of Object.keys(We)){const t=We[e];Hy[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}),Fy=new TextEncoder,My=new TextDecoder;function Z1(e){return My.decode(e)}function J1(e){return Fy.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?eb(t):Q1(t)}function Q1(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 eb(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 My.decode(t)}function Pr(e){const t=Fy.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 tb(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 wn(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 nb(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 nc(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 rb(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 Ir(e,t){if(t+1>e.length)throw new Error("Offset is outside the bounds of Uint8Array");return e[t]}function ib(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 Ms(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 qy(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 Vy(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 sb(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 Dy(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 $y(e){return e<We.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}function ob(e,t,n){const r=$y(t);return r===1?wn(e,n,t):r===2?(wn(e,n,We.OP_PUSHDATA1),wn(e,n+1,t)):r===3?(wn(e,n,We.OP_PUSHDATA2),nb(e,n+1,t,"LE")):(wn(e,n,We.OP_PUSHDATA4),nc(e,n+1,t,"LE")),r}function cb(e,t){const n=Ir(e,t);let r,i;if(n<We.OP_PUSHDATA1)r=n,i=1;else if(n===We.OP_PUSHDATA1){if(t+2>e.length)return null;r=Ir(e,t+1),i=2}else if(n===We.OP_PUSHDATA2){if(t+3>e.length)return null;r=ib(e,t+1,"LE"),i=3}else{if(t+5>e.length)return null;if(n!==We.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=Ms(e,t+1,"LE"),i=5}return{opcode:n,number:r,size:i}}function ab(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function ub(e){let t=Math.abs(e);const n=ab(t),r=new Uint8Array(n),i=e<0;for(let s=0;s<n;++s)wn(r,s,t&255),t>>=8;return r[n-1]&128?wn(r,n-1,i?128:0):i&&(r[n-1]|=128),r}var Cu;function fb(e){return{lang:e?.lang??Cu?.lang,message:e?.message,abortEarly:e?.abortEarly??Cu?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Cu?.abortPipeEarly}}var lb;function hb(e){return lb?.get(e)}var db;function pb(e){return db?.get(e)}var yb;function gb(e,t){return yb?.get(e)?.get(t)}function Ao(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 Wt(e,t,n,r,i){const s=i&&"input"in i?i.input:n.value,o=i?.expected??e.expects??null,c=i?.received??Ao(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??gb(e.reference,a.lang)??(u?pb(a.lang):null)??r.message??hb(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 mb(e,t){const n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}var wb=class extends Error{issues;constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function jy(e,t){return{kind:"validation",type:"every_item",reference:jy,async:!1,expects:null,requirement:e,message:t,_run(n,r){return n.typed&&!n.value.every(this.requirement)&&Wt(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)&&Wt(this,"integer",t,n),t}}}function Ky(e,t){return{kind:"validation",type:"length",reference:Ky,async:!1,expects:`${e}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value.length!==this.requirement&&Wt(this,"length",n,r,{received:`${n.value.length}`}),n}}}function Da(e,t){return{kind:"validation",type:"max_value",reference:Da,async:!1,expects:`<=${e instanceof Date?e.toJSON():Ao(e)}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value>this.requirement&&Wt(this,"value",n,r,{received:n.value instanceof Date?n.value.toJSON():Ao(n.value)}),n}}}function $a(e,t){return{kind:"validation",type:"min_value",reference:$a,async:!1,expects:`>=${e instanceof Date?e.toJSON():Ao(e)}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value<this.requirement&&Wt(this,"value",n,r,{received:n.value instanceof Date?n.value.toJSON():Ao(n.value)}),n}}}function Gy(e,t){return{kind:"validation",type:"regex",reference:Gy,async:!1,expects:`${e}`,requirement:e,message:t,_run(n,r){return n.typed&&!this.requirement.test(n.value)&&Wt(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 Wy(){return{kind:"schema",type:"any",reference:Wy,expects:"any",async:!1,_run(e){return e.typed=!0,e}}}function ln(e,t){return{kind:"schema",type:"array",reference:ln,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 Wt(this,"type",n,r);return n}}}function Xy(e){return{kind:"schema",type:"bigint",reference:Xy,expects:"bigint",async:!1,message:e,_run(t,n){return typeof t.value=="bigint"?t.typed=!0:Wt(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:Wt(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:Wt(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 un(e){return{kind:"schema",type:"number",reference:un,expects:"number",async:!1,message:e,_run(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:Wt(this,"type",t,n),t}}}function _t(e,t){return{kind:"schema",type:"object",reference:_t,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 Wt(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 Xi(e){return{kind:"schema",type:"string",reference:Xi,expects:"string",async:!1,message:e,_run(t,n){return typeof t.value=="string"?t.typed=!0:Wt(this,"type",t,n),t}}}function er(e,t){return{kind:"schema",type:"tuple",reference:er,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 Wt(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:mb(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];Wt(this,"type",n,r,{issues:id(s)}),n.typed=!0}else{if(o?.length===1)return o[0];Wt(this,"type",n,r,{issues:id(o)})}return n}}}function ct(e,t,n){const r=e._run({typed:!1,value:t},fb(n));if(r.issues)throw new wb(r.issues);return r.value}function ui(e,t){const n={};for(const r in e.entries)n[r]=la(e.entries[r]);return{...e,entries:n}}function Ls(...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=Pr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),vt=e=>Ls(Ka(Uint8Array),Ky(e));function vo(e,t){return e.length!==t.length?!1:e.every((n,r)=>de(n,t[r])===0)}function $n(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 Yy(e){return Array.isArray(e)?e.length!==2?!1:e.every(t=>Yy(t)):vl(e)}const bb=vt(32),Eb=vt(20),cd=vt(32),je=Ka(Uint8Array);Ls(Xi(),Gy(/^([0-9a-f]{2})+$/i));const _b=Ls(un(),Tl(),$a(0),Da(255)),gr=Ls(un(),Tl(),$a(0),Da(4294967295)),Uu=Ls(Xy(),$a(0n),Da(0x7fffffffffffffffn)),ad=e=>_t(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 Sb(e){const t=Ir(e,e.length-1);if(!Ol(t))throw new Error("Invalid hashType "+t);const n=z1(e.subarray(0,-1)),r=ld(n.r),i=ld(n.s);return{signature:at([r,i]),hashType:t}}function Tb(e,t){if(ct(_t({signature:vt(64),hashType:_b}),{signature:e,hashType:t}),!Ol(t))throw new Error("Invalid hashType "+t);const n=new Uint8Array(1);wn(n,0,t);const r=fd(e.slice(0,32)),i=fd(e.slice(32,64));return at([Y1(r,i),n])}const xb=Object.freeze(Object.defineProperty({__proto__:null,decode:Sb,encode:Tb},Symbol.toStringTag,{value:"Module"})),Zy=We.OP_RESERVED,Jy=ln(Al([Ka(Uint8Array),un()]));function Ab(e){return ja(un(),e)&&(e===We.OP_0||e>=We.OP_1&&e<=We.OP_16||e===We.OP_1NEGATE)}function Qy(e){return ja(je,e)||Ab(e)}function Il(e){return ja(Ls(Wy(),jy(Qy)),e)}function eg(e){return e.length-e.filter(Qy).length}function ha(e){if(e.length===0)return We.OP_0;if(e.length===1){if(e[0]>=1&&e[0]<=16)return Zy+e[0];if(e[0]===129)return We.OP_1NEGATE}}function tg(e){return e instanceof Uint8Array}function vb(e){return ja(Jy,e)}function da(e){return e instanceof Uint8Array}function hn(e){if(tg(e))return e;ct(Jy,e);const t=e.reduce((i,s)=>da(s)?s.length===1&&ha(s)!==void 0?i+1:i+$y(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){wn(n,r,s),r+=1;return}r+=ob(n,i.length,r),n.set(i,r),r+=i.length}else wn(n,r,i),r+=1}),r!==n.length)throw new Error("Could not decode chunks");return n}function lt(e){if(vb(e))return e;ct(je,e);const t=[];let n=0;for(;n<e.length;){const r=e[n];if(r>We.OP_0&&r<=We.OP_PUSHDATA4){const i=cb(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 Ib(e){if(tg(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 Hy[t]}).join(" ")}function Ob(e){return e=lt(e),ct(Kn(Il),e),e.map(t=>da(t)?t:t===We.OP_0?new Uint8Array(0):ub(t-Zy))}function Bb(e){return $n(e)}function Ol(e){const t=e&-129;return t>0&&t<4}function Or(e){return!(e instanceof Uint8Array)||!Ol(e[e.length-1])?!1:X1(e.slice(0,-1))}const _o=xb;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 ls=We,Sc=ls.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 Or(a)||(t.allowIncomplete&&a===ls.OP_0)!==void 0}ct(ui(_t({network:_t({}),m:un(),n:un(),output:je,pubkeys:ln(Kn($n),"Received invalid pubkey"),signatures:ln(Kn(n),"Expected signature to be of type isAcceptableSignature"),input:je})),e);const i={network:e.network||Pn};let s=[],o=!1;function c(a){o||(o=!0,s=lt(a),i.m=s[0]-Sc,i.n=s[s.length-2]-Sc,i.pubkeys=s.slice(1,-2))}if(Te(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return hn([].concat(Sc+e.m,e.pubkeys,Sc+i.n,ls.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 hn([ls.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(un(),s[0],{message:"Output is invalid"}),ct(un(),s[s.length-2],{message:"Output is invalid"}),s[s.length-1]!==ls.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=>$n(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&&!vo(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]!==ls.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&&!vo(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=We;function ng(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(ui(_t({network:_t({}),output:je,pubkey:Kn($n,"invalid pubkey"),signature:Kn(Or,"Expected signature to be of type isCanonicalScriptSignature"),input:je})),e);const n=In(()=>lt(e.input)),i={name:"p2pk",network:e.network||Pn};if(Te(i,"output",()=>{if(e.pubkey)return hn([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 hn([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(!$n(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(!Or(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}const ts=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function rc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Nb(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function On(e,...t){if(!rc(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 kb(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 qi(...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 Tc(e,t){return e<<t|e>>>32-t>>>0}const rg=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Pb=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function rt(e){if(On(e),rg)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Pb[e[n]];return t}const or={_0:48,_9:57,A:65,F:70,a:97,f:102};function pd(e){if(e>=or._0&&e<=or._9)return e-or._0;if(e>=or.A&&e<=or.F)return e-(or.A-10);if(e>=or.a&&e<=or.f)return e-(or.a-10)}function ic(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(rg)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 ig(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 Rb{}function Wa(e){const t=r=>e().update(ig(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function sg(e=32){if(ts&&typeof ts.getRandomValues=="function")return ts.getRandomValues(new Uint8Array(e));if(ts&&typeof ts.randomBytes=="function")return Uint8Array.from(ts.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Cb(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 Ub(e,t,n){return e&t^~e&n}function Hb(e,t,n){return e&t^e&n^t&n}class Bl extends Rb{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=ig(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),kb(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,qi(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let l=o;l<i;l++)n[l]=0;Cb(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 Ur=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Hr=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]),Fb=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),og=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Mb=og.map(e=>(9*e+5)%16),cg=(()=>{const n=[[og],[Mb]];for(let r=0;r<4;r++)for(let i of n)i.push(i[r].map(s=>Fb[s]));return n})(),ag=cg[0],ug=cg[1],fg=[[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)),Lb=ag.map((e,t)=>e.map(n=>fg[t][n])),qb=ug.map((e,t)=>e.map(n=>fg[t][n])),Vb=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Db=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 xc=new Uint32Array(16);class $b 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)xc[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=Vb[y],E=Db[y],S=ag[y],_=ug[y],w=Lb[y],T=qb[y];for(let O=0;O<16;O++){const A=Tc(r+yd(y,s,c,u)+xc[S[O]]+m,w[O])+l|0;r=l,l=u,u=Tc(c,10)|0,c=s,s=A}for(let O=0;O<16;O++){const A=Tc(i+yd(g,o,a,f)+xc[_[O]]+E,T[O])+d|0;i=d,d=f,f=Tc(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(){qi(xc)}destroy(){this.destroyed=!0,qi(this.buffer),this.set(0,0,0,0,0)}}const jb=Wa(()=>new $b),Kb=jb,Ac=BigInt(2**32-1),gd=BigInt(32);function Gb(e,t=!1){return t?{h:Number(e&Ac),l:Number(e>>gd&Ac)}:{h:Number(e>>gd&Ac)|0,l:Number(e&Ac)|0}}function Wb(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}=Gb(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,ns=(e,t,n)=>e>>>n|t<<32-n,rs=(e,t,n)=>e<<32-n|t>>>n,vc=(e,t,n)=>e<<64-n|t>>>n-32,Ic=(e,t,n)=>e>>>n-32|t<<64-n;function cr(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}const Xb=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),zb=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Yb=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Zb=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Jb=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Qb=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,eE=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]),Fr=new Uint32Array(64);class lg extends Bl{constructor(t=32){super(64,t,8,!1),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}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)Fr[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const d=Fr[l-15],y=Fr[l-2],g=zn(d,7)^zn(d,18)^d>>>3,m=zn(y,17)^zn(y,19)^y>>>10;Fr[l]=m+Fr[l-7]+g+Fr[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+Ub(c,a,u)+eE[l]+Fr[l]|0,m=(zn(r,2)^zn(r,13)^zn(r,22))+Hb(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(){qi(Fr)}destroy(){this.set(0,0,0,0,0,0,0,0),qi(this.buffer)}}class tE extends lg{constructor(){super(28),this.A=Hr[0]|0,this.B=Hr[1]|0,this.C=Hr[2]|0,this.D=Hr[3]|0,this.E=Hr[4]|0,this.F=Hr[5]|0,this.G=Hr[6]|0,this.H=Hr[7]|0}}const hg=Wb(["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))),nE=hg[0],rE=hg[1],Mr=new Uint32Array(80),Lr=new Uint32Array(80);class iE 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)Mr[w]=t.getUint32(n),Lr[w]=t.getUint32(n+=4);for(let w=16;w<80;w++){const T=Mr[w-15]|0,O=Lr[w-15]|0,A=ns(T,O,1)^ns(T,O,8)^md(T,O,7),R=rs(T,O,1)^rs(T,O,8)^wd(T,O,7),M=Mr[w-2]|0,v=Lr[w-2]|0,C=ns(M,v,19)^vc(M,v,61)^md(M,v,6),q=rs(M,v,19)^Ic(M,v,61)^wd(M,v,6),K=Yb(R,q,Lr[w-7],Lr[w-16]),H=Zb(K,A,C,Mr[w-7],Mr[w-16]);Mr[w]=H|0,Lr[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:S,Hl:_}=this;for(let w=0;w<80;w++){const T=ns(l,d,14)^ns(l,d,18)^vc(l,d,41),O=rs(l,d,14)^rs(l,d,18)^Ic(l,d,41),A=l&y^~l&m,R=d&g^~d&E,M=Jb(_,O,R,rE[w],Lr[w]),v=Qb(M,S,T,A,nE[w],Mr[w]),C=M|0,q=ns(r,i,28)^vc(r,i,34)^vc(r,i,39),K=rs(r,i,28)^Ic(r,i,34)^Ic(r,i,39),H=r&s^r&c^s&c,D=i&o^i&a^o&a;S=m|0,_=E|0,m=y|0,E=g|0,y=l|0,g=d|0,{h:l,l:d}=cr(u|0,f|0,v|0,C|0),u=c|0,f=a|0,c=s|0,a=o|0,s=r|0,o=i|0;const P=Xb(C,K,D);r=zb(P,v,q,H),i=P|0}({h:r,l:i}=cr(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=cr(this.Bh|0,this.Bl|0,s|0,o|0),{h:c,l:a}=cr(this.Ch|0,this.Cl|0,c|0,a|0),{h:u,l:f}=cr(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=cr(this.Eh|0,this.El|0,l|0,d|0),{h:y,l:g}=cr(this.Fh|0,this.Fl|0,y|0,g|0),{h:m,l:E}=cr(this.Gh|0,this.Gl|0,m|0,E|0),{h:S,l:_}=cr(this.Hh|0,this.Hl|0,S|0,_|0),this.set(r,i,s,o,c,a,u,f,l,d,y,g,m,E,S,_)}roundClean(){qi(Mr,Lr)}destroy(){qi(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const bn=Wa(()=>new lg),sE=Wa(()=>new tE),oE=Wa(()=>new iE),en=bn;function vr(e){return Kb(en(e))}function mi(e){return en(en(e))}const cE={"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([cE[e],t]))}function aE(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 _=u[d],w=0;for(let T=g-1;(_!==0||w<l)&&T!==-1;T--,w++)_+=256*m[T]>>>0,m[T]=_%n>>>0,_=_/n>>>0;if(_!==0)throw new Error("Non-zero carry");l=w,d++}let E=g-l;for(;E!==g&&m[E]===0;)E++;let S=r.repeat(f);for(;E<g;++E)S+=e.charAt(m[E]);return S}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 _=u.charCodeAt(f);if(_>255)return;let w=t[_];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 S=l;for(;m!==y;)E[S++]=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 uE="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Fu=aE(uE);function fE(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 lE(e){return en(en(e))}const Io=fE(lE),qr=We;function sc(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(ui(_t({network:_t({}),address:Xi(),hash:Eb,output:vt(25),pubkey:Kn($n),signature:Kn(Or),input:je})),e);const n=In(()=>{const o=Io.decode(e.address),c=Ir(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 wn(o,0,i.pubKeyHash),o.set(s.hash,1),Io.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 vr(e.pubkey||s.pubkey)}),Te(s,"output",()=>{if(s.hash)return hn([qr.OP_DUP,qr.OP_HASH160,s.hash,qr.OP_EQUALVERIFY,qr.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 hn([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]!==qr.OP_DUP||e.output[1]!==qr.OP_HASH160||e.output[2]!==20||e.output[23]!==qr.OP_EQUALVERIFY||e.output[24]!==qr.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=vr(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(!Or(c[0]))throw new TypeError("Input has invalid signature");if(!$n(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=vr(c[1]);if(o.length>0&&de(o,a)!==0)throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}const Zs=We;function oc(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(ui(_t({network:_t({}),address:Xi(),hash:vt(20),output:vt(23),redeem:ui(_t({network:_t({}),output:je,input:je,witness:ln(je)})),input:je,witness:ln(je)})),e);let n=e.network;n||(n=e.redeem&&e.redeem.network||Pn);const r={network:n},i=In(()=>{const c=Io.decode(e.address),a=Ir(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===Zs.OP_FALSE?Uint8Array.from([]):a,input:hn(c.slice(0,-1)),witness:e.witness||[]}});if(Te(r,"address",()=>{if(!r.hash)return;const c=new Uint8Array(21);return wn(c,0,r.network.scriptHash),c.set(r.hash,1),Io.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 vr(r.redeem.output)}),Te(r,"output",()=>{if(r.hash)return hn([Zs.OP_HASH160,r.hash,Zs.OP_EQUAL])}),Te(r,"redeem",()=>{if(e.input)return o()}),Te(r,"input",()=>{if(!(!e.redeem||!e.redeem.input||!e.redeem.output))return hn([].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]!==Zs.OP_HASH160||e.output[1]!==20||e.output[22]!==Zs.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(eg(f)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const l=vr(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&&!vo(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(r,e)}var wi={},bd;function cc(){if(bd)return wi;bd=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.bech32m=wi.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 S=0;S<u.length;++S)for(y=y<<f|u[S],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,S){if(S=S||90,m.length+7+E.length>S)throw new TypeError("Exceeds length limit");m=m.toLowerCase();let _=r(m);if(typeof _=="string")throw new Error(_);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");_=n(_)^O,w+=e.charAt(O)}for(let T=0;T<6;++T)_=n(_);_^=f;for(let T=0;T<6;++T){const O=_>>(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 S=m.toLowerCase(),_=m.toUpperCase();if(m!==S&&m!==_)return"Mixed-case string "+m;m=S;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),C=t[v];if(C===void 0)return"Unknown character "+v;A=n(A)^C,!(M+6>=O.length)&&R.push(C)}return A!==f?"Invalid checksum for "+m:{prefix:T,words:R}}function y(m,E){const S=d(m,E);if(typeof S=="object")return S}function g(m,E){const S=d(m,E);if(typeof S=="object")return S;throw new Error(S)}return{decodeUnsafe:y,decode:g,encode:l,toWords:s,fromWordsUnsafe:o,fromWords:c}}return wi.bech32=a("bech32"),wi.bech32m=a("bech32m"),wi}var Gt=cc();const Ed=We,hE=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(ui(_t({address:Xi(),hash:vt(20),input:vt(0),network:_t({}),output:vt(22),pubkey:Kn($n,"Not a valid pubkey"),signature:Kn(Or),witness:ln(je)})),e);const n=In(()=>{const s=Gt.bech32.decode(e.address),o=s.words.shift(),c=Gt.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=Gt.bech32.toWords(i.hash);return s.unshift(0),Gt.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 vr(e.pubkey||i.pubkey)}),Te(i,"output",()=>{if(i.hash)return hn([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 hE}),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=vr(e.pubkey);if(s.length>0&&de(s,o)!==0)throw new TypeError("Hash mismatch");if(s=o,!$n(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(!Or(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!$n(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=vr(e.witness[1]);if(s.length>0&&de(s,o)!==0)throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}const _d=We,Mu=new Uint8Array(0);function Oc(e){return!!(e instanceof Uint8Array&&e.length===65&&e[0]===4&&$n(e))}function ac(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:_t({}),address:Xi(),hash:bb,output:vt(34),redeem:ad({input:je,network:_t({}),output:je,witness:ln(je)}),input:vt(0),witness:ln(je)}),e);const n=In(()=>{const o=Gt.bech32.decode(e.address),c=o.words.shift(),a=Gt.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=Gt.bech32.toWords(s.hash);return o.unshift(0),Gt.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 hn([_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=Ob(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(eg(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&&!vo(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&r().some(Oc)||e.redeem.output&&(lt(e.redeem.output)||[]).some(Oc))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(Oc)||(lt(c)||[]).some(Oc))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(s,e)}const So={};function dE(e){e?e!==So.eccLib&&(pE(e),So.eccLib=e):So.eccLib=e}function Lf(){if(!So.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return So.eccLib}const ar=e=>Pr(e);function pE(e){Sn(typeof e.isXOnlyPoint=="function"),Sn(e.isXOnlyPoint(ar("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Sn(e.isXOnlyPoint(ar("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Sn(e.isXOnlyPoint(ar("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Sn(e.isXOnlyPoint(ar("0000000000000000000000000000000000000000000000000000000000000001"))),Sn(!e.isXOnlyPoint(ar("0000000000000000000000000000000000000000000000000000000000000000"))),Sn(!e.isXOnlyPoint(ar("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Sn(typeof e.xOnlyPointAddTweak=="function"),yE.forEach(t=>{const n=e.xOnlyPointAddTweak(ar(t.pubkey),ar(t.tweak));t.result===null?Sn(n===null):(Sn(n!==null),Sn(n.parity===t.parity),Sn(de(n.xOnlyPubkey,ar(t.result))===0))})}function Sn(e){if(!e)throw new Error("ecc library invalid")}const yE=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}],dg="0123456789abcdefABCDEF";dg.split("").map(e=>e.codePointAt(0));Array(256).fill(!0).map((e,t)=>{const n=String.fromCodePoint(t),r=dg.indexOf(n);return r<0?void 0:r<16?r:r-6});new TextEncoder;new TextDecoder;function gE(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 mE(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 wE(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 bE(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 EE(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 _E(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 SE=e=>{if(e<0||e>0xffffffffffffffffn)throw new RangeError("value out of range")};function TE(e){if(e<0||e>Number.MAX_SAFE_INTEGER||e%1!==0)throw new RangeError("value out of range")}function pg(e){typeof e=="number"?TE(e):SE(e)}function fi(e,t,n){pg(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),gE(t,n+1,Number(e),"LE"),r=3):e<=4294967295?(t.set([254],n),mE(t,n+1,Number(e),"LE"),r=5):(t.set([255],n),wE(t,n+1,BigInt(e),"LE"),r=9),{buffer:t,bytes:r}}function qs(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=bE(e,t+1,"LE");return{numberValue:r,bigintValue:BigInt(r),bytes:3}}else if(n===254){const r=EE(e,t+1,"LE");return{numberValue:r,bigintValue:BigInt(r),bytes:5}}else{const r=_E(e,t+1,"LE");return{numberValue:r<=Number.MAX_SAFE_INTEGER?Number(r):null,bigintValue:r,bytes:9}}}function Bn(e){return pg(e),e<253?1:e<=65535?3:e<=4294967295?5:9}const xE=9007199254740991;function AE(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(er([je,gr]),[t,n])}writeUInt8(t){this.offset=wn(this.buffer,this.offset,t)}writeInt32(t){this.offset=qy(this.buffer,this.offset,t,"LE")}writeInt64(t){this.offset=Vy(this.buffer,this.offset,BigInt(t),"LE")}writeUInt32(t){this.offset=nc(this.buffer,this.offset,t,"LE")}writeUInt64(t){this.offset=rb(this.buffer,this.offset,BigInt(t),"LE")}writeVarInt(t){const{bytes:n}=fi(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 vE{buffer;offset;constructor(t,n=0){this.buffer=t,this.offset=n,ct(er([je,gr]),[t,n])}readUInt8(){const t=Ir(this.buffer,this.offset);return this.offset++,t}readInt32(){const t=sb(this.buffer,this.offset,"LE");return this.offset+=4,t}readUInt32(){const t=Ms(this.buffer,this.offset,"LE");return this.offset+=4,t}readInt64(){const t=Dy(this.buffer,this.offset,"LE");return this.offset+=8,t}readVarInt(){const{bigintValue:t,bytes:n}=qs(this.buffer,this.offset);return this.offset+=n,t}readSlice(t){AE(t,xE);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 yg=192,IE=128,OE=e=>"left"in e&&"right"in e;function qf(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=Df(r,s):r=Df(s,r)}return r}function Vf(e){if(vl(e))return{hash:_r(e)};const t=[Vf(e[0]),Vf(e[1])];t.sort((i,s)=>de(i.hash,s.hash));const[n,r]=t;return{hash:Df(n.hash,r.hash),left:n,right:r}}function pa(e,t){if(OE(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 _r(e){const t=e.version||yg;return Xa("TapLeaf",at([Uint8Array.from([t]),NE(e.output)]))}function BE(e,t){return Xa("TapTweak",at(t?[e,t]:[e]))}function Bc(e,t){if(!(e instanceof Uint8Array)||e.length!==32||t&&t.length!==32)return null;const n=BE(e,t),r=Lf().xOnlyPointAddTweak(e,n);return!r||r.xOnlyPubkey===null?null:{parity:r.parity,x:Uint8Array.from(r.xOnlyPubkey)}}function Df(e,t){return Xa("TapBranch",at([e,t]))}function NE(e){const t=Bn(e.length),n=new Uint8Array(t);return fi(e.length,n),at([n,e])}const Td=We,xd=1,kE=80;function uc(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(ui(_t({address:Xi(),input:vt(0),network:_t({}),output:vt(34),internalPubkey:vt(32),hash:vt(32),pubkey:vt(32),signature:Al([vt(64),vt(65)]),witness:ln(je),scriptTree:Kn(Yy,"Taptree is not of type isTaptree"),redeem:ui(_t({output:je,redeemVersion:un(),witness:ln(je)})),redeemVersion:un()})),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]===kE?e.witness.slice(0,-1):e.witness.slice()}),i=In(()=>{if(e.scriptTree)return Vf(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=Gt.bech32m.toWords(o.pubkey);return c.unshift(xd),Gt.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=_r({output:l,version:f});return qf(u,d)}return null}),Te(o,"output",()=>{if(o.pubkey)return hn([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:yg),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=Bc(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=_r({output:e.redeem.output,version:o.redeemVersion}),u=pa(c,a);if(!u)return;const f=Bc(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=Bc(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&&!Lf().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=_r({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&&!vo(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(!Lf().isXOnlyPoint(d))throw new TypeError("Invalid internalPubkey for p2tr witness");const y=f[0]&Xc,g=u[u.length-2],m=_r({output:g,version:y}),E=qf(f,m),S=Bc(d,E);if(!S)throw new TypeError("Invalid outputKey for p2tr witness");if(c.length&&de(c,S.x)!==0)throw new TypeError("Pubkey mismatch for p2tr witness");if(S.parity!==(f[0]&1))throw new Error("Incorrect parity")}}return Object.assign(o,e)}const gg=40,mg=2,wg=16,bg=2,Eg=80,_g="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 PE(e,t){const n=e.slice(2);if(n.length<mg||n.length>gg)throw new TypeError("Invalid program length for segwit address");const r=e[0]-Eg;if(r<bg||r>wg)throw new TypeError("Invalid version for segwit address");if(e[1]!==n.length)throw new TypeError("Invalid script for segwit address");return console.warn(_g),RE(n,r,t.bech32)}function Sg(e){const t=Io.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=Ir(t,0),r=t.slice(1);return{version:n,hash:r}}function kl(e){let t,n;try{t=Gt.bech32.decode(e)}catch{}if(t){if(n=t.words[0],n!==0)throw new TypeError(e+" uses wrong encoding")}else if(t=Gt.bech32m.decode(e),n=t.words[0],n===0)throw new TypeError(e+" uses wrong encoding");const r=Gt.bech32.fromWords(t.words.slice(1));return{version:n,prefix:t.prefix,data:Uint8Array.from(r)}}function RE(e,t,n){const r=Gt.bech32.toWords(e);return r.unshift(t),t===0?Gt.bech32.encode(n,r):Gt.bech32m.encode(n,r)}function CE(e,t){t=t||Pn;try{return sc({output:e,network:t}).address}catch{}try{return oc({output:e,network:t}).address}catch{}try{return za({output:e,network:t}).address}catch{}try{return ac({output:e,network:t}).address}catch{}try{return uc({output:e,network:t}).address}catch{}try{return PE(e,t)}catch{}throw new Error(Ib(e)+" has no matching Address")}function Tg(e,t){t=t||Pn;let n,r;try{n=Sg(e)}catch{}if(n){if(n.version===t.pubKeyHash)return sc({hash:n.hash}).output;if(n.version===t.scriptHash)return oc({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 ac({hash:r.data}).output}else if(r.version===1){if(r.data.length===32)return uc({pubkey:r.data}).output}else if(r.version>=bg&&r.version<=wg&&r.data.length>=mg&&r.data.length<=gg)return console.warn(_g),hn([r.version+Eg,r.data])}}throw new Error(e+" has no matching Script")}function Qn(e){const t=e.length;return Bn(t)+t}function UE(e){const t=e.length;return Bn(t)+e.reduce((n,r)=>n+Qn(r),0)}const ti=new Uint8Array(0),Ad=[],Lu=Pr("0000000000000000000000000000000000000000000000000000000000000000"),vd=Pr("0000000000000000000000000000000000000000000000000000000000000001"),HE=Pr("ffffffffffffffff"),FE={script:ti,valueBuffer:HE};function ME(e){return e.value!==void 0}let gt=class Ze{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 vE(t),i=new Ze;i.version=r.readInt32();const s=r.readUInt8(),o=r.readUInt8();let c=!1;s===Ze.ADVANCED_TRANSACTION_MARKER&&o===Ze.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 Ze.fromBuffer(Pr(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&&Ze.isCoinbaseHash(this.ins[0].hash)}addInput(t,n,r,i){return ct(er([cd,gr,Mf(la(gr)),Mf(la(je))]),[t,n,r,i]),r==null&&(r=Ze.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:n,script:i||ti,sequence:r,witness:Ad})-1}addOutput(t,n){return ct(er([je,Uu]),[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+Qn(i.script),0)+this.outs.reduce((r,i)=>r+8+Qn(i.script),0)+(n?this.ins.reduce((r,i)=>r+UE(i.witness),0):0)}clone(){const t=new Ze;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(er([gr,je,un()]),[t,n,r]),t>=this.ins.length)return vd;const i=hn(lt(n).filter(c=>c!==We.OP_CODESEPARATOR)),s=this.clone();if((r&31)===Ze.SIGHASH_NONE)s.outs=[],s.ins.forEach((c,a)=>{a!==t&&(c.sequence=0)});else if((r&31)===Ze.SIGHASH_SINGLE){if(t>=this.outs.length)return vd;s.outs.length=t+1;for(let c=0;c<t;c++)s.outs[c]=FE;s.ins.forEach((c,a)=>{a!==t&&(c.sequence=0)})}r&Ze.SIGHASH_ANYONECANPAY?(s.ins=[s.ins[t]],s.ins[0].script=i):(s.ins.forEach(c=>{c.script=ti}),s.ins[t].script=i);const o=new Uint8Array(s.byteLength(!1)+4);return qy(o,o.length-4,r,"LE"),s.__toBuffer(o,0,!1),mi(o)}hashForWitnessV1(t,n,r,i,s,o){if(ct(er([gr,ln(je),ln(Uu),gr]),[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===Ze.SIGHASH_DEFAULT?Ze.SIGHASH_ALL:i&Ze.SIGHASH_OUTPUT_MASK,u=(i&Ze.SIGHASH_INPUT_MASK)===Ze.SIGHASH_ANYONECANPAY,f=c===Ze.SIGHASH_NONE,l=c===Ze.SIGHASH_SINGLE;let d=ti,y=ti,g=ti,m=ti,E=ti;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(Qn).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+Qn(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+Qn(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=(s?2:0)+(o?1:0),_=174-(u?49:0)-(f?32:0)+(o?32:0)+(s?37:0),w=$t.withCapacity(_);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(S),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(Qn(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(er([gr,je,Uu,gr]),[t,n,r,i]);let s=Uint8Array.from([]),o,c=Lu,a=Lu,u=Lu;if(i&Ze.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=mi(s)),!(i&Ze.SIGHASH_ANYONECANPAY)&&(i&31)!==Ze.SIGHASH_SINGLE&&(i&31)!==Ze.SIGHASH_NONE&&(s=new Uint8Array(4*this.ins.length),o=new $t(s,0),this.ins.forEach(l=>{o.writeUInt32(l.sequence)}),u=mi(s)),(i&31)!==Ze.SIGHASH_SINGLE&&(i&31)!==Ze.SIGHASH_NONE){const l=this.outs.reduce((d,y)=>d+8+Qn(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=mi(s)}else if((i&31)===Ze.SIGHASH_SINGLE&&t<this.outs.length){const l=this.outs[t];s=new Uint8Array(8+Qn(l.script)),o=new $t(s,0),o.writeInt64(l.value),o.writeVarSlice(l.script),c=mi(s)}s=new Uint8Array(156+Qn(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),mi(s)}getHash(t){return t&&this.isCoinbase()?new Uint8Array(32):mi(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(er([un(),je]),[t,n]),this.ins[t].script=n}setWitness(t,n){ct(er([un(),ln(je)]),[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(Ze.ADVANCED_TRANSACTION_MARKER),i.writeUInt8(Ze.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=>{ME(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 rr;(function(e){e[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB"})(rr||(rr={}));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 LE=e=>[...Array(e).keys()];function qE(e){if(e.key[0]!==rr.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 LE(e.value.length/4-1)){const i=Ms(e.value,r*4+4,"LE"),s=!!(i&2147483648),o=i&2147483647;n.path+="/"+o.toString(10)+(s?"'":"")}return n}function VE(e){const t=new Uint8Array([rr.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),nc(i,s,a,"LE"),s+=4}),{key:n,value:i}}const DE="{ masterFingerprint: Uint8Array; extendedPubkey: Uint8Array; path: string; }";function $E(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 jE(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 KE=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:jE,check:$E,decode:qE,encode:VE,expected:DE},Symbol.toStringTag,{value:"Module"}));function GE(e){return{key:new Uint8Array([rr.UNSIGNED_TX]),value:e.toBuffer()}}const WE=Object.freeze(Object.defineProperty({__proto__:null,encode:GE},Symbol.toStringTag,{value:"Module"}));function XE(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 zE(e){return{key:new Uint8Array([me.FINAL_SCRIPTSIG]),value:e}}const YE="Uint8Array";function ZE(e){return e instanceof Uint8Array}function JE(e,t){return!!e&&!!t&&e.finalScriptSig===void 0}const QE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:JE,check:ZE,decode:XE,encode:zE,expected:YE},Symbol.toStringTag,{value:"Module"}));function e2(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 t2(e){return{key:new Uint8Array([me.FINAL_SCRIPTWITNESS]),value:e}}const n2="Uint8Array";function r2(e){return e instanceof Uint8Array}function i2(e,t){return!!e&&!!t&&e.finalScriptWitness===void 0}const s2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:i2,check:r2,decode:e2,encode:t2,expected:n2},Symbol.toStringTag,{value:"Module"}));function o2(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 c2(e){return{key:new Uint8Array([me.NON_WITNESS_UTXO]),value:e}}const a2="Uint8Array";function u2(e){return e instanceof Uint8Array}function f2(e,t){return!!e&&!!t&&e.nonWitnessUtxo===void 0}const l2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:f2,check:u2,decode:o2,encode:c2,expected:a2},Symbol.toStringTag,{value:"Module"}));function h2(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 d2(e){const t=new Uint8Array([me.PARTIAL_SIG]);return{key:at([t,e.pubkey]),value:e.signature}}const p2="{ pubkey: Uint8Array; signature: Uint8Array; }";function y2(e){return e.pubkey instanceof Uint8Array&&e.signature instanceof Uint8Array&&[33,65].includes(e.pubkey.length)&&[2,3,4].includes(e.pubkey[0])&&g2(e.signature)}function g2(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 m2(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 w2=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:m2,check:y2,decode:h2,encode:d2,expected:p2},Symbol.toStringTag,{value:"Module"}));function b2(e){if(e.key[0]!==me.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+xe(e.key));return Z1(e.value)}function E2(e){return{key:new Uint8Array([me.POR_COMMITMENT]),value:J1(e)}}const _2="string";function S2(e){return typeof e=="string"}function T2(e,t){return!!e&&!!t&&e.porCommitment===void 0}const x2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:T2,check:S2,decode:b2,encode:E2,expected:_2},Symbol.toStringTag,{value:"Module"}));function A2(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(Ms(e.value,0,"LE"))}function v2(e){const t=Uint8Array.from([me.SIGHASH_TYPE]),n=new Uint8Array(4);return nc(n,0,e,"LE"),{key:t,value:n}}const I2="number";function O2(e){return typeof e=="number"}function B2(e,t){return!!e&&!!t&&e.sighashType===void 0}const N2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:B2,check:O2,decode:A2,encode:v2,expected:I2},Symbol.toStringTag,{value:"Module"}));function k2(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(!xg(e.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return e.value}function P2(e){return{key:Uint8Array.from([me.TAP_KEY_SIG]),value:e}}const R2="Uint8Array";function xg(e){return e instanceof Uint8Array&&(e.length===64||e.length===65)}function C2(e,t){return!!e&&!!t&&e.tapKeySig===void 0}const U2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:C2,check:xg,decode:k2,encode:P2,expected:R2},Symbol.toStringTag,{value:"Module"}));function H2(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 F2(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 M2="{ controlBlock: Uint8Array; leafVersion: number, script: Uint8Array; }";function L2(e){return e.controlBlock instanceof Uint8Array&&(e.controlBlock.length-1)%32===0&&(e.controlBlock[0]&254)===e.leafVersion&&e.script instanceof Uint8Array}function q2(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 V2=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:q2,check:L2,decode:H2,encode:F2,expected:M2},Symbol.toStringTag,{value:"Module"}));function D2(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(!Ag(e.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return e.value}function $2(e){return{key:Uint8Array.from([me.TAP_MERKLE_ROOT]),value:e}}const j2="Uint8Array";function Ag(e){return e instanceof Uint8Array&&e.length===32}function K2(e,t){return!!e&&!!t&&e.tapMerkleRoot===void 0}const G2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:K2,check:Ag,decode:D2,encode:$2,expected:j2},Symbol.toStringTag,{value:"Module"}));function W2(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 X2(e){const t=Uint8Array.from([me.TAP_SCRIPT_SIG]);return{key:at([t,e.pubkey,e.leafHash]),value:e.signature}}const z2="{ pubkey: Uint8Array; leafHash: Uint8Array; signature: Uint8Array; }";function Y2(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 Z2(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 J2=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:Z2,check:Y2,decode:W2,encode:X2,expected:z2},Symbol.toStringTag,{value:"Module"}));function Q2(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=Dy(e.value,0,"LE");let n=8;const{numberValue:r,bytes:i}=qs(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 e_(e){const{script:t,value:n}=e,r=Bn(t.length),i=new Uint8Array(8+r+t.length);return Vy(i,0,BigInt(n),"LE"),fi(t.length,i,8),i.set(t,8+r),{key:Uint8Array.from([me.WITNESS_UTXO]),value:i}}const t_="{ script: Uint8Array; value: bigint; }";function n_(e){return e.script instanceof Uint8Array&&typeof e.value=="bigint"}function r_(e,t){return!!e&&!!t&&e.witnessUtxo===void 0}const i_=Object.freeze(Object.defineProperty({__proto__:null,canAdd:r_,check:n_,decode:Q2,encode:e_,expected:t_},Symbol.toStringTag,{value:"Module"}));function s_(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}=qs(e.value,t);t+=o,n.push({depth:r,leafVersion:i,script:e.value.slice(t,t+s)}),t+=s}return{leaves:n}}function o_(e){const t=Uint8Array.from([pt.TAP_TREE]),n=[].concat(...e.leaves.map(r=>[Uint8Array.of(r.depth,r.leafVersion),fi(BigInt(r.script.length)).buffer,r.script]));return{key:t,value:at(n)}}const c_="{ leaves: [{ depth: number; leafVersion: number, script: Uint8Array; }] }";function a_(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 u_(e,t){return!!e&&!!t&&e.tapTree===void 0}const f_=Object.freeze(Object.defineProperty({__proto__:null,canAdd:u_,check:a_,decode:s_,encode:o_,expected:c_},Symbol.toStringTag,{value:"Module"})),l_=e=>[...Array(e).keys()],h_=e=>e.length===33&&[2,3].includes(e[0])||e.length===65&&e[0]===4;function Pl(e,t=h_){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 l_(c.value.length/4-1)){const l=Ms(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),nc(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 vg(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 d_=e=>e.length===32;function Ig(e){const t=Pl(e,d_);function n(o){const{numberValue:c,bytes:a}=qs(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);fi(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 Og(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 Bg(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 Cl={unsignedTx:WE,globalXpub:KE,checkPubkey:Rl([])},St={nonWitnessUtxo:l2,partialSig:w2,sighashType:N2,finalScriptSig:QE,finalScriptWitness:s2,porCommitment:x2,witnessUtxo:i_,bip32Derivation:Pl(me.BIP32_DERIVATION),redeemScript:vg(me.REDEEM_SCRIPT),witnessScript:Bg(me.WITNESS_SCRIPT),checkPubkey:Rl([me.PARTIAL_SIG,me.BIP32_DERIVATION]),tapKeySig:U2,tapScriptSig:J2,tapLeafScript:V2,tapBip32Derivation:Ig(me.TAP_BIP32_DERIVATION),tapInternalKey:Og(me.TAP_INTERNAL_KEY),tapMerkleRoot:G2},mr={bip32Derivation:Pl(pt.BIP32_DERIVATION),redeemScript:vg(pt.REDEEM_SCRIPT),witnessScript:Bg(pt.WITNESS_SCRIPT),checkPubkey:Rl([pt.BIP32_DERIVATION]),tapBip32Derivation:Ig(pt.TAP_BIP32_DERIVATION),tapTree:f_,tapInternalKey:Og(pt.TAP_INTERNAL_KEY)},p_=Object.freeze(Object.defineProperty({__proto__:null,globals:Cl,inputs:St,outputs:mr},Symbol.toStringTag,{value:"Module"})),ya=e=>[...Array(e).keys()];function Id(e){const t=e.map(y_);return t.push(Uint8Array.from([0])),at(t)}function y_(e){const t=e.key.length,n=e.value.length,r=Bn(t),i=Bn(n),s=new Uint8Array(r+t+i+n);return fi(t,s,0),s.set(e.key,r),fi(n,s,r+t),s.set(e.value,r+t+i),s}function g_(e,t){let n=0;function r(){const{numberValue:E,bytes:S}=qs(e,n);n+=S;const _=e.slice(n,n+Number(E));return n+=Number(E),_}function i(){const E=Ms(e,n,"BE");return n+=4,E}function s(){const E=Ir(e,n);return n+=1,E}function o(){const E=r(),S=r();return{key:E,value:S}}function c(){if(n>=e.length)throw new Error("Format Error: Unexpected End of PSBT");const E=Ir(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(),S=xe(E.key);if(u[S])throw new Error("Format Error: Keys must be unique for global keymap: key "+S);u[S]=1,a.push(E)}const f=a.filter(E=>E.key[0]===rr.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(S[T])throw new Error("Format Error: Keys must be unique for each input: input index "+E+" key "+T);S[T]=1,_.push(w)}g.push(_)}for(const E of ya(y)){const S={},_=[];for(;!c();){const w=o(),T=xe(w.key);if(S[T])throw new Error("Format Error: Keys must be unique for each output: output index "+E+" key "+T);S[T]=1,_.push(w)}m.push(_)}return Ng(l,{globalMapKeyVals:a,inputKeyVals:g,outputKeyVals:m})}function Dt(e,t,n){if(de(t,Uint8Array.from([n])))throw new Error(`Format Error: Invalid ${e} key: ${xe(t)}`)}function Ng(e,{globalMapKeyVals:t,inputKeyVals:n,outputKeyVals:r}){const i={unsignedTx:e};let s=0;for(const f of t)switch(f.key[0]){case rr.UNSIGNED_TX:if(Dt("global",f.key,rr.UNSIGNED_TX),s>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");s++;break;case rr.GLOBAL_XPUB:i.globalXpub===void 0&&(i.globalXpub=[]),i.globalXpub.push(Cl.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(St.checkPubkey(d),d.key[0]){case me.NON_WITNESS_UTXO:if(Dt("input",d.key,me.NON_WITNESS_UTXO),l.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");l.nonWitnessUtxo=St.nonWitnessUtxo.decode(d);break;case me.WITNESS_UTXO:if(Dt("input",d.key,me.WITNESS_UTXO),l.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");l.witnessUtxo=St.witnessUtxo.decode(d);break;case me.PARTIAL_SIG:l.partialSig===void 0&&(l.partialSig=[]),l.partialSig.push(St.partialSig.decode(d));break;case me.SIGHASH_TYPE:if(Dt("input",d.key,me.SIGHASH_TYPE),l.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");l.sighashType=St.sighashType.decode(d);break;case me.REDEEM_SCRIPT:if(Dt("input",d.key,me.REDEEM_SCRIPT),l.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");l.redeemScript=St.redeemScript.decode(d);break;case me.WITNESS_SCRIPT:if(Dt("input",d.key,me.WITNESS_SCRIPT),l.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");l.witnessScript=St.witnessScript.decode(d);break;case me.BIP32_DERIVATION:l.bip32Derivation===void 0&&(l.bip32Derivation=[]),l.bip32Derivation.push(St.bip32Derivation.decode(d));break;case me.FINAL_SCRIPTSIG:Dt("input",d.key,me.FINAL_SCRIPTSIG),l.finalScriptSig=St.finalScriptSig.decode(d);break;case me.FINAL_SCRIPTWITNESS:Dt("input",d.key,me.FINAL_SCRIPTWITNESS),l.finalScriptWitness=St.finalScriptWitness.decode(d);break;case me.POR_COMMITMENT:Dt("input",d.key,me.POR_COMMITMENT),l.porCommitment=St.porCommitment.decode(d);break;case me.TAP_KEY_SIG:Dt("input",d.key,me.TAP_KEY_SIG),l.tapKeySig=St.tapKeySig.decode(d);break;case me.TAP_SCRIPT_SIG:l.tapScriptSig===void 0&&(l.tapScriptSig=[]),l.tapScriptSig.push(St.tapScriptSig.decode(d));break;case me.TAP_LEAF_SCRIPT:l.tapLeafScript===void 0&&(l.tapLeafScript=[]),l.tapLeafScript.push(St.tapLeafScript.decode(d));break;case me.TAP_BIP32_DERIVATION:l.tapBip32Derivation===void 0&&(l.tapBip32Derivation=[]),l.tapBip32Derivation.push(St.tapBip32Derivation.decode(d));break;case me.TAP_INTERNAL_KEY:Dt("input",d.key,me.TAP_INTERNAL_KEY),l.tapInternalKey=St.tapInternalKey.decode(d);break;case me.TAP_MERKLE_ROOT:Dt("input",d.key,me.TAP_MERKLE_ROOT),l.tapMerkleRoot=St.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(mr.checkPubkey(d),d.key[0]){case pt.REDEEM_SCRIPT:if(Dt("output",d.key,pt.REDEEM_SCRIPT),l.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");l.redeemScript=mr.redeemScript.decode(d);break;case pt.WITNESS_SCRIPT:if(Dt("output",d.key,pt.WITNESS_SCRIPT),l.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");l.witnessScript=mr.witnessScript.decode(d);break;case pt.BIP32_DERIVATION:l.bip32Derivation===void 0&&(l.bip32Derivation=[]),l.bip32Derivation.push(mr.bip32Derivation.decode(d));break;case pt.TAP_INTERNAL_KEY:Dt("output",d.key,pt.TAP_INTERNAL_KEY),l.tapInternalKey=mr.tapInternalKey.decode(d);break;case pt.TAP_TREE:Dt("output",d.key,pt.TAP_TREE),l.tapTree=mr.tapTree.decode(d);break;case pt.TAP_BIP32_DERIVATION:l.tapBip32Derivation===void 0&&(l.tapBip32Derivation=[]),l.tapBip32Derivation.push(mr.tapBip32Derivation.decode(d));break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(d)}u.push(l)}return{globalMap:i,inputs:a,outputs:u}}function m_({globalMap:e,inputs:t,outputs:n}){const{globalKeyVals:r,inputKeyVals:i,outputKeyVals:s}=$f({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 w_=(e,t)=>de(e.key,t.key);function qu(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(w_)}function $f({globalMap:e,inputs:t,outputs:n}){return{globalKeyVals:qu(e,Cl),inputKeyVals:t.map(r=>qu(r,St)),outputKeyVals:n.map(r=>qu(r,mr))}}function b_(e){const t=e[0],n=$f(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=is(n.globalKeyVals),o=n.inputKeyVals.map(is),c=n.outputKeyVals.map(is);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=$f(a);is(f.globalKeyVals).forEach(Vu(s,n.globalKeyVals,f.globalKeyVals)),f.inputKeyVals.map(is).forEach((g,m)=>g.forEach(Vu(o[m],n.inputKeyVals[m],f.inputKeyVals[m]))),f.outputKeyVals.map(is).forEach((g,m)=>g.forEach(Vu(c[m],n.outputKeyVals[m],f.outputKeyVals[m])))}return Ng(i,{globalMapKeyVals:n.globalKeyVals,inputKeyVals:n.inputKeyVals,outputKeyVals:n.outputKeyVals})}function Vu(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 is(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 Ct(e,t){const n=e[t];if(n===void 0)throw new Error(`No input #${t}`);return n}function Oo(e,t){const n=e[t];if(n===void 0)throw new Error(`No output #${t}`);return n}function Du(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 $u(e){let t=0;return Object.keys(e).forEach(n=>{Number(isNaN(Number(n)))&&t++}),t}function E_(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 Ul(e){return(t,n)=>{for(const r of Object.keys(t)){const i=t[r],{canAdd:s,canAddToArray:o,check:c,expected:a}=p_[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 __=Ul("global"),kg=Ul("input"),Pg=Ul("output");function S_(e,t){const n=e.length-1,r=Ct(e,n);kg(t,r)}function T_(e,t){const n=e.length-1,r=Oo(e,n);Pg(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=Pr(t);return this.fromBuffer(r,n)}static fromBuffer(t,n){const r=g_(t,n),i=new this(r.globalMap.unsignedTx);return Object.assign(i,r),i}toBase64(){const t=this.toBuffer();return tb(t)}toHex(){const t=this.toBuffer();return xe(t)}toBuffer(){return m_(this)}updateGlobal(t){return __(t,this.globalMap),this}updateInput(t,n){const r=Ct(this.inputs,t);return kg(n,r),this}updateOutput(t,n){const r=Oo(this.outputs,t);return Pg(n,r),this}addUnknownKeyValToGlobal(t){return Du(t,this.globalMap.unknownKeyVals,$u(rr)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,n){const r=Ct(this.inputs,t);return Du(n,r.unknownKeyVals,$u(me)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(n),this}addUnknownKeyValToOutput(t,n){const r=Oo(this.outputs,t);return Du(n,r.unknownKeyVals,$u(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)),S_(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)),T_(this.outputs,t),this}clearFinalizedInput(t){const n=Ct(this.inputs,t);E_(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=b_([this].concat(t));return Object.assign(this,n),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}};function zi(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}const x_=zi(Ga),A_=zi(ng),v_=zi(sc),Ya=zi(za),kd=zi(ac),Rg=zi(oc),Cg=zi(uc);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)]),fi(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 Ug(e,t){const n=vr(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 Ug(e,t)!==-1}function I_(e,t){return O_(e).some(r=>Hg(r,_o.decode,t))}function Hg(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 O_(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=B_(e)}else t=e.partialSig;return t.map(n=>n.signature)}function B_(e){const t=e.finalScriptSig?lt(e.finalScriptSig)||[]:[],n=e.finalScriptWitness?lt(e.finalScriptWitness)||[]:[];return t.concat(n).filter(r=>r instanceof Uint8Array&&Or(r)).map(r=>({signature:r}))}const zc=e=>e.length===32?e:e.slice(1,33);function Pd(e,t,n){const r=$_(t,e,n);try{const s=V_(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 Nc(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&&Cg(e.witnessUtxo.script))}function ju(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t)}function Rd(e,t,n){M_(e,t,n),q_(e,t,n)}function Cd(e,t,n){L_(e,t,n),N_(e,t)}function N_(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=k_(n,r);if(i&&de(s,i)!==0)throw new Error("Error adding output. Script or address mismatch.")}}function k_(e,t){const n=t&&P_(t.leaves),{output:r}=uc({internalPubkey:e,scriptTree:n});return r}function P_(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:F_(e)}function R_(e,t){return U_(e).some(r=>Hg(r,C_,t))}function C_(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||gt.SIGHASH_DEFAULT}}function U_(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(n=>n.signature)),!t.length){const n=H_(e.finalScriptWitness);n&&t.push(n)}return t}function H_(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function F_(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>IE)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 M_(e,t,n){const r=Mn(e)&&ws(t),i=ws(e)&&Mn(t),s=e===t&&Mn(t)&&ws(t);if(r||i||s)throw new Error(`Invalid arguments for Psbt.${n}. Cannot use both taproot and non-taproot fields.`)}function L_(e,t,n){const r=ju(e)&&ws(t),i=ws(e)&&ju(t),s=e===t&&ju(t)&&ws(t);if(r||i||s)throw new Error(`Invalid arguments for Psbt.${n}. Cannot use both taproot and non-taproot fields.`)}function q_(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=_r({output:e.script,version:e.leafVersion}),r=qf(e.controlBlock,n);return de(r,t)===0}function V_(e,t){const n=_r({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(r=>de(r.leafHash,n)===0).map(r=>D_(t.script,r)).sort((r,i)=>i.positionInScript-r.positionInScript).map(r=>r.signature)}function D_(e,t){return Object.assign({positionInScript:Ug(t.pubkey,e)},t)}function $_(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=>j_(i,e.tapScriptSig,n));if(!r)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return r}function j_(e,t,n){const r=_r({output:e.script,version:e.leafVersion});return(!n||de(r,n)===0)&&t.find(s=>de(s.leafHash,r)===0)!==void 0}function ws(e){return e&&!!(e.redeemScript||e.witnessScript||e.bip32Derivation&&e.bip32Derivation.length)}const K_={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=Pr(t);return this.fromBuffer(r,n)}static fromBuffer(t,n={}){const r=Nd.fromBuffer(t,G_),i=new ma(n,r);return Z_(i.__CACHE.__TX,i.__CACHE),i}__CACHE;opts;constructor(t={},n=new Nd(new Fg)){this.data=n,this.opts=Object.assign({},K_,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=CE(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){kc(t),this.opts.maximumFeeRate=t}setVersion(t){kc(t),Js(this.data.inputs,"setVersion");const n=this.__CACHE;return n.__TX.version=t,n.__EXTRACTED_TX=void 0,this}setLocktime(t){kc(t),Js(this.data.inputs,"setLocktime");const n=this.__CACHE;return n.__TX.locktime=t,n.__EXTRACTED_TX=void 0,this}setInputSequence(t,n){kc(n),Js(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"),Js(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];qg(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]");Js(this.data.inputs,"addOutput");const{address:n}=t;if(typeof n=="string"){const{network:i}=this.opts,s=Tg(n,i);t=Object.assign({},t,{script:s})}Cd(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(Mg))throw new Error("Not finalized");const n=this.__CACHE;if(t||X_(this,n,this.opts),n.__EXTRACTED_TX)return n.__EXTRACTED_TX;const r=n.__TX.clone();return Gg(this.data.inputs,r,n,!0),r}getFeeRate(){return Ld("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return Ld("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Ct(this.data.inputs,0),Qs(this.data.inputs.length).forEach(t=>this.finalizeInput(t)),this}finalizeInput(t,n){const r=Ct(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=Ct(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=J_){const{script:i,isP2SH:s,isP2WSH:o,isSegwit:c}=nS(t,n,this.__CACHE);if(!i)throw new Error(`No script found for input #${t}`);z_(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=uc({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=Ct(this.data.inputs,t),r=Wg(t,n,this.__CACHE),i=Qa(r,t,"input",n.redeemScript||cS(n.finalScriptSig),n.witnessScript||aS(n.finalScriptWitness)),s=i.type==="raw"?"":i.type+"-",o=zg(i.meaningfulScript);return s+o}inputHasPubkey(t,n){const r=Ct(this.data.inputs,t);return sS(n,r,t,this.__CACHE)}inputHasHDKey(t,n){const r=Ct(this.data.inputs,t),i=Hd(n);return!!r.bip32Derivation&&r.bip32Derivation.some(i)}outputHasPubkey(t,n){const r=Oo(this.data.outputs,t);return oS(n,r,t,this.__CACHE)}outputHasHDKey(t,n){const r=Oo(this.data.outputs,t),i=Hd(n);return!!r.bip32Derivation&&r.bip32Derivation.some(i)}validateSignaturesOfAllInputs(t){return Ct(this.data.inputs,0),Qs(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=_o.decode(l.signature),{hash:y,script:g}=f!==d.hashType?Dg(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):eS(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,Vd(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,Vd(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 Qs(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 Qs(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 Dd(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=Dd(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 Qs(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=Ct(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=Ct(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}=qd(this.data.inputs,t,n.publicKey,this.__CACHE,r),o=[{pubkey:n.publicKey,signature:_o.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=>Nc(r.signSchnorr(u.hash),n.sighashType))[0],a=o.filter(u=>!!u.leafHash).map(u=>({pubkey:zc(r.publicKey),signature:Nc(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=Ct(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=Ct(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}=qd(this.data.inputs,t,n.publicKey,this.__CACHE,r);return Promise.resolve(n.sign(i)).then(o=>{const c=[{pubkey:n.publicKey,signature:_o.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:Nc(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:Nc(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 Cd(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 G_=e=>new Fg(e);class Fg{tx;constructor(t=Uint8Array.from([2,0,0,0,0,0,0,0,0,0])){this.tx=gt.fromBuffer(t),Y_(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(Pr(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 W_(e,t,n){switch(n){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Ud(1,e.partialSig);case"multisig":const r=Ga({output:t});return Ud(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 Ud(e,t,n){if(!t)return!1;let r;if(n?r=n.map(i=>{const s=uS(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 Mg(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 kc(e){if(typeof e!="number"||e!==Math.floor(e)||e>4294967295||e<0)throw new Error("Invalid 32 bit integer")}function X_(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 Js(e,t){e.forEach(n=>{if(Mn(n)?R_(n,t):I_(n,t))throw new Error("Can not modify transaction, signatures exist.")})}function z_(e){if(!e.sighashType||!e.partialSig)return;const{partialSig:t,sighashType:n}=e;t.forEach(r=>{const{hashType:i}=_o.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 Y_(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 Z_(e,t){e.ins.forEach(n=>{qg(t,n)})}function qg(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 Vg(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=Vg(oc,"Redeem script"),Md=Vg(ac,"Witness script");function Ld(e,t,n,r){if(!n.every(Mg))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(),Gg(n,i,r,s),e==="__FEE_RATE")return r.__FEE_RATE;if(e==="__FEE")return r.__FEE}function J_(e,t,n,r,i,s){const o=zg(n);if(!W_(t,n,o))throw new Error(`Can not finalize input #${e}`);return Q_(n,o,t.partialSig,r,i,s)}function Q_(e,t,n,r,i,s){let o,c;const a=tS(e,t,n),u=s?ac({redeem:a}):null,f=i?oc({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 qd(e,t,n,r,i){const s=Ct(e,t),{hash:o,sighashType:c,script:a}=Dg(t,s,r,!1,i);return Lg(n,a,"sign"),{hash:o,sighashType:c}}function Dg(e,t,n,r,i){const s=n.__TX,o=t.sighashType||gt.SIGHASH_ALL;jg(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=sc({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 X1(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 z1(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 Y1(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 We={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},Hy={};for(const e of Object.keys(We)){const t=We[e];Hy[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}),Fy=new TextEncoder,My=new TextDecoder;function Z1(e){return My.decode(e)}function J1(e){return Fy.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?eb(t):Q1(t)}function Q1(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 eb(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 My.decode(t)}function Pr(e){const t=Fy.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 tb(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 nb(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 nc(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 rb(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 Ir(e,t){if(t+1>e.length)throw new Error("Offset is outside the bounds of Uint8Array");return e[t]}function ib(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 Ls(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 qy(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 Vy(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 sb(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 Dy(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 $y(e){return e<We.OP_PUSHDATA1?1:e<=255?2:e<=65535?3:5}function ob(e,t,n){const r=$y(t);return r===1?bn(e,n,t):r===2?(bn(e,n,We.OP_PUSHDATA1),bn(e,n+1,t)):r===3?(bn(e,n,We.OP_PUSHDATA2),nb(e,n+1,t,"LE")):(bn(e,n,We.OP_PUSHDATA4),nc(e,n+1,t,"LE")),r}function cb(e,t){const n=Ir(e,t);let r,i;if(n<We.OP_PUSHDATA1)r=n,i=1;else if(n===We.OP_PUSHDATA1){if(t+2>e.length)return null;r=Ir(e,t+1),i=2}else if(n===We.OP_PUSHDATA2){if(t+3>e.length)return null;r=ib(e,t+1,"LE"),i=3}else{if(t+5>e.length)return null;if(n!==We.OP_PUSHDATA4)throw new Error("Unexpected opcode");r=Ls(e,t+1,"LE"),i=5}return{opcode:n,number:r,size:i}}function ab(e){return e>2147483647?5:e>8388607?4:e>32767?3:e>127?2:e>0?1:0}function ub(e){let t=Math.abs(e);const n=ab(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 Cu;function fb(e){return{lang:e?.lang??Cu?.lang,message:e?.message,abortEarly:e?.abortEarly??Cu?.abortEarly,abortPipeEarly:e?.abortPipeEarly??Cu?.abortPipeEarly}}var lb;function hb(e){return lb?.get(e)}var db;function pb(e){return db?.get(e)}var yb;function gb(e,t){return yb?.get(e)?.get(t)}function Ao(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 Wt(e,t,n,r,i){const s=i&&"input"in i?i.input:n.value,o=i?.expected??e.expects??null,c=i?.received??Ao(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??gb(e.reference,a.lang)??(u?pb(a.lang):null)??r.message??hb(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 mb(e,t){const n=[...new Set(e)];return n.length>1?`(${n.join(` ${t} `)})`:n[0]??"never"}var wb=class extends Error{issues;constructor(e){super(e[0].message),this.name="ValiError",this.issues=e}};function jy(e,t){return{kind:"validation",type:"every_item",reference:jy,async:!1,expects:null,requirement:e,message:t,_run(n,r){return n.typed&&!n.value.every(this.requirement)&&Wt(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)&&Wt(this,"integer",t,n),t}}}function Ky(e,t){return{kind:"validation",type:"length",reference:Ky,async:!1,expects:`${e}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value.length!==this.requirement&&Wt(this,"length",n,r,{received:`${n.value.length}`}),n}}}function Da(e,t){return{kind:"validation",type:"max_value",reference:Da,async:!1,expects:`<=${e instanceof Date?e.toJSON():Ao(e)}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value>this.requirement&&Wt(this,"value",n,r,{received:n.value instanceof Date?n.value.toJSON():Ao(n.value)}),n}}}function $a(e,t){return{kind:"validation",type:"min_value",reference:$a,async:!1,expects:`>=${e instanceof Date?e.toJSON():Ao(e)}`,requirement:e,message:t,_run(n,r){return n.typed&&n.value<this.requirement&&Wt(this,"value",n,r,{received:n.value instanceof Date?n.value.toJSON():Ao(n.value)}),n}}}function Gy(e,t){return{kind:"validation",type:"regex",reference:Gy,async:!1,expects:`${e}`,requirement:e,message:t,_run(n,r){return n.typed&&!this.requirement.test(n.value)&&Wt(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 Wy(){return{kind:"schema",type:"any",reference:Wy,expects:"any",async:!1,_run(e){return e.typed=!0,e}}}function hn(e,t){return{kind:"schema",type:"array",reference:hn,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 Wt(this,"type",n,r);return n}}}function Xy(e){return{kind:"schema",type:"bigint",reference:Xy,expects:"bigint",async:!1,message:e,_run(t,n){return typeof t.value=="bigint"?t.typed=!0:Wt(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:Wt(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:Wt(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 fn(e){return{kind:"schema",type:"number",reference:fn,expects:"number",async:!1,message:e,_run(t,n){return typeof t.value=="number"&&!isNaN(t.value)?t.typed=!0:Wt(this,"type",t,n),t}}}function _t(e,t){return{kind:"schema",type:"object",reference:_t,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 Wt(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 Xi(e){return{kind:"schema",type:"string",reference:Xi,expects:"string",async:!1,message:e,_run(t,n){return typeof t.value=="string"?t.typed=!0:Wt(this,"type",t,n),t}}}function er(e,t){return{kind:"schema",type:"tuple",reference:er,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 Wt(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:mb(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];Wt(this,"type",n,r,{issues:id(s)}),n.typed=!0}else{if(o?.length===1)return o[0];Wt(this,"type",n,r,{issues:id(o)})}return n}}}function ct(e,t,n){const r=e._run({typed:!1,value:t},fb(n));if(r.issues)throw new wb(r.issues);return r.value}function ui(e,t){const n={};for(const r in e.entries)n[r]=la(e.entries[r]);return{...e,entries:n}}function qs(...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=Pr("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),vt=e=>qs(Ka(Uint8Array),Ky(e));function vo(e,t){return e.length!==t.length?!1:e.every((n,r)=>de(n,t[r])===0)}function $n(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 Yy(e){return Array.isArray(e)?e.length!==2?!1:e.every(t=>Yy(t)):vl(e)}const bb=vt(32),Eb=vt(20),cd=vt(32),je=Ka(Uint8Array);qs(Xi(),Gy(/^([0-9a-f]{2})+$/i));const _b=qs(fn(),Tl(),$a(0),Da(255)),gr=qs(fn(),Tl(),$a(0),Da(4294967295)),Uu=qs(Xy(),$a(0n),Da(0x7fffffffffffffffn)),ad=e=>_t(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 Sb(e){const t=Ir(e,e.length-1);if(!Ol(t))throw new Error("Invalid hashType "+t);const n=z1(e.subarray(0,-1)),r=ld(n.r),i=ld(n.s);return{signature:at([r,i]),hashType:t}}function Tb(e,t){if(ct(_t({signature:vt(64),hashType:_b}),{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([Y1(r,i),n])}const xb=Object.freeze(Object.defineProperty({__proto__:null,decode:Sb,encode:Tb},Symbol.toStringTag,{value:"Module"})),Zy=We.OP_RESERVED,Jy=hn(Al([Ka(Uint8Array),fn()]));function Ab(e){return ja(fn(),e)&&(e===We.OP_0||e>=We.OP_1&&e<=We.OP_16||e===We.OP_1NEGATE)}function Qy(e){return ja(je,e)||Ab(e)}function Il(e){return ja(qs(Wy(),jy(Qy)),e)}function eg(e){return e.length-e.filter(Qy).length}function ha(e){if(e.length===0)return We.OP_0;if(e.length===1){if(e[0]>=1&&e[0]<=16)return Zy+e[0];if(e[0]===129)return We.OP_1NEGATE}}function tg(e){return e instanceof Uint8Array}function vb(e){return ja(Jy,e)}function da(e){return e instanceof Uint8Array}function nn(e){if(tg(e))return e;ct(Jy,e);const t=e.reduce((i,s)=>da(s)?s.length===1&&ha(s)!==void 0?i+1:i+$y(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+=ob(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(vb(e))return e;ct(je,e);const t=[];let n=0;for(;n<e.length;){const r=e[n];if(r>We.OP_0&&r<=We.OP_PUSHDATA4){const i=cb(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 Ib(e){if(tg(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 Hy[t]}).join(" ")}function Ob(e){return e=lt(e),ct(Kn(Il),e),e.map(t=>da(t)?t:t===We.OP_0?new Uint8Array(0):ub(t-Zy))}function Bb(e){return $n(e)}function Ol(e){const t=e&-129;return t>0&&t<4}function Or(e){return!(e instanceof Uint8Array)||!Ol(e[e.length-1])?!1:X1(e.slice(0,-1))}const _o=xb;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 ls=We,Sc=ls.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 Or(a)||(t.allowIncomplete&&a===ls.OP_0)!==void 0}ct(ui(_t({network:_t({}),m:fn(),n:fn(),output:je,pubkeys:hn(Kn($n),"Received invalid pubkey"),signatures:hn(Kn(n),"Expected signature to be of type isAcceptableSignature"),input:je})),e);const i={network:e.network||Pn};let s=[],o=!1;function c(a){o||(o=!0,s=lt(a),i.m=s[0]-Sc,i.n=s[s.length-2]-Sc,i.pubkeys=s.slice(1,-2))}if(Te(i,"output",()=>{if(e.m&&i.n&&e.pubkeys)return nn([].concat(Sc+e.m,e.pubkeys,Sc+i.n,ls.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([ls.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(fn(),s[0],{message:"Output is invalid"}),ct(fn(),s[s.length-2],{message:"Output is invalid"}),s[s.length-1]!==ls.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=>$n(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&&!vo(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]!==ls.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&&!vo(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=We;function ng(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(ui(_t({network:_t({}),output:je,pubkey:Kn($n,"invalid pubkey"),signature:Kn(Or,"Expected signature to be of type isCanonicalScriptSignature"),input:je})),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(!$n(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(!Or(i.signature))throw new TypeError("Input has invalid signature")}}return Object.assign(i,e)}const ts=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function rc(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"}function Nb(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function On(e,...t){if(!rc(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 kb(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 qi(...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 Tc(e,t){return e<<t|e>>>32-t>>>0}const rg=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Pb=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function rt(e){if(On(e),rg)return e.toHex();let t="";for(let n=0;n<e.length;n++)t+=Pb[e[n]];return t}const or={_0:48,_9:57,A:65,F:70,a:97,f:102};function pd(e){if(e>=or._0&&e<=or._9)return e-or._0;if(e>=or.A&&e<=or.F)return e-(or.A-10);if(e>=or.a&&e<=or.f)return e-(or.a-10)}function ic(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);if(rg)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 ig(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 Rb{}function Wa(e){const t=r=>e().update(ig(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}function sg(e=32){if(ts&&typeof ts.getRandomValues=="function")return ts.getRandomValues(new Uint8Array(e));if(ts&&typeof ts.randomBytes=="function")return Uint8Array.from(ts.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Cb(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 Ub(e,t,n){return e&t^~e&n}function Hb(e,t,n){return e&t^e&n^t&n}class Bl extends Rb{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=ig(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),kb(t,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,qi(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let l=o;l<i;l++)n[l]=0;Cb(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 Ur=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Hr=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]),Fb=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),og=Uint8Array.from(new Array(16).fill(0).map((e,t)=>t)),Mb=og.map(e=>(9*e+5)%16),cg=(()=>{const n=[[og],[Mb]];for(let r=0;r<4;r++)for(let i of n)i.push(i[r].map(s=>Fb[s]));return n})(),ag=cg[0],ug=cg[1],fg=[[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)),Lb=ag.map((e,t)=>e.map(n=>fg[t][n])),qb=ug.map((e,t)=>e.map(n=>fg[t][n])),Vb=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),Db=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 xc=new Uint32Array(16);class $b 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)xc[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=Vb[y],E=Db[y],S=ag[y],_=ug[y],w=Lb[y],T=qb[y];for(let O=0;O<16;O++){const A=Tc(r+yd(y,s,c,u)+xc[S[O]]+m,w[O])+l|0;r=l,l=u,u=Tc(c,10)|0,c=s,s=A}for(let O=0;O<16;O++){const A=Tc(i+yd(g,o,a,f)+xc[_[O]]+E,T[O])+d|0;i=d,d=f,f=Tc(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(){qi(xc)}destroy(){this.destroyed=!0,qi(this.buffer),this.set(0,0,0,0,0)}}const jb=Wa(()=>new $b),Kb=jb,Ac=BigInt(2**32-1),gd=BigInt(32);function Gb(e,t=!1){return t?{h:Number(e&Ac),l:Number(e>>gd&Ac)}:{h:Number(e>>gd&Ac)|0,l:Number(e&Ac)|0}}function Wb(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}=Gb(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,ns=(e,t,n)=>e>>>n|t<<32-n,rs=(e,t,n)=>e<<32-n|t>>>n,vc=(e,t,n)=>e<<64-n|t>>>n-32,Ic=(e,t,n)=>e>>>n-32|t<<64-n;function cr(e,t,n,r){const i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}const Xb=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),zb=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,Yb=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),Zb=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,Jb=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Qb=(e,t,n,r,i,s)=>t+n+r+i+s+(e/2**32|0)|0,eE=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]),Fr=new Uint32Array(64);class lg extends Bl{constructor(t=32){super(64,t,8,!1),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}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)Fr[l]=t.getUint32(n,!1);for(let l=16;l<64;l++){const d=Fr[l-15],y=Fr[l-2],g=zn(d,7)^zn(d,18)^d>>>3,m=zn(y,17)^zn(y,19)^y>>>10;Fr[l]=m+Fr[l-7]+g+Fr[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+Ub(c,a,u)+eE[l]+Fr[l]|0,m=(zn(r,2)^zn(r,13)^zn(r,22))+Hb(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(){qi(Fr)}destroy(){this.set(0,0,0,0,0,0,0,0),qi(this.buffer)}}class tE extends lg{constructor(){super(28),this.A=Hr[0]|0,this.B=Hr[1]|0,this.C=Hr[2]|0,this.D=Hr[3]|0,this.E=Hr[4]|0,this.F=Hr[5]|0,this.G=Hr[6]|0,this.H=Hr[7]|0}}const hg=Wb(["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))),nE=hg[0],rE=hg[1],Mr=new Uint32Array(80),Lr=new Uint32Array(80);class iE 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)Mr[w]=t.getUint32(n),Lr[w]=t.getUint32(n+=4);for(let w=16;w<80;w++){const T=Mr[w-15]|0,O=Lr[w-15]|0,A=ns(T,O,1)^ns(T,O,8)^md(T,O,7),R=rs(T,O,1)^rs(T,O,8)^wd(T,O,7),M=Mr[w-2]|0,v=Lr[w-2]|0,C=ns(M,v,19)^vc(M,v,61)^md(M,v,6),q=rs(M,v,19)^Ic(M,v,61)^wd(M,v,6),K=Yb(R,q,Lr[w-7],Lr[w-16]),H=Zb(K,A,C,Mr[w-7],Mr[w-16]);Mr[w]=H|0,Lr[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:S,Hl:_}=this;for(let w=0;w<80;w++){const T=ns(l,d,14)^ns(l,d,18)^vc(l,d,41),O=rs(l,d,14)^rs(l,d,18)^Ic(l,d,41),A=l&y^~l&m,R=d&g^~d&E,M=Jb(_,O,R,rE[w],Lr[w]),v=Qb(M,S,T,A,nE[w],Mr[w]),C=M|0,q=ns(r,i,28)^vc(r,i,34)^vc(r,i,39),K=rs(r,i,28)^Ic(r,i,34)^Ic(r,i,39),H=r&s^r&c^s&c,D=i&o^i&a^o&a;S=m|0,_=E|0,m=y|0,E=g|0,y=l|0,g=d|0,{h:l,l:d}=cr(u|0,f|0,v|0,C|0),u=c|0,f=a|0,c=s|0,a=o|0,s=r|0,o=i|0;const P=Xb(C,K,D);r=zb(P,v,q,H),i=P|0}({h:r,l:i}=cr(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=cr(this.Bh|0,this.Bl|0,s|0,o|0),{h:c,l:a}=cr(this.Ch|0,this.Cl|0,c|0,a|0),{h:u,l:f}=cr(this.Dh|0,this.Dl|0,u|0,f|0),{h:l,l:d}=cr(this.Eh|0,this.El|0,l|0,d|0),{h:y,l:g}=cr(this.Fh|0,this.Fl|0,y|0,g|0),{h:m,l:E}=cr(this.Gh|0,this.Gl|0,m|0,E|0),{h:S,l:_}=cr(this.Hh|0,this.Hl|0,S|0,_|0),this.set(r,i,s,o,c,a,u,f,l,d,y,g,m,E,S,_)}roundClean(){qi(Mr,Lr)}destroy(){qi(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const En=Wa(()=>new lg),sE=Wa(()=>new tE),oE=Wa(()=>new iE),en=En;function vr(e){return Kb(en(e))}function mi(e){return en(en(e))}const cE={"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([cE[e],t]))}function aE(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 _=u[d],w=0;for(let T=g-1;(_!==0||w<l)&&T!==-1;T--,w++)_+=256*m[T]>>>0,m[T]=_%n>>>0,_=_/n>>>0;if(_!==0)throw new Error("Non-zero carry");l=w,d++}let E=g-l;for(;E!==g&&m[E]===0;)E++;let S=r.repeat(f);for(;E<g;++E)S+=e.charAt(m[E]);return S}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 _=u.charCodeAt(f);if(_>255)return;let w=t[_];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 S=l;for(;m!==y;)E[S++]=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 uE="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Fu=aE(uE);function fE(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 lE(e){return en(en(e))}const Io=fE(lE),qr=We;function sc(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(ui(_t({network:_t({}),address:Xi(),hash:Eb,output:vt(25),pubkey:Kn($n),signature:Kn(Or),input:je})),e);const n=In(()=>{const o=Io.decode(e.address),c=Ir(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),Io.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 vr(e.pubkey||s.pubkey)}),Te(s,"output",()=>{if(s.hash)return nn([qr.OP_DUP,qr.OP_HASH160,s.hash,qr.OP_EQUALVERIFY,qr.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]!==qr.OP_DUP||e.output[1]!==qr.OP_HASH160||e.output[2]!==20||e.output[23]!==qr.OP_EQUALVERIFY||e.output[24]!==qr.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=vr(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(!Or(c[0]))throw new TypeError("Input has invalid signature");if(!$n(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=vr(c[1]);if(o.length>0&&de(o,a)!==0)throw new TypeError("Hash mismatch")}}return Object.assign(s,e)}const Js=We;function oc(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(ui(_t({network:_t({}),address:Xi(),hash:vt(20),output:vt(23),redeem:ui(_t({network:_t({}),output:je,input:je,witness:hn(je)})),input:je,witness:hn(je)})),e);let n=e.network;n||(n=e.redeem&&e.redeem.network||Pn);const r={network:n},i=In(()=>{const c=Io.decode(e.address),a=Ir(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),Io.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 vr(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(eg(f)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const l=vr(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&&!vo(e.redeem.witness,e.witness))throw new TypeError("Witness and redeem.witness mismatch")}return Object.assign(r,e)}var wi={},bd;function cc(){if(bd)return wi;bd=1,Object.defineProperty(wi,"__esModule",{value:!0}),wi.bech32m=wi.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 S=0;S<u.length;++S)for(y=y<<f|u[S],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,S){if(S=S||90,m.length+7+E.length>S)throw new TypeError("Exceeds length limit");m=m.toLowerCase();let _=r(m);if(typeof _=="string")throw new Error(_);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");_=n(_)^O,w+=e.charAt(O)}for(let T=0;T<6;++T)_=n(_);_^=f;for(let T=0;T<6;++T){const O=_>>(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 S=m.toLowerCase(),_=m.toUpperCase();if(m!==S&&m!==_)return"Mixed-case string "+m;m=S;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),C=t[v];if(C===void 0)return"Unknown character "+v;A=n(A)^C,!(M+6>=O.length)&&R.push(C)}return A!==f?"Invalid checksum for "+m:{prefix:T,words:R}}function y(m,E){const S=d(m,E);if(typeof S=="object")return S}function g(m,E){const S=d(m,E);if(typeof S=="object")return S;throw new Error(S)}return{decodeUnsafe:y,decode:g,encode:l,toWords:s,fromWordsUnsafe:o,fromWords:c}}return wi.bech32=a("bech32"),wi.bech32m=a("bech32m"),wi}var Gt=cc();const Ed=We,hE=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(ui(_t({address:Xi(),hash:vt(20),input:vt(0),network:_t({}),output:vt(22),pubkey:Kn($n,"Not a valid pubkey"),signature:Kn(Or),witness:hn(je)})),e);const n=In(()=>{const s=Gt.bech32.decode(e.address),o=s.words.shift(),c=Gt.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=Gt.bech32.toWords(i.hash);return s.unshift(0),Gt.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 vr(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 hE}),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=vr(e.pubkey);if(s.length>0&&de(s,o)!==0)throw new TypeError("Hash mismatch");if(s=o,!$n(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(!Or(e.witness[0]))throw new TypeError("Witness has invalid signature");if(!$n(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=vr(e.witness[1]);if(s.length>0&&de(s,o)!==0)throw new TypeError("Hash mismatch")}}return Object.assign(i,e)}const _d=We,Mu=new Uint8Array(0);function Oc(e){return!!(e instanceof Uint8Array&&e.length===65&&e[0]===4&&$n(e))}function ac(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:_t({}),address:Xi(),hash:bb,output:vt(34),redeem:ad({input:je,network:_t({}),output:je,witness:hn(je)}),input:vt(0),witness:hn(je)}),e);const n=In(()=>{const o=Gt.bech32.decode(e.address),c=o.words.shift(),a=Gt.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=Gt.bech32.toWords(s.hash);return o.unshift(0),Gt.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=Ob(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(eg(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&&!vo(e.witness,e.redeem.witness))throw new TypeError("Witness and redeem.witness mismatch");if(e.redeem.input&&r().some(Oc)||e.redeem.output&&(lt(e.redeem.output)||[]).some(Oc))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(Oc)||(lt(c)||[]).some(Oc))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(s,e)}const So={};function dE(e){e?e!==So.eccLib&&(pE(e),So.eccLib=e):So.eccLib=e}function Lf(){if(!So.eccLib)throw new Error("No ECC Library provided. You must call initEccLib() with a valid TinySecp256k1Interface instance");return So.eccLib}const ar=e=>Pr(e);function pE(e){Tn(typeof e.isXOnlyPoint=="function"),Tn(e.isXOnlyPoint(ar("79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"))),Tn(e.isXOnlyPoint(ar("fffffffffffffffffffffffffffffffffffffffffffffffffffffffeeffffc2e"))),Tn(e.isXOnlyPoint(ar("f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9"))),Tn(e.isXOnlyPoint(ar("0000000000000000000000000000000000000000000000000000000000000001"))),Tn(!e.isXOnlyPoint(ar("0000000000000000000000000000000000000000000000000000000000000000"))),Tn(!e.isXOnlyPoint(ar("fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"))),Tn(typeof e.xOnlyPointAddTweak=="function"),yE.forEach(t=>{const n=e.xOnlyPointAddTweak(ar(t.pubkey),ar(t.tweak));t.result===null?Tn(n===null):(Tn(n!==null),Tn(n.parity===t.parity),Tn(de(n.xOnlyPubkey,ar(t.result))===0))})}function Tn(e){if(!e)throw new Error("ecc library invalid")}const yE=[{pubkey:"79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",tweak:"fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140",parity:-1,result:null},{pubkey:"1617d38ed8d8657da4d4761e8057bc396ea9e4b9d29776d4be096016dbd2509b",tweak:"a8397a935f0dfceba6ba9618f6451ef4d80637abf4e6af2669fbc9de6a8fd2ac",parity:1,result:"e478f99dab91052ab39a33ea35fd5e6e4933f4d28023cd597c9a1f6760346adf"},{pubkey:"2c0b7cf95324a07d05398b240174dc0c2be444d96b159aa6c7f7b1e668680991",tweak:"823c3cd2142744b075a87eade7e1b8678ba308d566226a0056ca2b7a76f86b47",parity:0,result:"9534f8dc8c6deda2dc007655981c78b49c5d96c778fbf363462a11ec9dfd948c"}],dg="0123456789abcdefABCDEF";dg.split("").map(e=>e.codePointAt(0));Array(256).fill(!0).map((e,t)=>{const n=String.fromCodePoint(t),r=dg.indexOf(n);return r<0?void 0:r<16?r:r-6});new TextEncoder;new TextDecoder;function gE(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 mE(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 wE(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 bE(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 EE(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 _E(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 SE=e=>{if(e<0||e>0xffffffffffffffffn)throw new RangeError("value out of range")};function TE(e){if(e<0||e>Number.MAX_SAFE_INTEGER||e%1!==0)throw new RangeError("value out of range")}function pg(e){typeof e=="number"?TE(e):SE(e)}function fi(e,t,n){pg(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),gE(t,n+1,Number(e),"LE"),r=3):e<=4294967295?(t.set([254],n),mE(t,n+1,Number(e),"LE"),r=5):(t.set([255],n),wE(t,n+1,BigInt(e),"LE"),r=9),{buffer:t,bytes:r}}function Vs(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=bE(e,t+1,"LE");return{numberValue:r,bigintValue:BigInt(r),bytes:3}}else if(n===254){const r=EE(e,t+1,"LE");return{numberValue:r,bigintValue:BigInt(r),bytes:5}}else{const r=_E(e,t+1,"LE");return{numberValue:r<=Number.MAX_SAFE_INTEGER?Number(r):null,bigintValue:r,bytes:9}}}function Bn(e){return pg(e),e<253?1:e<=65535?3:e<=4294967295?5:9}const xE=9007199254740991;function AE(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(er([je,gr]),[t,n])}writeUInt8(t){this.offset=bn(this.buffer,this.offset,t)}writeInt32(t){this.offset=qy(this.buffer,this.offset,t,"LE")}writeInt64(t){this.offset=Vy(this.buffer,this.offset,BigInt(t),"LE")}writeUInt32(t){this.offset=nc(this.buffer,this.offset,t,"LE")}writeUInt64(t){this.offset=rb(this.buffer,this.offset,BigInt(t),"LE")}writeVarInt(t){const{bytes:n}=fi(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 vE{buffer;offset;constructor(t,n=0){this.buffer=t,this.offset=n,ct(er([je,gr]),[t,n])}readUInt8(){const t=Ir(this.buffer,this.offset);return this.offset++,t}readInt32(){const t=sb(this.buffer,this.offset,"LE");return this.offset+=4,t}readUInt32(){const t=Ls(this.buffer,this.offset,"LE");return this.offset+=4,t}readInt64(){const t=Dy(this.buffer,this.offset,"LE");return this.offset+=8,t}readVarInt(){const{bigintValue:t,bytes:n}=Vs(this.buffer,this.offset);return this.offset+=n,t}readSlice(t){AE(t,xE);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 yg=192,IE=128,OE=e=>"left"in e&&"right"in e;function qf(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=Df(r,s):r=Df(s,r)}return r}function Vf(e){if(vl(e))return{hash:_r(e)};const t=[Vf(e[0]),Vf(e[1])];t.sort((i,s)=>de(i.hash,s.hash));const[n,r]=t;return{hash:Df(n.hash,r.hash),left:n,right:r}}function pa(e,t){if(OE(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 _r(e){const t=e.version||yg;return Xa("TapLeaf",at([Uint8Array.from([t]),NE(e.output)]))}function BE(e,t){return Xa("TapTweak",at(t?[e,t]:[e]))}function Bc(e,t){if(!(e instanceof Uint8Array)||e.length!==32||t&&t.length!==32)return null;const n=BE(e,t),r=Lf().xOnlyPointAddTweak(e,n);return!r||r.xOnlyPubkey===null?null:{parity:r.parity,x:Uint8Array.from(r.xOnlyPubkey)}}function Df(e,t){return Xa("TapBranch",at([e,t]))}function NE(e){const t=Bn(e.length),n=new Uint8Array(t);return fi(e.length,n),at([n,e])}const Td=We,xd=1,kE=80;function uc(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(ui(_t({address:Xi(),input:vt(0),network:_t({}),output:vt(34),internalPubkey:vt(32),hash:vt(32),pubkey:vt(32),signature:Al([vt(64),vt(65)]),witness:hn(je),scriptTree:Kn(Yy,"Taptree is not of type isTaptree"),redeem:ui(_t({output:je,redeemVersion:fn(),witness:hn(je)})),redeemVersion:fn()})),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]===kE?e.witness.slice(0,-1):e.witness.slice()}),i=In(()=>{if(e.scriptTree)return Vf(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=Gt.bech32m.toWords(o.pubkey);return c.unshift(xd),Gt.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=_r({output:l,version:f});return qf(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:yg),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=Bc(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=_r({output:e.redeem.output,version:o.redeemVersion}),u=pa(c,a);if(!u)return;const f=Bc(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=Bc(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&&!Lf().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=_r({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&&!vo(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(!Lf().isXOnlyPoint(d))throw new TypeError("Invalid internalPubkey for p2tr witness");const y=f[0]&Xc,g=u[u.length-2],m=_r({output:g,version:y}),E=qf(f,m),S=Bc(d,E);if(!S)throw new TypeError("Invalid outputKey for p2tr witness");if(c.length&&de(c,S.x)!==0)throw new TypeError("Pubkey mismatch for p2tr witness");if(S.parity!==(f[0]&1))throw new Error("Incorrect parity")}}return Object.assign(o,e)}const gg=40,mg=2,wg=16,bg=2,Eg=80,_g="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 PE(e,t){const n=e.slice(2);if(n.length<mg||n.length>gg)throw new TypeError("Invalid program length for segwit address");const r=e[0]-Eg;if(r<bg||r>wg)throw new TypeError("Invalid version for segwit address");if(e[1]!==n.length)throw new TypeError("Invalid script for segwit address");return console.warn(_g),RE(n,r,t.bech32)}function Sg(e){const t=Io.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=Ir(t,0),r=t.slice(1);return{version:n,hash:r}}function kl(e){let t,n;try{t=Gt.bech32.decode(e)}catch{}if(t){if(n=t.words[0],n!==0)throw new TypeError(e+" uses wrong encoding")}else if(t=Gt.bech32m.decode(e),n=t.words[0],n===0)throw new TypeError(e+" uses wrong encoding");const r=Gt.bech32.fromWords(t.words.slice(1));return{version:n,prefix:t.prefix,data:Uint8Array.from(r)}}function RE(e,t,n){const r=Gt.bech32.toWords(e);return r.unshift(t),t===0?Gt.bech32.encode(n,r):Gt.bech32m.encode(n,r)}function CE(e,t){t=t||Pn;try{return sc({output:e,network:t}).address}catch{}try{return oc({output:e,network:t}).address}catch{}try{return za({output:e,network:t}).address}catch{}try{return ac({output:e,network:t}).address}catch{}try{return uc({output:e,network:t}).address}catch{}try{return PE(e,t)}catch{}throw new Error(Ib(e)+" has no matching Address")}function Tg(e,t){t=t||Pn;let n,r;try{n=Sg(e)}catch{}if(n){if(n.version===t.pubKeyHash)return sc({hash:n.hash}).output;if(n.version===t.scriptHash)return oc({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 ac({hash:r.data}).output}else if(r.version===1){if(r.data.length===32)return uc({pubkey:r.data}).output}else if(r.version>=bg&&r.version<=wg&&r.data.length>=mg&&r.data.length<=gg)return console.warn(_g),nn([r.version+Eg,r.data])}}throw new Error(e+" has no matching Script")}function Qn(e){const t=e.length;return Bn(t)+t}function UE(e){const t=e.length;return Bn(t)+e.reduce((n,r)=>n+Qn(r),0)}const ti=new Uint8Array(0),Ad=[],Lu=Pr("0000000000000000000000000000000000000000000000000000000000000000"),vd=Pr("0000000000000000000000000000000000000000000000000000000000000001"),HE=Pr("ffffffffffffffff"),FE={script:ti,valueBuffer:HE};function ME(e){return e.value!==void 0}let gt=class Ze{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 vE(t),i=new Ze;i.version=r.readInt32();const s=r.readUInt8(),o=r.readUInt8();let c=!1;s===Ze.ADVANCED_TRANSACTION_MARKER&&o===Ze.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 Ze.fromBuffer(Pr(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&&Ze.isCoinbaseHash(this.ins[0].hash)}addInput(t,n,r,i){return ct(er([cd,gr,Mf(la(gr)),Mf(la(je))]),[t,n,r,i]),r==null&&(r=Ze.DEFAULT_SEQUENCE),this.ins.push({hash:t,index:n,script:i||ti,sequence:r,witness:Ad})-1}addOutput(t,n){return ct(er([je,Uu]),[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+Qn(i.script),0)+this.outs.reduce((r,i)=>r+8+Qn(i.script),0)+(n?this.ins.reduce((r,i)=>r+UE(i.witness),0):0)}clone(){const t=new Ze;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(er([gr,je,fn()]),[t,n,r]),t>=this.ins.length)return vd;const i=nn(lt(n).filter(c=>c!==We.OP_CODESEPARATOR)),s=this.clone();if((r&31)===Ze.SIGHASH_NONE)s.outs=[],s.ins.forEach((c,a)=>{a!==t&&(c.sequence=0)});else if((r&31)===Ze.SIGHASH_SINGLE){if(t>=this.outs.length)return vd;s.outs.length=t+1;for(let c=0;c<t;c++)s.outs[c]=FE;s.ins.forEach((c,a)=>{a!==t&&(c.sequence=0)})}r&Ze.SIGHASH_ANYONECANPAY?(s.ins=[s.ins[t]],s.ins[0].script=i):(s.ins.forEach(c=>{c.script=ti}),s.ins[t].script=i);const o=new Uint8Array(s.byteLength(!1)+4);return qy(o,o.length-4,r,"LE"),s.__toBuffer(o,0,!1),mi(o)}hashForWitnessV1(t,n,r,i,s,o){if(ct(er([gr,hn(je),hn(Uu),gr]),[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===Ze.SIGHASH_DEFAULT?Ze.SIGHASH_ALL:i&Ze.SIGHASH_OUTPUT_MASK,u=(i&Ze.SIGHASH_INPUT_MASK)===Ze.SIGHASH_ANYONECANPAY,f=c===Ze.SIGHASH_NONE,l=c===Ze.SIGHASH_SINGLE;let d=ti,y=ti,g=ti,m=ti,E=ti;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(Qn).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+Qn(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+Qn(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=(s?2:0)+(o?1:0),_=174-(u?49:0)-(f?32:0)+(o?32:0)+(s?37:0),w=$t.withCapacity(_);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(S),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(Qn(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(er([gr,je,Uu,gr]),[t,n,r,i]);let s=Uint8Array.from([]),o,c=Lu,a=Lu,u=Lu;if(i&Ze.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=mi(s)),!(i&Ze.SIGHASH_ANYONECANPAY)&&(i&31)!==Ze.SIGHASH_SINGLE&&(i&31)!==Ze.SIGHASH_NONE&&(s=new Uint8Array(4*this.ins.length),o=new $t(s,0),this.ins.forEach(l=>{o.writeUInt32(l.sequence)}),u=mi(s)),(i&31)!==Ze.SIGHASH_SINGLE&&(i&31)!==Ze.SIGHASH_NONE){const l=this.outs.reduce((d,y)=>d+8+Qn(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=mi(s)}else if((i&31)===Ze.SIGHASH_SINGLE&&t<this.outs.length){const l=this.outs[t];s=new Uint8Array(8+Qn(l.script)),o=new $t(s,0),o.writeInt64(l.value),o.writeVarSlice(l.script),c=mi(s)}s=new Uint8Array(156+Qn(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),mi(s)}getHash(t){return t&&this.isCoinbase()?new Uint8Array(32):mi(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(er([fn(),je]),[t,n]),this.ins[t].script=n}setWitness(t,n){ct(er([fn(),hn(je)]),[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(Ze.ADVANCED_TRANSACTION_MARKER),i.writeUInt8(Ze.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=>{ME(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 rr;(function(e){e[e.UNSIGNED_TX=0]="UNSIGNED_TX",e[e.GLOBAL_XPUB=1]="GLOBAL_XPUB"})(rr||(rr={}));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 LE=e=>[...Array(e).keys()];function qE(e){if(e.key[0]!==rr.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 LE(e.value.length/4-1)){const i=Ls(e.value,r*4+4,"LE"),s=!!(i&2147483648),o=i&2147483647;n.path+="/"+o.toString(10)+(s?"'":"")}return n}function VE(e){const t=new Uint8Array([rr.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),nc(i,s,a,"LE"),s+=4}),{key:n,value:i}}const DE="{ masterFingerprint: Uint8Array; extendedPubkey: Uint8Array; path: string; }";function $E(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 jE(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 KE=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:jE,check:$E,decode:qE,encode:VE,expected:DE},Symbol.toStringTag,{value:"Module"}));function GE(e){return{key:new Uint8Array([rr.UNSIGNED_TX]),value:e.toBuffer()}}const WE=Object.freeze(Object.defineProperty({__proto__:null,encode:GE},Symbol.toStringTag,{value:"Module"}));function XE(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 zE(e){return{key:new Uint8Array([me.FINAL_SCRIPTSIG]),value:e}}const YE="Uint8Array";function ZE(e){return e instanceof Uint8Array}function JE(e,t){return!!e&&!!t&&e.finalScriptSig===void 0}const QE=Object.freeze(Object.defineProperty({__proto__:null,canAdd:JE,check:ZE,decode:XE,encode:zE,expected:YE},Symbol.toStringTag,{value:"Module"}));function e2(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 t2(e){return{key:new Uint8Array([me.FINAL_SCRIPTWITNESS]),value:e}}const n2="Uint8Array";function r2(e){return e instanceof Uint8Array}function i2(e,t){return!!e&&!!t&&e.finalScriptWitness===void 0}const s2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:i2,check:r2,decode:e2,encode:t2,expected:n2},Symbol.toStringTag,{value:"Module"}));function o2(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 c2(e){return{key:new Uint8Array([me.NON_WITNESS_UTXO]),value:e}}const a2="Uint8Array";function u2(e){return e instanceof Uint8Array}function f2(e,t){return!!e&&!!t&&e.nonWitnessUtxo===void 0}const l2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:f2,check:u2,decode:o2,encode:c2,expected:a2},Symbol.toStringTag,{value:"Module"}));function h2(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 d2(e){const t=new Uint8Array([me.PARTIAL_SIG]);return{key:at([t,e.pubkey]),value:e.signature}}const p2="{ pubkey: Uint8Array; signature: Uint8Array; }";function y2(e){return e.pubkey instanceof Uint8Array&&e.signature instanceof Uint8Array&&[33,65].includes(e.pubkey.length)&&[2,3,4].includes(e.pubkey[0])&&g2(e.signature)}function g2(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 m2(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 w2=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:m2,check:y2,decode:h2,encode:d2,expected:p2},Symbol.toStringTag,{value:"Module"}));function b2(e){if(e.key[0]!==me.POR_COMMITMENT)throw new Error("Decode Error: could not decode porCommitment with key 0x"+xe(e.key));return Z1(e.value)}function E2(e){return{key:new Uint8Array([me.POR_COMMITMENT]),value:J1(e)}}const _2="string";function S2(e){return typeof e=="string"}function T2(e,t){return!!e&&!!t&&e.porCommitment===void 0}const x2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:T2,check:S2,decode:b2,encode:E2,expected:_2},Symbol.toStringTag,{value:"Module"}));function A2(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(Ls(e.value,0,"LE"))}function v2(e){const t=Uint8Array.from([me.SIGHASH_TYPE]),n=new Uint8Array(4);return nc(n,0,e,"LE"),{key:t,value:n}}const I2="number";function O2(e){return typeof e=="number"}function B2(e,t){return!!e&&!!t&&e.sighashType===void 0}const N2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:B2,check:O2,decode:A2,encode:v2,expected:I2},Symbol.toStringTag,{value:"Module"}));function k2(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(!xg(e.value))throw new Error("Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature");return e.value}function P2(e){return{key:Uint8Array.from([me.TAP_KEY_SIG]),value:e}}const R2="Uint8Array";function xg(e){return e instanceof Uint8Array&&(e.length===64||e.length===65)}function C2(e,t){return!!e&&!!t&&e.tapKeySig===void 0}const U2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:C2,check:xg,decode:k2,encode:P2,expected:R2},Symbol.toStringTag,{value:"Module"}));function H2(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 F2(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 M2="{ controlBlock: Uint8Array; leafVersion: number, script: Uint8Array; }";function L2(e){return e.controlBlock instanceof Uint8Array&&(e.controlBlock.length-1)%32===0&&(e.controlBlock[0]&254)===e.leafVersion&&e.script instanceof Uint8Array}function q2(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 V2=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:q2,check:L2,decode:H2,encode:F2,expected:M2},Symbol.toStringTag,{value:"Module"}));function D2(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(!Ag(e.value))throw new Error("Decode Error: tapMerkleRoot not a 32-byte hash");return e.value}function $2(e){return{key:Uint8Array.from([me.TAP_MERKLE_ROOT]),value:e}}const j2="Uint8Array";function Ag(e){return e instanceof Uint8Array&&e.length===32}function K2(e,t){return!!e&&!!t&&e.tapMerkleRoot===void 0}const G2=Object.freeze(Object.defineProperty({__proto__:null,canAdd:K2,check:Ag,decode:D2,encode:$2,expected:j2},Symbol.toStringTag,{value:"Module"}));function W2(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 X2(e){const t=Uint8Array.from([me.TAP_SCRIPT_SIG]);return{key:at([t,e.pubkey,e.leafHash]),value:e.signature}}const z2="{ pubkey: Uint8Array; leafHash: Uint8Array; signature: Uint8Array; }";function Y2(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 Z2(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 J2=Object.freeze(Object.defineProperty({__proto__:null,canAddToArray:Z2,check:Y2,decode:W2,encode:X2,expected:z2},Symbol.toStringTag,{value:"Module"}));function Q2(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=Dy(e.value,0,"LE");let n=8;const{numberValue:r,bytes:i}=Vs(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 e_(e){const{script:t,value:n}=e,r=Bn(t.length),i=new Uint8Array(8+r+t.length);return Vy(i,0,BigInt(n),"LE"),fi(t.length,i,8),i.set(t,8+r),{key:Uint8Array.from([me.WITNESS_UTXO]),value:i}}const t_="{ script: Uint8Array; value: bigint; }";function n_(e){return e.script instanceof Uint8Array&&typeof e.value=="bigint"}function r_(e,t){return!!e&&!!t&&e.witnessUtxo===void 0}const i_=Object.freeze(Object.defineProperty({__proto__:null,canAdd:r_,check:n_,decode:Q2,encode:e_,expected:t_},Symbol.toStringTag,{value:"Module"}));function s_(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}=Vs(e.value,t);t+=o,n.push({depth:r,leafVersion:i,script:e.value.slice(t,t+s)}),t+=s}return{leaves:n}}function o_(e){const t=Uint8Array.from([pt.TAP_TREE]),n=[].concat(...e.leaves.map(r=>[Uint8Array.of(r.depth,r.leafVersion),fi(BigInt(r.script.length)).buffer,r.script]));return{key:t,value:at(n)}}const c_="{ leaves: [{ depth: number; leafVersion: number, script: Uint8Array; }] }";function a_(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 u_(e,t){return!!e&&!!t&&e.tapTree===void 0}const f_=Object.freeze(Object.defineProperty({__proto__:null,canAdd:u_,check:a_,decode:s_,encode:o_,expected:c_},Symbol.toStringTag,{value:"Module"})),l_=e=>[...Array(e).keys()],h_=e=>e.length===33&&[2,3].includes(e[0])||e.length===65&&e[0]===4;function Pl(e,t=h_){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 l_(c.value.length/4-1)){const l=Ls(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),nc(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 vg(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 d_=e=>e.length===32;function Ig(e){const t=Pl(e,d_);function n(o){const{numberValue:c,bytes:a}=Vs(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);fi(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 Og(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 Bg(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 Cl={unsignedTx:WE,globalXpub:KE,checkPubkey:Rl([])},St={nonWitnessUtxo:l2,partialSig:w2,sighashType:N2,finalScriptSig:QE,finalScriptWitness:s2,porCommitment:x2,witnessUtxo:i_,bip32Derivation:Pl(me.BIP32_DERIVATION),redeemScript:vg(me.REDEEM_SCRIPT),witnessScript:Bg(me.WITNESS_SCRIPT),checkPubkey:Rl([me.PARTIAL_SIG,me.BIP32_DERIVATION]),tapKeySig:U2,tapScriptSig:J2,tapLeafScript:V2,tapBip32Derivation:Ig(me.TAP_BIP32_DERIVATION),tapInternalKey:Og(me.TAP_INTERNAL_KEY),tapMerkleRoot:G2},mr={bip32Derivation:Pl(pt.BIP32_DERIVATION),redeemScript:vg(pt.REDEEM_SCRIPT),witnessScript:Bg(pt.WITNESS_SCRIPT),checkPubkey:Rl([pt.BIP32_DERIVATION]),tapBip32Derivation:Ig(pt.TAP_BIP32_DERIVATION),tapTree:f_,tapInternalKey:Og(pt.TAP_INTERNAL_KEY)},p_=Object.freeze(Object.defineProperty({__proto__:null,globals:Cl,inputs:St,outputs:mr},Symbol.toStringTag,{value:"Module"})),ya=e=>[...Array(e).keys()];function Id(e){const t=e.map(y_);return t.push(Uint8Array.from([0])),at(t)}function y_(e){const t=e.key.length,n=e.value.length,r=Bn(t),i=Bn(n),s=new Uint8Array(r+t+i+n);return fi(t,s,0),s.set(e.key,r),fi(n,s,r+t),s.set(e.value,r+t+i),s}function g_(e,t){let n=0;function r(){const{numberValue:E,bytes:S}=Vs(e,n);n+=S;const _=e.slice(n,n+Number(E));return n+=Number(E),_}function i(){const E=Ls(e,n,"BE");return n+=4,E}function s(){const E=Ir(e,n);return n+=1,E}function o(){const E=r(),S=r();return{key:E,value:S}}function c(){if(n>=e.length)throw new Error("Format Error: Unexpected End of PSBT");const E=Ir(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(),S=xe(E.key);if(u[S])throw new Error("Format Error: Keys must be unique for global keymap: key "+S);u[S]=1,a.push(E)}const f=a.filter(E=>E.key[0]===rr.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(S[T])throw new Error("Format Error: Keys must be unique for each input: input index "+E+" key "+T);S[T]=1,_.push(w)}g.push(_)}for(const E of ya(y)){const S={},_=[];for(;!c();){const w=o(),T=xe(w.key);if(S[T])throw new Error("Format Error: Keys must be unique for each output: output index "+E+" key "+T);S[T]=1,_.push(w)}m.push(_)}return Ng(l,{globalMapKeyVals:a,inputKeyVals:g,outputKeyVals:m})}function Dt(e,t,n){if(de(t,Uint8Array.from([n])))throw new Error(`Format Error: Invalid ${e} key: ${xe(t)}`)}function Ng(e,{globalMapKeyVals:t,inputKeyVals:n,outputKeyVals:r}){const i={unsignedTx:e};let s=0;for(const f of t)switch(f.key[0]){case rr.UNSIGNED_TX:if(Dt("global",f.key,rr.UNSIGNED_TX),s>0)throw new Error("Format Error: GlobalMap has multiple UNSIGNED_TX");s++;break;case rr.GLOBAL_XPUB:i.globalXpub===void 0&&(i.globalXpub=[]),i.globalXpub.push(Cl.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(St.checkPubkey(d),d.key[0]){case me.NON_WITNESS_UTXO:if(Dt("input",d.key,me.NON_WITNESS_UTXO),l.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");l.nonWitnessUtxo=St.nonWitnessUtxo.decode(d);break;case me.WITNESS_UTXO:if(Dt("input",d.key,me.WITNESS_UTXO),l.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");l.witnessUtxo=St.witnessUtxo.decode(d);break;case me.PARTIAL_SIG:l.partialSig===void 0&&(l.partialSig=[]),l.partialSig.push(St.partialSig.decode(d));break;case me.SIGHASH_TYPE:if(Dt("input",d.key,me.SIGHASH_TYPE),l.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");l.sighashType=St.sighashType.decode(d);break;case me.REDEEM_SCRIPT:if(Dt("input",d.key,me.REDEEM_SCRIPT),l.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");l.redeemScript=St.redeemScript.decode(d);break;case me.WITNESS_SCRIPT:if(Dt("input",d.key,me.WITNESS_SCRIPT),l.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");l.witnessScript=St.witnessScript.decode(d);break;case me.BIP32_DERIVATION:l.bip32Derivation===void 0&&(l.bip32Derivation=[]),l.bip32Derivation.push(St.bip32Derivation.decode(d));break;case me.FINAL_SCRIPTSIG:Dt("input",d.key,me.FINAL_SCRIPTSIG),l.finalScriptSig=St.finalScriptSig.decode(d);break;case me.FINAL_SCRIPTWITNESS:Dt("input",d.key,me.FINAL_SCRIPTWITNESS),l.finalScriptWitness=St.finalScriptWitness.decode(d);break;case me.POR_COMMITMENT:Dt("input",d.key,me.POR_COMMITMENT),l.porCommitment=St.porCommitment.decode(d);break;case me.TAP_KEY_SIG:Dt("input",d.key,me.TAP_KEY_SIG),l.tapKeySig=St.tapKeySig.decode(d);break;case me.TAP_SCRIPT_SIG:l.tapScriptSig===void 0&&(l.tapScriptSig=[]),l.tapScriptSig.push(St.tapScriptSig.decode(d));break;case me.TAP_LEAF_SCRIPT:l.tapLeafScript===void 0&&(l.tapLeafScript=[]),l.tapLeafScript.push(St.tapLeafScript.decode(d));break;case me.TAP_BIP32_DERIVATION:l.tapBip32Derivation===void 0&&(l.tapBip32Derivation=[]),l.tapBip32Derivation.push(St.tapBip32Derivation.decode(d));break;case me.TAP_INTERNAL_KEY:Dt("input",d.key,me.TAP_INTERNAL_KEY),l.tapInternalKey=St.tapInternalKey.decode(d);break;case me.TAP_MERKLE_ROOT:Dt("input",d.key,me.TAP_MERKLE_ROOT),l.tapMerkleRoot=St.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(mr.checkPubkey(d),d.key[0]){case pt.REDEEM_SCRIPT:if(Dt("output",d.key,pt.REDEEM_SCRIPT),l.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");l.redeemScript=mr.redeemScript.decode(d);break;case pt.WITNESS_SCRIPT:if(Dt("output",d.key,pt.WITNESS_SCRIPT),l.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");l.witnessScript=mr.witnessScript.decode(d);break;case pt.BIP32_DERIVATION:l.bip32Derivation===void 0&&(l.bip32Derivation=[]),l.bip32Derivation.push(mr.bip32Derivation.decode(d));break;case pt.TAP_INTERNAL_KEY:Dt("output",d.key,pt.TAP_INTERNAL_KEY),l.tapInternalKey=mr.tapInternalKey.decode(d);break;case pt.TAP_TREE:Dt("output",d.key,pt.TAP_TREE),l.tapTree=mr.tapTree.decode(d);break;case pt.TAP_BIP32_DERIVATION:l.tapBip32Derivation===void 0&&(l.tapBip32Derivation=[]),l.tapBip32Derivation.push(mr.tapBip32Derivation.decode(d));break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(d)}u.push(l)}return{globalMap:i,inputs:a,outputs:u}}function m_({globalMap:e,inputs:t,outputs:n}){const{globalKeyVals:r,inputKeyVals:i,outputKeyVals:s}=$f({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 w_=(e,t)=>de(e.key,t.key);function qu(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(w_)}function $f({globalMap:e,inputs:t,outputs:n}){return{globalKeyVals:qu(e,Cl),inputKeyVals:t.map(r=>qu(r,St)),outputKeyVals:n.map(r=>qu(r,mr))}}function b_(e){const t=e[0],n=$f(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=is(n.globalKeyVals),o=n.inputKeyVals.map(is),c=n.outputKeyVals.map(is);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=$f(a);is(f.globalKeyVals).forEach(Vu(s,n.globalKeyVals,f.globalKeyVals)),f.inputKeyVals.map(is).forEach((g,m)=>g.forEach(Vu(o[m],n.inputKeyVals[m],f.inputKeyVals[m]))),f.outputKeyVals.map(is).forEach((g,m)=>g.forEach(Vu(c[m],n.outputKeyVals[m],f.outputKeyVals[m])))}return Ng(i,{globalMapKeyVals:n.globalKeyVals,inputKeyVals:n.inputKeyVals,outputKeyVals:n.outputKeyVals})}function Vu(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 is(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 Ct(e,t){const n=e[t];if(n===void 0)throw new Error(`No input #${t}`);return n}function Oo(e,t){const n=e[t];if(n===void 0)throw new Error(`No output #${t}`);return n}function Du(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 $u(e){let t=0;return Object.keys(e).forEach(n=>{Number(isNaN(Number(n)))&&t++}),t}function E_(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 Ul(e){return(t,n)=>{for(const r of Object.keys(t)){const i=t[r],{canAdd:s,canAddToArray:o,check:c,expected:a}=p_[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 __=Ul("global"),kg=Ul("input"),Pg=Ul("output");function S_(e,t){const n=e.length-1,r=Ct(e,n);kg(t,r)}function T_(e,t){const n=e.length-1,r=Oo(e,n);Pg(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=Pr(t);return this.fromBuffer(r,n)}static fromBuffer(t,n){const r=g_(t,n),i=new this(r.globalMap.unsignedTx);return Object.assign(i,r),i}toBase64(){const t=this.toBuffer();return tb(t)}toHex(){const t=this.toBuffer();return xe(t)}toBuffer(){return m_(this)}updateGlobal(t){return __(t,this.globalMap),this}updateInput(t,n){const r=Ct(this.inputs,t);return kg(n,r),this}updateOutput(t,n){const r=Oo(this.outputs,t);return Pg(n,r),this}addUnknownKeyValToGlobal(t){return Du(t,this.globalMap.unknownKeyVals,$u(rr)),this.globalMap.unknownKeyVals||(this.globalMap.unknownKeyVals=[]),this.globalMap.unknownKeyVals.push(t),this}addUnknownKeyValToInput(t,n){const r=Ct(this.inputs,t);return Du(n,r.unknownKeyVals,$u(me)),r.unknownKeyVals||(r.unknownKeyVals=[]),r.unknownKeyVals.push(n),this}addUnknownKeyValToOutput(t,n){const r=Oo(this.outputs,t);return Du(n,r.unknownKeyVals,$u(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)),S_(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)),T_(this.outputs,t),this}clearFinalizedInput(t){const n=Ct(this.inputs,t);E_(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=b_([this].concat(t));return Object.assign(this,n),this}getTransaction(){return this.globalMap.unsignedTx.toBuffer()}};function zi(e){return t=>{try{return e({output:t}),!0}catch{return!1}}}const x_=zi(Ga),A_=zi(ng),v_=zi(sc),Ya=zi(za),kd=zi(ac),Rg=zi(oc),Cg=zi(uc);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)]),fi(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 Ug(e,t){const n=vr(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 Ug(e,t)!==-1}function I_(e,t){return O_(e).some(r=>Hg(r,_o.decode,t))}function Hg(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 O_(e){let t=[];if((e.partialSig||[]).length===0){if(!e.finalScriptSig&&!e.finalScriptWitness)return[];t=B_(e)}else t=e.partialSig;return t.map(n=>n.signature)}function B_(e){const t=e.finalScriptSig?lt(e.finalScriptSig)||[]:[],n=e.finalScriptWitness?lt(e.finalScriptWitness)||[]:[];return t.concat(n).filter(r=>r instanceof Uint8Array&&Or(r)).map(r=>({signature:r}))}const zc=e=>e.length===32?e:e.slice(1,33);function Pd(e,t,n){const r=$_(t,e,n);try{const s=V_(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 Nc(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&&Cg(e.witnessUtxo.script))}function ju(e,t){return e&&!!(e.tapInternalKey||e.tapTree||e.tapBip32Derivation&&e.tapBip32Derivation.length||t)}function Rd(e,t,n){M_(e,t,n),q_(e,t,n)}function Cd(e,t,n){L_(e,t,n),N_(e,t)}function N_(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=k_(n,r);if(i&&de(s,i)!==0)throw new Error("Error adding output. Script or address mismatch.")}}function k_(e,t){const n=t&&P_(t.leaves),{output:r}=uc({internalPubkey:e,scriptTree:n});return r}function P_(e=[]){return e.length===1&&e[0].depth===0?{output:e[0].script,version:e[0].leafVersion}:F_(e)}function R_(e,t){return U_(e).some(r=>Hg(r,C_,t))}function C_(e){return{signature:e.slice(0,64),hashType:e.slice(64)[0]||gt.SIGHASH_DEFAULT}}function U_(e){const t=[];if(e.tapKeySig&&t.push(e.tapKeySig),e.tapScriptSig&&t.push(...e.tapScriptSig.map(n=>n.signature)),!t.length){const n=H_(e.finalScriptWitness);n&&t.push(n)}return t}function H_(e){if(!e)return;const t=e.slice(2);if(t.length===64||t.length===65)return t}function F_(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>IE)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 M_(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 L_(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 q_(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=_r({output:e.script,version:e.leafVersion}),r=qf(e.controlBlock,n);return de(r,t)===0}function V_(e,t){const n=_r({output:t.script,version:t.leafVersion});return(e.tapScriptSig||[]).filter(r=>de(r.leafHash,n)===0).map(r=>D_(t.script,r)).sort((r,i)=>i.positionInScript-r.positionInScript).map(r=>r.signature)}function D_(e,t){return Object.assign({positionInScript:Ug(t.pubkey,e)},t)}function $_(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=>j_(i,e.tapScriptSig,n));if(!r)throw new Error(`Can not finalize taproot input #${t}. Signature for tapleaf script not found.`);return r}function j_(e,t,n){const r=_r({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 K_={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=Pr(t);return this.fromBuffer(r,n)}static fromBuffer(t,n={}){const r=Nd.fromBuffer(t,G_),i=new ma(n,r);return Z_(i.__CACHE.__TX,i.__CACHE),i}__CACHE;opts;constructor(t={},n=new Nd(new Fg)){this.data=n,this.opts=Object.assign({},K_,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=CE(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){kc(t),this.opts.maximumFeeRate=t}setVersion(t){kc(t),Qs(this.data.inputs,"setVersion");const n=this.__CACHE;return n.__TX.version=t,n.__EXTRACTED_TX=void 0,this}setLocktime(t){kc(t),Qs(this.data.inputs,"setLocktime");const n=this.__CACHE;return n.__TX.locktime=t,n.__EXTRACTED_TX=void 0,this}setInputSequence(t,n){kc(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];qg(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=Tg(n,i);t=Object.assign({},t,{script:s})}Cd(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(Mg))throw new Error("Not finalized");const n=this.__CACHE;if(t||X_(this,n,this.opts),n.__EXTRACTED_TX)return n.__EXTRACTED_TX;const r=n.__TX.clone();return Gg(this.data.inputs,r,n,!0),r}getFeeRate(){return Ld("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return Ld("__FEE","fee",this.data.inputs,this.__CACHE)}finalizeAllInputs(){return Ct(this.data.inputs,0),eo(this.data.inputs.length).forEach(t=>this.finalizeInput(t)),this}finalizeInput(t,n){const r=Ct(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=Ct(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=J_){const{script:i,isP2SH:s,isP2WSH:o,isSegwit:c}=nS(t,n,this.__CACHE);if(!i)throw new Error(`No script found for input #${t}`);z_(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=uc({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=Ct(this.data.inputs,t),r=Wg(t,n,this.__CACHE),i=Qa(r,t,"input",n.redeemScript||cS(n.finalScriptSig),n.witnessScript||aS(n.finalScriptWitness)),s=i.type==="raw"?"":i.type+"-",o=zg(i.meaningfulScript);return s+o}inputHasPubkey(t,n){const r=Ct(this.data.inputs,t);return sS(n,r,t,this.__CACHE)}inputHasHDKey(t,n){const r=Ct(this.data.inputs,t),i=Hd(n);return!!r.bip32Derivation&&r.bip32Derivation.some(i)}outputHasPubkey(t,n){const r=Oo(this.data.outputs,t);return oS(n,r,t,this.__CACHE)}outputHasHDKey(t,n){const r=Oo(this.data.outputs,t),i=Hd(n);return!!r.bip32Derivation&&r.bip32Derivation.some(i)}validateSignaturesOfAllInputs(t){return Ct(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=_o.decode(l.signature),{hash:y,script:g}=f!==d.hashType?Dg(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):eS(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,Vd(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,Vd(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 Dd(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=Dd(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=Ct(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=Ct(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}=qd(this.data.inputs,t,n.publicKey,this.__CACHE,r),o=[{pubkey:n.publicKey,signature:_o.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=>Nc(r.signSchnorr(u.hash),n.sighashType))[0],a=o.filter(u=>!!u.leafHash).map(u=>({pubkey:zc(r.publicKey),signature:Nc(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=Ct(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=Ct(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}=qd(this.data.inputs,t,n.publicKey,this.__CACHE,r);return Promise.resolve(n.sign(i)).then(o=>{const c=[{pubkey:n.publicKey,signature:_o.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:Nc(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:Nc(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 Cd(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 G_=e=>new Fg(e);class Fg{tx;constructor(t=Uint8Array.from([2,0,0,0,0,0,0,0,0,0])){this.tx=gt.fromBuffer(t),Y_(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(Pr(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 W_(e,t,n){switch(n){case"pubkey":case"pubkeyhash":case"witnesspubkeyhash":return Ud(1,e.partialSig);case"multisig":const r=Ga({output:t});return Ud(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 Ud(e,t,n){if(!t)return!1;let r;if(n?r=n.map(i=>{const s=uS(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 Mg(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 kc(e){if(typeof e!="number"||e!==Math.floor(e)||e>4294967295||e<0)throw new Error("Invalid 32 bit integer")}function X_(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)?R_(n,t):I_(n,t))throw new Error("Can not modify transaction, signatures exist.")})}function z_(e){if(!e.sighashType||!e.partialSig)return;const{partialSig:t,sighashType:n}=e;t.forEach(r=>{const{hashType:i}=_o.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 Y_(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 Z_(e,t){e.ins.forEach(n=>{qg(t,n)})}function qg(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 Vg(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=Vg(oc,"Redeem script"),Md=Vg(ac,"Witness script");function Ld(e,t,n,r){if(!n.every(Mg))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(),Gg(n,i,r,s),e==="__FEE_RATE")return r.__FEE_RATE;if(e==="__FEE")return r.__FEE}function J_(e,t,n,r,i,s){const o=zg(n);if(!W_(t,n,o))throw new Error(`Can not finalize input #${e}`);return Q_(n,o,t.partialSig,r,i,s)}function Q_(e,t,n,r,i,s){let o,c;const a=tS(e,t,n),u=s?ac({redeem:a}):null,f=i?oc({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 qd(e,t,n,r,i){const s=Ct(e,t),{hash:o,sighashType:c,script:a}=Dg(t,s,r,!1,i);return Lg(n,a,"sign"),{hash:o,sighashType:c}}function Dg(e,t,n,r,i){const s=n.__TX,o=t.sighashType||gt.SIGHASH_ALL;jg(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=sc({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
- *********************`),c=s.hashForSignature(e,u,o)}return{script:u,sighashType:o,hash:c}}function eS(e,t,n,r){const i=[];if(t.tapInternalKey){const o=$g(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 $g(e,t,n){const{script:r}=Hl(e,t,n);return Cg(r)?r.subarray(2,34):null}function Vd(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;jg(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=$g(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=_r({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 jg(e,t){if(t&&t.indexOf(e)<0){const n=iS(e);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${n}`)}}function tS(e,t,n){let r;switch(t){case"multisig":const i=rS(e,n);r=Ga({output:e,signatures:i});break;case"pubkey":r=ng({output:e,signature:n[0].signature});break;case"pubkeyhash":r=sc({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 nS(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 Dd(e,t,n){const r=Ct(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 rS(e,t){return Ga({output:e}).pubkeys.map(r=>(t.filter(i=>de(i.pubkey,r)===0)[0]||{}).signature).filter(r=>!!r)}function Kg(e){let t=0;function n(o){return t+=o,e.slice(t-o,t)}function r(){const o=qs(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 iS(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 Gg(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=Kg(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 Wg(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 sS(e,t,n,r){const i=Wg(n,t,r),{meaningfulScript:s}=Qa(i,n,"input",t.redeemScript,t.witnessScript);return Za(e,s)}function oS(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 cS(e){if(!e)return;const t=lt(e);if(!t)return;const n=t[t.length-1];if(!(!(n instanceof Uint8Array)||Xg(n)||fS(n)||!lt(n)))return n}function aS(e){if(!e)return;const t=Kg(e),n=t[t.length-1];if(!(Xg(n)||!lt(n)))return n}function uS(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 Xg(e){return e.length===33&&Bb(e)}function fS(e){return Or(e)}function Qa(e,t,n,r,i){const s=Rg(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)||Rg(e))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function zg(e){return Ya(e)?"witnesspubkeyhash":v_(e)?"pubkeyhash":x_(e)?"multisig":A_(e)?"pubkey":"nonstandard"}function Qs(e){return[...Array(e).keys()]}dE(G1);const Bs={Mainnet:"mainnet",Testnet:"testnet"},ba="abcdefghijklmnopqrstuvwxyz234567",Ns=Object.create(null);for(let e=0;e<ba.length;e++)Ns[ba[e]]=e;Ns[0]=Ns.o;Ns[1]=Ns.i;function lS(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 hS(e){let t=0,n=0;const r=new Uint8Array(e.length*4/3|0);let i=0;function s(o){let c=Ns[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 dS=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 pS(e){let t=-1;for(let n=0;n<e.length;n++){const i=(e[n]^t)&255;t=dS[i]^t>>>8}return(t^-1)>>>0}const Pc="__principal__",yS=2,$d=4,gS="aaaaa-aa";let Ge=class hs{static anonymous(){return new this(new Uint8Array([$d]))}static managementCanister(){return this.fromText(gS)}static selfAuthenticating(t){const n=sE(t);return new this(new Uint8Array([...n,yS]))}static from(t){if(typeof t=="string")return hs.fromText(t);if(Object.getPrototypeOf(t)===Uint8Array.prototype)return new hs(t);if(hs.isPrincipal(t))return new hs(t._arr);throw new Error(`Impossible to convert ${JSON.stringify(t)} to Principal.`)}static fromHex(t){return new this(ic(t))}static fromText(t){let n=t;if(t.includes(Pc)){const o=JSON.parse(t);Pc in o&&(n=o[Pc])}const r=n.toLowerCase().replace(/-/g,"");let i=hS(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 hs||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]===$d}toUint8Array(){return this._arr}toHex(){return rt(this._arr).toUpperCase()}toText(){const t=new ArrayBuffer(4);new DataView(t).setUint32(0,pS(this._arr));const r=new Uint8Array(t),i=new Uint8Array([...r,...this._arr]),o=lS(i).match(/.{1,5}/g);if(!o)throw new Error;return o.join("-")}toString(){return this.toText()}toJSON(){return{[Pc]: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 Ve(...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 Vs{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=Yg(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 Yg(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?Yg(e.buffer):new Uint8Array(e)}function mS(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 wS(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(e.buffer,e.byteOffset,e.byteLength)}function bS(e){const n=new TextEncoder().encode(e);let r=0;for(const i of n)r=(r*223+i)%2**32;return r}function on(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 bS(e)}function Zg(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 Jg(){throw new Error("unexpected end of buffer")}function Vi(e,t){return e.byteLength<t&&Jg(),e.read(t)}function Di(e){const t=e.readUint8();return t===void 0&&Jg(),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:Zg(e))+1,n=new Vs(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 Nt(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 It(e){typeof e=="number"&&(e=BigInt(e));const t=e<BigInt(0);t&&(e=-e-BigInt(1));const n=(e===BigInt(0)?0:Zg(e))+1,r=new Vs(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 ni(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 Nt(e);break}const r=new Uint8Array(Vi(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 ES(e,t){if(BigInt(e)<BigInt(0))throw new Error("Cannot write negative values.");return Qg(e,t)}function Qg(e,t){e=BigInt(e);const n=new Vs(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 em(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 _S(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let n=em(e,t);const r=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return n>=r&&(n-=r*BigInt(2)),n}var qe;(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"})(qe||(qe={}));const Yc="DIDL",jd=400;function Bo(e,t,n){return e.map((r,i)=>n(r,t[i]))}class SS{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=Ve(...this._typs);return Ve(t,n)}indexOf(t){if(!this._idx.has(t))throw new Error("Missing type index for "+t);return It(this._idx.get(t)||0)}}class TS{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 Ne;(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__"})(Ne||(Ne={}));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 di 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 Ne.EmptyClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 It(qe.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}}class tm extends eu{get typeName(){return Ne.UnknownClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 nm extends Rn{get typeName(){return Ne.BoolClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 It(qe.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 No extends Rn{get typeName(){return Ne.NullClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 It(qe.Null)}decodeValue(t,n){return this.checkType(n),null}get name(){return"null"}}class li extends Rn{get typeName(){return Ne.ReservedClass}static[Symbol.hasInstance](t){return t.typeName===Ne.ReservedClass}accept(t,n){return t.visitReserved(this,n)}covariant(t){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return It(qe.Reserved)}decodeValue(t,n){return n.name!==this.name&&n.decodeValue(t,n),null}get name(){return"reserved"}}class rm extends Rn{get typeName(){return Ne.TextClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 Ve(r,n)}encodeType(){return It(qe.Text)}decodeValue(t,n){this.checkType(n);const r=Nt(t),i=Vi(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 Ne.IntClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 It(t)}encodeType(){return It(qe.Int)}decodeValue(t,n){return this.checkType(n),ni(t)}get name(){return"int"}valueToString(t){return t.toString()}}class Ll extends Rn{get typeName(){return Ne.NatClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 It(qe.Nat)}decodeValue(t,n){return this.checkType(n),Nt(t)}get name(){return"nat"}valueToString(t){return t.toString()}}class ql extends Rn{get typeName(){return Ne.FloatClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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?qe.Float32:qe.Float64;return It(t)}decodeValue(t,n){this.checkType(n);const r=Vi(t,this._bits/8),i=wS(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 $i extends Rn{get typeName(){return Ne.FixedIntClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 Qg(t,this._bits/8)}encodeType(){const t=Math.log2(this._bits)-3;return It(-9-t)}decodeValue(t,n){this.checkType(n);const r=_S(t,this._bits/8);return this._bits<=32?Number(r):r}get name(){return`int${this._bits}`}valueToString(t){return t.toString()}}class ci extends Rn{get typeName(){return Ne.FixedNatClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 ES(t,this._bits/8)}encodeType(){const t=Math.log2(this._bits)-3;return It(-5-t)}decodeValue(t,n){this.checkType(n);const r=em(t,this._bits/8);return this._bits<=32?Number(r):r}get name(){return`nat${this._bits}`}valueToString(t){return t.toString()}}class ks extends di{get typeName(){return Ne.VecClass}static[Symbol.hasInstance](t){return t.typeName===Ne.VecClass}constructor(t){super(),this._type=t,this._blobOptimization=!1,t instanceof ci&&t._bits===8&&(this._blobOptimization=!0)}accept(t,n){return t.visitVec(this,this._type,n)}covariant(t){const n=this._type instanceof ci?this._type._bits:this._type instanceof $i?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:
12
+ *********************`),c=s.hashForSignature(e,u,o)}return{script:u,sighashType:o,hash:c}}function eS(e,t,n,r){const i=[];if(t.tapInternalKey){const o=$g(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 $g(e,t,n){const{script:r}=Hl(e,t,n);return Cg(r)?r.subarray(2,34):null}function Vd(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;jg(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=$g(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=_r({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 jg(e,t){if(t&&t.indexOf(e)<0){const n=iS(e);throw new Error(`Sighash type is not allowed. Retry the sign method passing the sighashTypes array of whitelisted types. Sighash type: ${n}`)}}function tS(e,t,n){let r;switch(t){case"multisig":const i=rS(e,n);r=Ga({output:e,signatures:i});break;case"pubkey":r=ng({output:e,signature:n[0].signature});break;case"pubkeyhash":r=sc({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 nS(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 Dd(e,t,n){const r=Ct(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 rS(e,t){return Ga({output:e}).pubkeys.map(r=>(t.filter(i=>de(i.pubkey,r)===0)[0]||{}).signature).filter(r=>!!r)}function Kg(e){let t=0;function n(o){return t+=o,e.slice(t-o,t)}function r(){const o=Vs(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 iS(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 Gg(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=Kg(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 Wg(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 sS(e,t,n,r){const i=Wg(n,t,r),{meaningfulScript:s}=Qa(i,n,"input",t.redeemScript,t.witnessScript);return Za(e,s)}function oS(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 cS(e){if(!e)return;const t=lt(e);if(!t)return;const n=t[t.length-1];if(!(!(n instanceof Uint8Array)||Xg(n)||fS(n)||!lt(n)))return n}function aS(e){if(!e)return;const t=Kg(e),n=t[t.length-1];if(!(Xg(n)||!lt(n)))return n}function uS(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 Xg(e){return e.length===33&&Bb(e)}function fS(e){return Or(e)}function Qa(e,t,n,r,i){const s=Rg(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)||Rg(e))throw new Error("P2WPKH or P2SH can not be contained within P2WSH")}function zg(e){return Ya(e)?"witnesspubkeyhash":v_(e)?"pubkeyhash":x_(e)?"multisig":A_(e)?"pubkey":"nonstandard"}function eo(e){return[...Array(e).keys()]}dE(G1);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 lS(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 hS(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 dS=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 pS(e){let t=-1;for(let n=0;n<e.length;n++){const i=(e[n]^t)&255;t=dS[i]^t>>>8}return(t^-1)>>>0}const Pc="__principal__",yS=2,$d=4,gS="aaaaa-aa";let Ge=class hs{static anonymous(){return new this(new Uint8Array([$d]))}static managementCanister(){return this.fromText(gS)}static selfAuthenticating(t){const n=sE(t);return new this(new Uint8Array([...n,yS]))}static from(t){if(typeof t=="string")return hs.fromText(t);if(Object.getPrototypeOf(t)===Uint8Array.prototype)return new hs(t);if(hs.isPrincipal(t))return new hs(t._arr);throw new Error(`Impossible to convert ${JSON.stringify(t)} to Principal.`)}static fromHex(t){return new this(ic(t))}static fromText(t){let n=t;if(t.includes(Pc)){const o=JSON.parse(t);Pc in o&&(n=o[Pc])}const r=n.toLowerCase().replace(/-/g,"");let i=hS(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 hs||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]===$d}toUint8Array(){return this._arr}toHex(){return rt(this._arr).toUpperCase()}toText(){const t=new ArrayBuffer(4);new DataView(t).setUint32(0,pS(this._arr));const r=new Uint8Array(t),i=new Uint8Array([...r,...this._arr]),o=lS(i).match(/.{1,5}/g);if(!o)throw new Error;return o.join("-")}toString(){return this.toText()}toJSON(){return{[Pc]: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 Ve(...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 Ds{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=Yg(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 Yg(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?Yg(e.buffer):new Uint8Array(e)}function mS(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 wS(e){if(!(e instanceof Uint8Array))throw new Error("Input must be a Uint8Array");return new DataView(e.buffer,e.byteOffset,e.byteLength)}function bS(e){const n=new TextEncoder().encode(e);let r=0;for(const i of n)r=(r*223+i)%2**32;return r}function cn(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 bS(e)}function Zg(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 Jg(){throw new Error("unexpected end of buffer")}function Vi(e,t){return e.byteLength<t&&Jg(),e.read(t)}function Di(e){const t=e.readUint8();return t===void 0&&Jg(),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:Zg(e))+1,n=new Ds(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 Nt(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 It(e){typeof e=="number"&&(e=BigInt(e));const t=e<BigInt(0);t&&(e=-e-BigInt(1));const n=(e===BigInt(0)?0:Zg(e))+1,r=new Ds(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 ni(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 Nt(e);break}const r=new Uint8Array(Vi(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 ES(e,t){if(BigInt(e)<BigInt(0))throw new Error("Cannot write negative values.");return Qg(e,t)}function Qg(e,t){e=BigInt(e);const n=new Ds(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 em(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 _S(e,t){if(t<=0||!Number.isInteger(t))throw new Error("Byte length must be a positive integer");let n=em(e,t);const r=BigInt(2)**(BigInt(8)*BigInt(t-1)+BigInt(7));return n>=r&&(n-=r*BigInt(2)),n}var qe;(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"})(qe||(qe={}));const Yc="DIDL",jd=400;function Bo(e,t,n){return e.map((r,i)=>n(r,t[i]))}class SS{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=Ve(...this._typs);return Ve(t,n)}indexOf(t){if(!this._idx.has(t))throw new Error("Missing type index for "+t);return It(this._idx.get(t)||0)}}class TS{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 Ne;(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__"})(Ne||(Ne={}));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 di 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 Ne.EmptyClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 It(qe.Empty)}decodeValue(){throw new Error("Empty cannot appear as an output")}get name(){return"empty"}}class tm extends eu{get typeName(){return Ne.UnknownClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 nm extends Rn{get typeName(){return Ne.BoolClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 It(qe.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 No extends Rn{get typeName(){return Ne.NullClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 It(qe.Null)}decodeValue(t,n){return this.checkType(n),null}get name(){return"null"}}class li extends Rn{get typeName(){return Ne.ReservedClass}static[Symbol.hasInstance](t){return t.typeName===Ne.ReservedClass}accept(t,n){return t.visitReserved(this,n)}covariant(t){return!0}encodeValue(){return new Uint8Array(0)}encodeType(){return It(qe.Reserved)}decodeValue(t,n){return n.name!==this.name&&n.decodeValue(t,n),null}get name(){return"reserved"}}class rm extends Rn{get typeName(){return Ne.TextClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 Ve(r,n)}encodeType(){return It(qe.Text)}decodeValue(t,n){this.checkType(n);const r=Nt(t),i=Vi(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 Ne.IntClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 It(t)}encodeType(){return It(qe.Int)}decodeValue(t,n){return this.checkType(n),ni(t)}get name(){return"int"}valueToString(t){return t.toString()}}class Ll extends Rn{get typeName(){return Ne.NatClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 It(qe.Nat)}decodeValue(t,n){return this.checkType(n),Nt(t)}get name(){return"nat"}valueToString(t){return t.toString()}}class ql extends Rn{get typeName(){return Ne.FloatClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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?qe.Float32:qe.Float64;return It(t)}decodeValue(t,n){this.checkType(n);const r=Vi(t,this._bits/8),i=wS(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 $i extends Rn{get typeName(){return Ne.FixedIntClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 Qg(t,this._bits/8)}encodeType(){const t=Math.log2(this._bits)-3;return It(-9-t)}decodeValue(t,n){this.checkType(n);const r=_S(t,this._bits/8);return this._bits<=32?Number(r):r}get name(){return`int${this._bits}`}valueToString(t){return t.toString()}}class ci extends Rn{get typeName(){return Ne.FixedNatClass}static[Symbol.hasInstance](t){return t.typeName===Ne.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 ES(t,this._bits/8)}encodeType(){const t=Math.log2(this._bits)-3;return It(-5-t)}decodeValue(t,n){this.checkType(n);const r=em(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 di{get typeName(){return Ne.VecClass}static[Symbol.hasInstance](t){return t.typeName===Ne.VecClass}constructor(t){super(),this._type=t,this._blobOptimization=!1,t instanceof ci&&t._bits===8&&(this._blobOptimization=!0)}accept(t,n){return t.visitVec(this,this._type,n)}covariant(t){const n=this._type instanceof ci?this._type._bits:this._type instanceof $i?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:
13
13
 
14
- index ${i} -> ${s.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=ft(t.length);if(this._blobOptimization)return Ve(n,new Uint8Array(t));if(ArrayBuffer.isView(t))if(t instanceof Int16Array||t instanceof Uint16Array){const i=new DataView(new ArrayBuffer(t.length*2));for(let s=0;s<t.length;s++)t instanceof Int16Array?i.setInt16(s*2,t[s],!0):i.setUint16(s*2,t[s],!0);return Ve(n,new Uint8Array(i.buffer))}else if(t instanceof Int32Array||t instanceof Uint32Array){const i=new DataView(new ArrayBuffer(t.length*4));for(let s=0;s<t.length;s++)t instanceof Int32Array?i.setInt32(s*4,t[s],!0):i.setUint32(s*4,t[s],!0);return Ve(n,new Uint8Array(i.buffer))}else if(t instanceof BigInt64Array||t instanceof BigUint64Array){const i=new DataView(new ArrayBuffer(t.length*8));for(let s=0;s<t.length;s++)t instanceof BigInt64Array?i.setBigInt64(s*8,t[s],!0):i.setBigUint64(s*8,t[s],!0);return Ve(n,new Uint8Array(i.buffer))}else return Ve(n,new Uint8Array(t.buffer,t.byteOffset,t.byteLength));const r=new Vs(new Uint8Array(n.byteLength+t.length),0);r.write(n);for(const i of t){const s=this._type.encodeValue(i);r.write(new Uint8Array(s))}return r.buffer}_buildTypeTableImpl(t){this._type.buildTypeTable(t);const n=It(qe.Vector),r=this._type.encodeType(t);t.add(this,Ve(n,r))}decodeValue(t,n){const r=this.checkType(n);if(!(r instanceof ks))throw new Error("Not a vector type");const i=Number(Nt(t));if(this._type instanceof ci){if(this._type._bits==8)return new Uint8Array(t.read(i));if(this._type._bits==16){const o=t.read(i*2);return new Uint16Array(o.buffer,o.byteOffset,i)}if(this._type._bits==32){const o=t.read(i*4);return new Uint32Array(o.buffer,o.byteOffset,i)}if(this._type._bits==64)return new BigUint64Array(t.read(i*8).buffer)}if(this._type instanceof $i){if(this._type._bits==8)return new Int8Array(t.read(i));if(this._type._bits==16){const o=t.read(i*2),c=new DataView(o.buffer,o.byteOffset,o.byteLength),a=new Int16Array(i);for(let u=0;u<i;u++)a[u]=c.getInt16(u*2,!0);return a}if(this._type._bits==32){const o=t.read(i*4),c=new DataView(o.buffer,o.byteOffset,o.byteLength),a=new Int32Array(i);for(let u=0;u<i;u++)a[u]=c.getInt32(u*4,!0);return a}if(this._type._bits==64){const o=t.read(i*8),c=new DataView(o.buffer,o.byteOffset,o.byteLength),a=new BigInt64Array(i);for(let u=0;u<i;u++)a[u]=c.getBigInt64(u*8,!0);return a}}const s=[];for(let o=0;o<i;o++)s.push(this._type.decodeValue(t,r._type));return s}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(t){return"vec {"+t.map(r=>this._type.valueToString(r)).join("; ")+"}"}}class Br extends di{get typeName(){return Ne.OptClass}static[Symbol.hasInstance](t){return t.typeName===Ne.OptClass}constructor(t){super(),this._type=t}accept(t,n){return t.visitOpt(this,this._type,n)}covariant(t){try{if(Array.isArray(t)&&(t.length===0||t.length===1&&this._type.covariant(t[0])))return!0}catch(n){throw new Error(`Invalid ${this.display()} argument: ${wt(t)}
14
+ index ${i} -> ${s.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=ft(t.length);if(this._blobOptimization)return Ve(n,new Uint8Array(t));if(ArrayBuffer.isView(t))if(t instanceof Int16Array||t instanceof Uint16Array){const i=new DataView(new ArrayBuffer(t.length*2));for(let s=0;s<t.length;s++)t instanceof Int16Array?i.setInt16(s*2,t[s],!0):i.setUint16(s*2,t[s],!0);return Ve(n,new Uint8Array(i.buffer))}else if(t instanceof Int32Array||t instanceof Uint32Array){const i=new DataView(new ArrayBuffer(t.length*4));for(let s=0;s<t.length;s++)t instanceof Int32Array?i.setInt32(s*4,t[s],!0):i.setUint32(s*4,t[s],!0);return Ve(n,new Uint8Array(i.buffer))}else if(t instanceof BigInt64Array||t instanceof BigUint64Array){const i=new DataView(new ArrayBuffer(t.length*8));for(let s=0;s<t.length;s++)t instanceof BigInt64Array?i.setBigInt64(s*8,t[s],!0):i.setBigUint64(s*8,t[s],!0);return Ve(n,new Uint8Array(i.buffer))}else return Ve(n,new Uint8Array(t.buffer,t.byteOffset,t.byteLength));const r=new Ds(new Uint8Array(n.byteLength+t.length),0);r.write(n);for(const i of t){const s=this._type.encodeValue(i);r.write(new Uint8Array(s))}return r.buffer}_buildTypeTableImpl(t){this._type.buildTypeTable(t);const n=It(qe.Vector),r=this._type.encodeType(t);t.add(this,Ve(n,r))}decodeValue(t,n){const r=this.checkType(n);if(!(r instanceof Ps))throw new Error("Not a vector type");const i=Number(Nt(t));if(this._type instanceof ci){if(this._type._bits==8)return new Uint8Array(t.read(i));if(this._type._bits==16){const o=t.read(i*2);return new Uint16Array(o.buffer,o.byteOffset,i)}if(this._type._bits==32){const o=t.read(i*4);return new Uint32Array(o.buffer,o.byteOffset,i)}if(this._type._bits==64)return new BigUint64Array(t.read(i*8).buffer)}if(this._type instanceof $i){if(this._type._bits==8)return new Int8Array(t.read(i));if(this._type._bits==16){const o=t.read(i*2),c=new DataView(o.buffer,o.byteOffset,o.byteLength),a=new Int16Array(i);for(let u=0;u<i;u++)a[u]=c.getInt16(u*2,!0);return a}if(this._type._bits==32){const o=t.read(i*4),c=new DataView(o.buffer,o.byteOffset,o.byteLength),a=new Int32Array(i);for(let u=0;u<i;u++)a[u]=c.getInt32(u*4,!0);return a}if(this._type._bits==64){const o=t.read(i*8),c=new DataView(o.buffer,o.byteOffset,o.byteLength),a=new BigInt64Array(i);for(let u=0;u<i;u++)a[u]=c.getBigInt64(u*8,!0);return a}}const s=[];for(let o=0;o<i;o++)s.push(this._type.decodeValue(t,r._type));return s}get name(){return`vec ${this._type.name}`}display(){return`vec ${this._type.display()}`}valueToString(t){return"vec {"+t.map(r=>this._type.valueToString(r)).join("; ")+"}"}}class Br extends di{get typeName(){return Ne.OptClass}static[Symbol.hasInstance](t){return t.typeName===Ne.OptClass}constructor(t){super(),this._type=t}accept(t,n){return t.visitOpt(this,this._type,n)}covariant(t){try{if(Array.isArray(t)&&(t.length===0||t.length===1&&this._type.covariant(t[0])))return!0}catch(n){throw new Error(`Invalid ${this.display()} argument: ${wt(t)}
15
15
 
16
- -> ${n.message}`)}throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){return t.length===0?new Uint8Array([0]):Ve(new Uint8Array([1]),this._type.encodeValue(t[0]))}_buildTypeTableImpl(t){this._type.buildTypeTable(t);const n=It(qe.Opt),r=this._type.encodeType(t);t.add(this,Ve(n,r))}decodeValue(t,n){if(n instanceof No)return[];if(n instanceof li)return[];let r=n;if(n instanceof Nn){const i=n.getType();if(typeof i>"u")throw new Error("type mismatch with uninitialized type");r=i}if(r instanceof Br)switch(Di(t)){case 0:return[];case 1:{const i=t.save();try{return[this._type.decodeValue(t,r._type)]}catch{return t.restore(i),r._type.decodeValue(t,r._type),[]}}default:throw new Error("Not an option value")}else{if(this._type instanceof No||this._type instanceof Br||this._type instanceof li)return r.decodeValue(t,r),[];{const i=t.save();try{return[this._type.decodeValue(t,n)]}catch{return t.restore(i),r.decodeValue(t,n),[]}}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(t){return t.length===0?"null":`opt ${this._type.valueToString(t[0])}`}}class ji extends di{get typeName(){return Ne.RecordClass}static[Symbol.hasInstance](t){return t.typeName===Ne.RecordClass||t.typeName===Ne.TupleClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((n,r)=>on(n[0])-on(r[0]))}accept(t,n){return t.visitRecord(this,this._fields,n)}tryAsTuple(){const t=[];for(let n=0;n<this._fields.length;n++){const[r,i]=this._fields[n];if(r!==`_${n}_`)return null;t.push(i)}return t}covariant(t){if(typeof t=="object"&&this._fields.every(([n,r])=>{if(!t.hasOwnProperty(n))throw new Error(`Record is missing key "${n}".`);try{return r.covariant(t[n])}catch(i){throw new Error(`Invalid ${this.display()} argument:
16
+ -> ${n.message}`)}throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){return t.length===0?new Uint8Array([0]):Ve(new Uint8Array([1]),this._type.encodeValue(t[0]))}_buildTypeTableImpl(t){this._type.buildTypeTable(t);const n=It(qe.Opt),r=this._type.encodeType(t);t.add(this,Ve(n,r))}decodeValue(t,n){if(n instanceof No)return[];if(n instanceof li)return[];let r=n;if(n instanceof Nn){const i=n.getType();if(typeof i>"u")throw new Error("type mismatch with uninitialized type");r=i}if(r instanceof Br)switch(Di(t)){case 0:return[];case 1:{const i=t.save();try{return[this._type.decodeValue(t,r._type)]}catch{return t.restore(i),r._type.decodeValue(t,r._type),[]}}default:throw new Error("Not an option value")}else{if(this._type instanceof No||this._type instanceof Br||this._type instanceof li)return r.decodeValue(t,r),[];{const i=t.save();try{return[this._type.decodeValue(t,n)]}catch{return t.restore(i),r.decodeValue(t,n),[]}}}}get name(){return`opt ${this._type.name}`}display(){return`opt ${this._type.display()}`}valueToString(t){return t.length===0?"null":`opt ${this._type.valueToString(t[0])}`}}class ji extends di{get typeName(){return Ne.RecordClass}static[Symbol.hasInstance](t){return t.typeName===Ne.RecordClass||t.typeName===Ne.TupleClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((n,r)=>cn(n[0])-cn(r[0]))}accept(t,n){return t.visitRecord(this,this._fields,n)}tryAsTuple(){const t=[];for(let n=0;n<this._fields.length;n++){const[r,i]=this._fields[n];if(r!==`_${n}_`)return null;t.push(i)}return t}covariant(t){if(typeof t=="object"&&this._fields.every(([n,r])=>{if(!t.hasOwnProperty(n))throw new Error(`Record is missing key "${n}".`);try{return r.covariant(t[n])}catch(i){throw new Error(`Invalid ${this.display()} argument:
17
17
 
18
- field ${n} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=this._fields.map(([i])=>t[i]),r=Bo(this._fields,n,([,i],s)=>i.encodeValue(s));return Ve(...r)}_buildTypeTableImpl(t){this._fields.forEach(([s,o])=>o.buildTypeTable(t));const n=It(qe.Record),r=ft(this._fields.length),i=this._fields.map(([s,o])=>Ve(ft(on(s)),o.encodeType(t)));t.add(this,Ve(n,r,Ve(...i)))}decodeValue(t,n){const r=this.checkType(n);if(!(r instanceof ji))throw new Error("Not a record type");const i={};let s=0,o=0;for(;o<r._fields.length;){const[c,a]=r._fields[o];if(s>=this._fields.length){a.decodeValue(t,a),o++;continue}const[u,f]=this._fields[s],l=on(this._fields[s][0]),d=on(c);if(l===d)i[u]=f.decodeValue(t,a),s++,o++;else if(d>l)if(f instanceof Br||f instanceof li)i[u]=[],s++;else throw new Error("Cannot find required field "+u);else a.decodeValue(t,a),o++}for(const[c,a]of this._fields.slice(s))if(a instanceof Br||a instanceof li)i[c]=[];else throw new Error("Cannot find required field "+c);return i}get fieldsAsObject(){const t={};for(const[n,r]of this._fields)t[on(n)]=r;return t}get name(){return`record {${this._fields.map(([n,r])=>n+":"+r.name).join("; ")}}`}display(){return`record {${this._fields.map(([n,r])=>n+":"+r.display()).join("; ")}}`}valueToString(t){const n=this._fields.map(([i])=>t[i]);return`record {${Bo(this._fields,n,([i,s],o)=>i+"="+s.valueToString(o)).join("; ")}}`}}class tu extends ji{get typeName(){return Ne.TupleClass}static[Symbol.hasInstance](t){return t.typeName===Ne.TupleClass}constructor(t){const n={};t.forEach((r,i)=>n["_"+i+"_"]=r),super(n),this._components=t}accept(t,n){return t.visitTuple(this,this._components,n)}covariant(t){if(Array.isArray(t)&&t.length>=this._fields.length&&this._components.every((n,r)=>{try{return n.covariant(t[r])}catch(i){throw new Error(`Invalid ${this.display()} argument:
18
+ field ${n} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=this._fields.map(([i])=>t[i]),r=Bo(this._fields,n,([,i],s)=>i.encodeValue(s));return Ve(...r)}_buildTypeTableImpl(t){this._fields.forEach(([s,o])=>o.buildTypeTable(t));const n=It(qe.Record),r=ft(this._fields.length),i=this._fields.map(([s,o])=>Ve(ft(cn(s)),o.encodeType(t)));t.add(this,Ve(n,r,Ve(...i)))}decodeValue(t,n){const r=this.checkType(n);if(!(r instanceof ji))throw new Error("Not a record type");const i={};let s=0,o=0;for(;o<r._fields.length;){const[c,a]=r._fields[o];if(s>=this._fields.length){a.decodeValue(t,a),o++;continue}const[u,f]=this._fields[s],l=cn(this._fields[s][0]),d=cn(c);if(l===d)i[u]=f.decodeValue(t,a),s++,o++;else if(d>l)if(f instanceof Br||f instanceof li)i[u]=[],s++;else throw new Error("Cannot find required field "+u);else a.decodeValue(t,a),o++}for(const[c,a]of this._fields.slice(s))if(a instanceof Br||a instanceof li)i[c]=[];else throw new Error("Cannot find required field "+c);return i}get fieldsAsObject(){const t={};for(const[n,r]of this._fields)t[cn(n)]=r;return t}get name(){return`record {${this._fields.map(([n,r])=>n+":"+r.name).join("; ")}}`}display(){return`record {${this._fields.map(([n,r])=>n+":"+r.display()).join("; ")}}`}valueToString(t){const n=this._fields.map(([i])=>t[i]);return`record {${Bo(this._fields,n,([i,s],o)=>i+"="+s.valueToString(o)).join("; ")}}`}}class tu extends ji{get typeName(){return Ne.TupleClass}static[Symbol.hasInstance](t){return t.typeName===Ne.TupleClass}constructor(t){const n={};t.forEach((r,i)=>n["_"+i+"_"]=r),super(n),this._components=t}accept(t,n){return t.visitTuple(this,this._components,n)}covariant(t){if(Array.isArray(t)&&t.length>=this._fields.length&&this._components.every((n,r)=>{try{return n.covariant(t[r])}catch(i){throw new Error(`Invalid ${this.display()} argument:
19
19
 
20
- index ${r} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=Bo(this._components,t,(r,i)=>r.encodeValue(i));return Ve(...n)}decodeValue(t,n){const r=this.checkType(n);if(!(r instanceof tu))throw new Error("not a tuple type");if(r._components.length<this._components.length)throw new Error("tuple mismatch");const i=[];for(const[s,o]of r._components.entries())s>=this._components.length?o.decodeValue(t,o):i.push(this._components[s].decodeValue(t,o));return i}display(){return`record {${this._components.map(n=>n.display()).join("; ")}}`}valueToString(t){return`record {${Bo(this._components,t,(r,i)=>r.valueToString(i)).join("; ")}}`}}class Ps extends di{get typeName(){return Ne.VariantClass}static[Symbol.hasInstance](t){return t.typeName===Ne.VariantClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((n,r)=>on(n[0])-on(r[0]))}accept(t,n){return t.visitVariant(this,this._fields,n)}covariant(t){if(typeof t=="object"&&Object.entries(t).length===1&&this._fields.every(([n,r])=>{try{return!t.hasOwnProperty(n)||r.covariant(t[n])}catch(i){throw new Error(`Invalid ${this.display()} argument:
20
+ index ${r} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=Bo(this._components,t,(r,i)=>r.encodeValue(i));return Ve(...n)}decodeValue(t,n){const r=this.checkType(n);if(!(r instanceof tu))throw new Error("not a tuple type");if(r._components.length<this._components.length)throw new Error("tuple mismatch");const i=[];for(const[s,o]of r._components.entries())s>=this._components.length?o.decodeValue(t,o):i.push(this._components[s].decodeValue(t,o));return i}display(){return`record {${this._components.map(n=>n.display()).join("; ")}}`}valueToString(t){return`record {${Bo(this._components,t,(r,i)=>r.valueToString(i)).join("; ")}}`}}class Rs extends di{get typeName(){return Ne.VariantClass}static[Symbol.hasInstance](t){return t.typeName===Ne.VariantClass}constructor(t={}){super(),this._fields=Object.entries(t).sort((n,r)=>cn(n[0])-cn(r[0]))}accept(t,n){return t.visitVariant(this,this._fields,n)}covariant(t){if(typeof t=="object"&&Object.entries(t).length===1&&this._fields.every(([n,r])=>{try{return!t.hasOwnProperty(n)||r.covariant(t[n])}catch(i){throw new Error(`Invalid ${this.display()} argument:
21
21
 
22
- variant ${n} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){for(let n=0;n<this._fields.length;n++){const[r,i]=this._fields[n];if(t.hasOwnProperty(r)){const s=ft(n),o=i.encodeValue(t[r]);return Ve(s,o)}}throw Error("Variant has no data: "+t)}_buildTypeTableImpl(t){this._fields.forEach(([,s])=>{s.buildTypeTable(t)});const n=It(qe.Variant),r=ft(this._fields.length),i=this._fields.map(([s,o])=>Ve(ft(on(s)),o.encodeType(t)));t.add(this,Ve(n,r,...i))}decodeValue(t,n){const r=this.checkType(n);if(!(r instanceof Ps))throw new Error("Not a variant type");const i=Number(Nt(t));if(i>=r._fields.length)throw Error("Invalid variant index: "+i);const[s,o]=r._fields[i];for(const[c,a]of this._fields)if(on(s)===on(c)){const u=a.decodeValue(t,o);return{[c]:u}}throw new Error("Cannot find field hash "+s)}get name(){return`variant {${this._fields.map(([n,r])=>n+":"+r.name).join("; ")}}`}display(){return`variant {${this._fields.map(([n,r])=>n+(r.name==="null"?"":`:${r.display()}`)).join("; ")}}`}valueToString(t){for(const[n,r]of this._fields)if(t.hasOwnProperty(n)){const i=r.valueToString(t[n]);return i==="null"?`variant {${n}}`:`variant {${n}=${i}}`}throw new Error("Variant has no data: "+t)}get alternativesAsObject(){const t={};for(const[n,r]of this._fields)t[on(n)]=r;return t}}const qa=class qa extends di{constructor(){super(...arguments),this._id=qa._counter++}get typeName(){return Ne.RecClass}static[Symbol.hasInstance](t){return t.typeName===Ne.RecClass}accept(t,n){if(!this._type)throw Error("Recursive type uninitialized.");return t.visitRec(this,this._type,n)}fill(t){this._type=t}getType(){return this._type}covariant(t){if(this._type&&this._type.covariant(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.encodeValue(t)}_buildTypeTableImpl(t){if(!this._type)throw Error("Recursive type uninitialized.");t.add(this,new Uint8Array([])),this._type.buildTypeTable(t),t.merge(this,this._type.name)}decodeValue(t,n){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.decodeValue(t,n)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error("Recursive type uninitialized.");return`μ${this.name}.${this._type.name}`}valueToString(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.valueToString(t)}};qa._counter=0;let Nn=qa;function Vl(e){if(Di(e)!==1)throw new Error("Cannot decode principal");const n=Number(Nt(e));return Ge.fromUint8Array(new Uint8Array(Vi(e,n)))}class im extends Rn{get typeName(){return Ne.PrincipalClass}static[Symbol.hasInstance](t){return t.typeName===Ne.PrincipalClass}accept(t,n){return t.visitPrincipal(this,n)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=t.toUint8Array(),r=ft(n.byteLength);return Ve(new Uint8Array([1]),r,n)}encodeType(){return It(qe.Principal)}decodeValue(t,n){return this.checkType(n),Vl(t)}get name(){return"principal"}valueToString(t){return`${this.name} "${t.toText()}"`}}class ko extends di{get typeName(){return Ne.FuncClass}static[Symbol.hasInstance](t){return t.typeName===Ne.FuncClass}static argsToString(t,n){if(t.length!==n.length)throw new Error("arity mismatch");return"("+t.map((r,i)=>r.valueToString(n[i])).join(", ")+")"}constructor(t,n,r=[]){super(),this.argTypes=t,this.retTypes=n,this.annotations=r}accept(t,n){return t.visitFunc(this,n)}covariant(t){if(Array.isArray(t)&&t.length===2&&t[0]&&t[0]._isPrincipal&&typeof t[1]=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue([t,n]){const r=t.toUint8Array(),i=ft(r.byteLength),s=Ve(new Uint8Array([1]),i,r),o=new TextEncoder().encode(n),c=ft(o.byteLength);return Ve(new Uint8Array([1]),s,c,o)}_buildTypeTableImpl(t){this.argTypes.forEach(u=>u.buildTypeTable(t)),this.retTypes.forEach(u=>u.buildTypeTable(t));const n=It(qe.Func),r=ft(this.argTypes.length),i=Ve(...this.argTypes.map(u=>u.encodeType(t))),s=ft(this.retTypes.length),o=Ve(...this.retTypes.map(u=>u.encodeType(t))),c=ft(this.annotations.length),a=Ve(...this.annotations.map(u=>this.encodeAnnotation(u)));t.add(this,Ve(n,r,i,s,o,c,a))}decodeValue(t,n){const r=n instanceof Nn?n.getType()??n:n;if(!Dl(r,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${r.display()}`);if(Di(t)!==1)throw new Error("Cannot decode function reference");const s=Vl(t),o=Number(Nt(t)),c=Vi(t,o),u=new TextDecoder("utf8",{fatal:!0}).decode(c);return[s,u]}get name(){const t=this.argTypes.map(i=>i.name).join(", "),n=this.retTypes.map(i=>i.name).join(", "),r=" "+this.annotations.join(" ");return`(${t}) -> (${n})${r}`}valueToString([t,n]){return`func "${t.toText()}".${n}`}display(){const t=this.argTypes.map(i=>i.display()).join(", "),n=this.retTypes.map(i=>i.display()).join(", "),r=" "+this.annotations.join(" ");return`(${t}) → (${n})${r}`}encodeAnnotation(t){if(t==="query")return new Uint8Array([1]);if(t==="oneway")return new Uint8Array([2]);if(t==="composite_query")return new Uint8Array([3]);throw new Error("Illegal function annotation")}}class Ea extends di{get typeName(){return Ne.ServiceClass}static[Symbol.hasInstance](t){return t.typeName===Ne.ServiceClass}constructor(t){super(),this._fields=Object.entries(t).sort((n,r)=>n[0]<r[0]?-1:n[0]>r[0]?1:0)}accept(t,n){return t.visitService(this,n)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=t.toUint8Array(),r=ft(n.length);return Ve(new Uint8Array([1]),r,n)}_buildTypeTableImpl(t){this._fields.forEach(([s,o])=>o.buildTypeTable(t));const n=It(qe.Service),r=ft(this._fields.length),i=this._fields.map(([s,o])=>{const c=new TextEncoder().encode(s),a=ft(c.length);return Ve(a,c,o.encodeType(t))});t.add(this,Ve(n,r,...i))}decodeValue(t,n){const r=n instanceof Nn?n.getType()??n:n;if(!Dl(r,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${r.display()}`);return Vl(t)}get name(){return`service {${this._fields.map(([n,r])=>n+":"+r.name).join("; ")}}`}valueToString(t){return`service "${t.toText()}"`}fieldsAsObject(){const t={};for(const[n,r]of this._fields)t[n]=r;return t}}function wt(e){const t=JSON.stringify(e,(n,r)=>typeof r=="bigint"?`BigInt(${r})`:r);return t&&t.length>jd?t.substring(0,jd-3)+"...":t}function Xf(e,t){if(t.length<e.length)throw Error("Wrong number of message arguments");const n=new SS;e.forEach(a=>a.buildTypeTable(n));const r=new TextEncoder().encode(Yc),i=n.encode(),s=ft(t.length),o=Ve(...e.map(a=>a.encodeType(n))),c=Ve(...Bo(e,t,(a,u)=>{try{a.covariant(u)}catch(f){throw new Error(f.message+`
22
+ variant ${n} -> ${i.message}`)}}))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){for(let n=0;n<this._fields.length;n++){const[r,i]=this._fields[n];if(t.hasOwnProperty(r)){const s=ft(n),o=i.encodeValue(t[r]);return Ve(s,o)}}throw Error("Variant has no data: "+t)}_buildTypeTableImpl(t){this._fields.forEach(([,s])=>{s.buildTypeTable(t)});const n=It(qe.Variant),r=ft(this._fields.length),i=this._fields.map(([s,o])=>Ve(ft(cn(s)),o.encodeType(t)));t.add(this,Ve(n,r,...i))}decodeValue(t,n){const r=this.checkType(n);if(!(r instanceof Rs))throw new Error("Not a variant type");const i=Number(Nt(t));if(i>=r._fields.length)throw Error("Invalid variant index: "+i);const[s,o]=r._fields[i];for(const[c,a]of this._fields)if(cn(s)===cn(c)){const u=a.decodeValue(t,o);return{[c]:u}}throw new Error("Cannot find field hash "+s)}get name(){return`variant {${this._fields.map(([n,r])=>n+":"+r.name).join("; ")}}`}display(){return`variant {${this._fields.map(([n,r])=>n+(r.name==="null"?"":`:${r.display()}`)).join("; ")}}`}valueToString(t){for(const[n,r]of this._fields)if(t.hasOwnProperty(n)){const i=r.valueToString(t[n]);return i==="null"?`variant {${n}}`:`variant {${n}=${i}}`}throw new Error("Variant has no data: "+t)}get alternativesAsObject(){const t={};for(const[n,r]of this._fields)t[cn(n)]=r;return t}}const qa=class qa extends di{constructor(){super(...arguments),this._id=qa._counter++}get typeName(){return Ne.RecClass}static[Symbol.hasInstance](t){return t.typeName===Ne.RecClass}accept(t,n){if(!this._type)throw Error("Recursive type uninitialized.");return t.visitRec(this,this._type,n)}fill(t){this._type=t}getType(){return this._type}covariant(t){if(this._type&&this._type.covariant(t))return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.encodeValue(t)}_buildTypeTableImpl(t){if(!this._type)throw Error("Recursive type uninitialized.");t.add(this,new Uint8Array([])),this._type.buildTypeTable(t),t.merge(this,this._type.name)}decodeValue(t,n){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.decodeValue(t,n)}get name(){return`rec_${this._id}`}display(){if(!this._type)throw Error("Recursive type uninitialized.");return`μ${this.name}.${this._type.name}`}valueToString(t){if(!this._type)throw Error("Recursive type uninitialized.");return this._type.valueToString(t)}};qa._counter=0;let Nn=qa;function Vl(e){if(Di(e)!==1)throw new Error("Cannot decode principal");const n=Number(Nt(e));return Ge.fromUint8Array(new Uint8Array(Vi(e,n)))}class im extends Rn{get typeName(){return Ne.PrincipalClass}static[Symbol.hasInstance](t){return t.typeName===Ne.PrincipalClass}accept(t,n){return t.visitPrincipal(this,n)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=t.toUint8Array(),r=ft(n.byteLength);return Ve(new Uint8Array([1]),r,n)}encodeType(){return It(qe.Principal)}decodeValue(t,n){return this.checkType(n),Vl(t)}get name(){return"principal"}valueToString(t){return`${this.name} "${t.toText()}"`}}class ko extends di{get typeName(){return Ne.FuncClass}static[Symbol.hasInstance](t){return t.typeName===Ne.FuncClass}static argsToString(t,n){if(t.length!==n.length)throw new Error("arity mismatch");return"("+t.map((r,i)=>r.valueToString(n[i])).join(", ")+")"}constructor(t,n,r=[]){super(),this.argTypes=t,this.retTypes=n,this.annotations=r}accept(t,n){return t.visitFunc(this,n)}covariant(t){if(Array.isArray(t)&&t.length===2&&t[0]&&t[0]._isPrincipal&&typeof t[1]=="string")return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue([t,n]){const r=t.toUint8Array(),i=ft(r.byteLength),s=Ve(new Uint8Array([1]),i,r),o=new TextEncoder().encode(n),c=ft(o.byteLength);return Ve(new Uint8Array([1]),s,c,o)}_buildTypeTableImpl(t){this.argTypes.forEach(u=>u.buildTypeTable(t)),this.retTypes.forEach(u=>u.buildTypeTable(t));const n=It(qe.Func),r=ft(this.argTypes.length),i=Ve(...this.argTypes.map(u=>u.encodeType(t))),s=ft(this.retTypes.length),o=Ve(...this.retTypes.map(u=>u.encodeType(t))),c=ft(this.annotations.length),a=Ve(...this.annotations.map(u=>this.encodeAnnotation(u)));t.add(this,Ve(n,r,i,s,o,c,a))}decodeValue(t,n){const r=n instanceof Nn?n.getType()??n:n;if(!Dl(r,this))throw new Error(`Cannot decode function reference at type ${this.display()} from wire type ${r.display()}`);if(Di(t)!==1)throw new Error("Cannot decode function reference");const s=Vl(t),o=Number(Nt(t)),c=Vi(t,o),u=new TextDecoder("utf8",{fatal:!0}).decode(c);return[s,u]}get name(){const t=this.argTypes.map(i=>i.name).join(", "),n=this.retTypes.map(i=>i.name).join(", "),r=" "+this.annotations.join(" ");return`(${t}) -> (${n})${r}`}valueToString([t,n]){return`func "${t.toText()}".${n}`}display(){const t=this.argTypes.map(i=>i.display()).join(", "),n=this.retTypes.map(i=>i.display()).join(", "),r=" "+this.annotations.join(" ");return`(${t}) → (${n})${r}`}encodeAnnotation(t){if(t==="query")return new Uint8Array([1]);if(t==="oneway")return new Uint8Array([2]);if(t==="composite_query")return new Uint8Array([3]);throw new Error("Illegal function annotation")}}class Ea extends di{get typeName(){return Ne.ServiceClass}static[Symbol.hasInstance](t){return t.typeName===Ne.ServiceClass}constructor(t){super(),this._fields=Object.entries(t).sort((n,r)=>n[0]<r[0]?-1:n[0]>r[0]?1:0)}accept(t,n){return t.visitService(this,n)}covariant(t){if(t&&t._isPrincipal)return!0;throw new Error(`Invalid ${this.display()} argument: ${wt(t)}`)}encodeValue(t){const n=t.toUint8Array(),r=ft(n.length);return Ve(new Uint8Array([1]),r,n)}_buildTypeTableImpl(t){this._fields.forEach(([s,o])=>o.buildTypeTable(t));const n=It(qe.Service),r=ft(this._fields.length),i=this._fields.map(([s,o])=>{const c=new TextEncoder().encode(s),a=ft(c.length);return Ve(a,c,o.encodeType(t))});t.add(this,Ve(n,r,...i))}decodeValue(t,n){const r=n instanceof Nn?n.getType()??n:n;if(!Dl(r,this))throw new Error(`Cannot decode service reference at type ${this.display()} from wire type ${r.display()}`);return Vl(t)}get name(){return`service {${this._fields.map(([n,r])=>n+":"+r.name).join("; ")}}`}valueToString(t){return`service "${t.toText()}"`}fieldsAsObject(){const t={};for(const[n,r]of this._fields)t[n]=r;return t}}function wt(e){const t=JSON.stringify(e,(n,r)=>typeof r=="bigint"?`BigInt(${r})`:r);return t&&t.length>jd?t.substring(0,jd-3)+"...":t}function Xf(e,t){if(t.length<e.length)throw Error("Wrong number of message arguments");const n=new SS;e.forEach(a=>a.buildTypeTable(n));const r=new TextEncoder().encode(Yc),i=n.encode(),s=ft(t.length),o=Ve(...e.map(a=>a.encodeType(n))),c=Ve(...Bo(e,t,(a,u)=>{try{a.covariant(u)}catch(f){throw new Error(f.message+`
23
23
 
24
- `)}return a.encodeValue(u)}));return Ve(r,i,s,o,c)}function sm(e,t){const n=new Vs(t);if(t.byteLength<Yc.length)throw new Error("Message length smaller than magic number");const r=Vi(n,Yc.length),i=new TextDecoder().decode(r);if(i!==Yc)throw new Error("Wrong magic number: "+JSON.stringify(i));function s(d){const y=[],g=Number(Nt(d));for(let S=0;S<g;S++){const _=Number(ni(d));switch(_){case qe.Opt:case qe.Vector:{const w=Number(ni(d));y.push([_,w]);break}case qe.Record:case qe.Variant:{const w=[];let T=Number(Nt(d)),O;for(;T--;){const A=Number(Nt(d));if(A>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof O=="number"&&O>=A)throw new Error("field id collision or not sorted");O=A;const R=Number(ni(d));w.push([A,R])}y.push([_,w]);break}case qe.Func:{const w=[];let T=Number(Nt(d));for(;T--;)w.push(Number(ni(d)));const O=[];let A=Number(Nt(d));for(;A--;)O.push(Number(ni(d)));const R=[];let M=Number(Nt(d));for(;M--;)switch(Number(Nt(d))){case 1:{R.push("query");break}case 2:{R.push("oneway");break}case 3:{R.push("composite_query");break}default:throw new Error("unknown annotation")}y.push([_,[w,O,R]]);break}case qe.Service:{let w=Number(Nt(d));const T=[];for(;w--;){const O=Number(Nt(d)),A=new TextDecoder().decode(Vi(d,O)),R=ni(d);T.push([A,R])}y.push([_,T]);break}default:throw new Error("Illegal op_code: "+_)}}const m=[],E=Number(Nt(d));for(let S=0;S<E;S++)m.push(Number(ni(d)));return[y,m]}const[o,c]=s(n);if(c.length<e.length)throw new Error("Wrong number of return values");const a=o.map(d=>Bm());function u(d){if(d<-24)throw new Error("future value not supported");if(d<0)switch(d){case-1:return um;case-2:return am;case-3:return hm;case-4:return lm;case-5:return bm;case-6:return Em;case-7:return _m;case-8:return Sm;case-9:return ym;case-10:return gm;case-11:return mm;case-12:return wm;case-13:return dm;case-14:return pm;case-15:return fm;case-16:return cm;case-17:return om;case-24:return Tm;default:throw new Error("Illegal op_code: "+d)}if(d>=o.length)throw new Error("type index out of range");return a[d]}function f(d){switch(d[0]){case qe.Vector:{const y=u(d[1]);return Am(y)}case qe.Opt:{const y=u(d[1]);return vm(y)}case qe.Record:{const y={};for(const[E,S]of d[1]){const _=`_${E}_`;y[_]=u(S)}const g=Im(y),m=g.tryAsTuple();return Array.isArray(m)?xm(...m):g}case qe.Variant:{const y={};for(const[g,m]of d[1]){const E=`_${g}_`;y[E]=u(m)}return Om(y)}case qe.Func:{const[y,g,m]=d[1];return Nm(y.map(E=>u(E)),g.map(E=>u(E)),m)}case qe.Service:{const y={},g=d[1];for(const[m,E]of g){let S=u(E);if(S instanceof Nn&&(S=S.getType()),!(S instanceof ko))throw new Error("Illegal service definition: services can only contain functions");y[m]=S}return km(y)}default:throw new Error("Illegal op_code: "+d[0])}}o.forEach((d,y)=>{if(d[0]===qe.Func){const g=f(d);a[y].fill(g)}}),o.forEach((d,y)=>{if(d[0]!==qe.Func){const g=f(d);a[y].fill(g)}}),zf();const l=c.map(d=>u(d));try{const d=e.map((y,g)=>y.decodeValue(n,l[g]));for(let y=e.length;y<l.length;y++)l[y].decodeValue(n,l[y]);if(n.byteLength>0)throw new Error("decode: Left-over bytes");return d}finally{zf()}}const om=new Fl,cm=new li,xS=new tm,am=new nm,um=new No,fm=new rm,lm=new Ml,hm=new Ll,dm=new ql(32),pm=new ql(64),ym=new $i(8),gm=new $i(16),mm=new $i(32),wm=new $i(64),bm=new ci(8),Em=new ci(16),_m=new ci(32),Sm=new ci(64),Tm=new im;function xm(...e){return new tu(e)}function Am(e){return new ks(e)}function vm(e){return new Br(e)}function Im(e){return new ji(e)}function Om(e){return new Ps(e)}function Bm(){return new Nn}function Nm(e,t,n=[]){return new ko(e,t,n)}function km(e){return new Ea(e)}class nu{constructor(t=new Map){this.rels=t}copy(){const t=new Map;for(const[n,r]of this.rels.entries()){const i=new Map(r);t.set(n,i)}return new nu(t)}known(t,n){return this.rels.get(t.name)?.get(n.name)}addNegative(t,n){this.addNames(t.name,n.name,!1)}add(t,n){this.addNames(t.name,n.name,!0)}display(){let t="";for(const[n,r]of this.rels)for(const[i,s]of r)t+=`${n} ${s?":<":"!<:"} ${i}
25
- `;return t}addNames(t,n,r){const i=this.rels.get(t);if(i==null){const s=new Map;s.set(n,r),this.rels.set(t,s)}else i.set(n,r)}}let Zc=new nu;function zf(){Zc=new nu}function AS(e,t){const n=new Set(e.annotations),r=new Set(t.annotations);if(n.size!==r.size)return!1;for(const i of n)if(!r.has(i))return!1;return!0}function Wu(e){return e instanceof Br||e instanceof No||e instanceof li}function Dl(e,t){const n=Zc.copy(),r=pr(n,e,t);return r?Zc.add(e,t):Zc.addNegative(e,t),r}function pr(e,t,n){if(t.name===n.name)return!0;const r=e.known(t,n);if(r!==void 0)return r;if(e.add(t,n),n instanceof li||t instanceof Fl||t instanceof Ll&&n instanceof Ml)return!0;if(t instanceof ks&&n instanceof ks)return pr(e,t._type,n._type);if(n instanceof Br)return!0;if(t instanceof ji&&n instanceof ji){const i=t.fieldsAsObject;for(const[s,o]of n._fields){const c=i[on(s)];if(c){if(!pr(e,c,o))return!1}else if(!Wu(o))return!1}return!0}if(t instanceof ko&&n instanceof ko){if(!AS(t,n))return!1;for(let i=0;i<t.argTypes.length;i++){const s=t.argTypes[i];if(i<n.argTypes.length){if(!pr(e,n.argTypes[i],s))return!1}else if(!Wu(s))return!1}for(let i=0;i<n.retTypes.length;i++){const s=n.retTypes[i];if(i<t.retTypes.length){if(!pr(e,t.retTypes[i],s))return!1}else if(!Wu(s))return!1}return!0}if(t instanceof Ps&&n instanceof Ps){const i=n.alternativesAsObject;for(const[s,o]of t._fields){const c=i[on(s)];if(!c||!pr(e,o,c))return!1}return!0}if(t instanceof Ea&&n instanceof Ea){const i=t.fieldsAsObject();for(const[s,o]of n._fields){const c=i[s];if(!c||!pr(e,c,o))return!1}return!0}return t instanceof Nn?pr(e,t.getType(),n):n instanceof Nn?pr(e,t,n.getType()):!1}const vS=Object.freeze(Object.defineProperty({__proto__:null,Bool:am,BoolClass:nm,ConstructType:di,Empty:om,EmptyClass:Fl,FixedIntClass:$i,FixedNatClass:ci,Float32:dm,Float64:pm,FloatClass:ql,Func:Nm,FuncClass:ko,Int:lm,Int16:gm,Int32:mm,Int64:wm,Int8:ym,IntClass:Ml,Nat:hm,Nat16:Em,Nat32:_m,Nat64:Sm,Nat8:bm,NatClass:Ll,Null:um,NullClass:No,Opt:vm,OptClass:Br,PrimitiveType:Rn,Principal:Tm,PrincipalClass:im,Rec:Bm,RecClass:Nn,Record:Im,RecordClass:ji,Reserved:cm,ReservedClass:li,Service:km,ServiceClass:Ea,Text:fm,TextClass:rm,Tuple:xm,TupleClass:tu,Type:eu,Unknown:xS,UnknownClass:tm,Variant:Om,VariantClass:Ps,Vec:Am,VecClass:ks,Visitor:TS,decode:sm,encode:Xf,resetSubtypeCache:zf,subtype:Dl},Symbol.toStringTag,{value:"Module"}));function Pm(e,t){return function(){return e.apply(t,arguments)}}const{toString:IS}=Object.prototype,{getPrototypeOf:$l}=Object,{iterator:ru,toStringTag:Rm}=Symbol,iu=(e=>t=>{const n=IS.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Gn=e=>(e=e.toLowerCase(),t=>iu(t)===e),su=e=>t=>typeof t===e,{isArray:Ds}=Array,Po=su("undefined");function fc(e){return e!==null&&!Po(e)&&e.constructor!==null&&!Po(e.constructor)&&dn(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Cm=Gn("ArrayBuffer");function OS(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Cm(e.buffer),t}const BS=su("string"),dn=su("function"),Um=su("number"),lc=e=>e!==null&&typeof e=="object",NS=e=>e===!0||e===!1,Jc=e=>{if(iu(e)!=="object")return!1;const t=$l(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Rm in e)&&!(ru in e)},kS=e=>{if(!lc(e)||fc(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},PS=Gn("Date"),RS=Gn("File"),CS=Gn("Blob"),US=Gn("FileList"),HS=e=>lc(e)&&dn(e.pipe),FS=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||dn(e.append)&&((t=iu(e))==="formdata"||t==="object"&&dn(e.toString)&&e.toString()==="[object FormData]"))},MS=Gn("URLSearchParams"),[LS,qS,VS,DS]=["ReadableStream","Request","Response","Headers"].map(Gn),$S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function hc(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,i;if(typeof e!="object"&&(e=[e]),Ds(e))for(r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else{if(fc(e))return;const s=n?Object.getOwnPropertyNames(e):Object.keys(e),o=s.length;let c;for(r=0;r<o;r++)c=s[r],t.call(null,e[c],c,e)}}function Hm(e,t){if(fc(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,i;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const Pi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:globalThis,Fm=e=>!Po(e)&&e!==Pi;function Yf(){const{caseless:e}=Fm(this)&&this||{},t={},n=(r,i)=>{const s=e&&Hm(t,i)||i;Jc(t[s])&&Jc(r)?t[s]=Yf(t[s],r):Jc(r)?t[s]=Yf({},r):Ds(r)?t[s]=r.slice():t[s]=r};for(let r=0,i=arguments.length;r<i;r++)arguments[r]&&hc(arguments[r],n);return t}const jS=(e,t,n,{allOwnKeys:r}={})=>(hc(t,(i,s)=>{n&&dn(i)?e[s]=Pm(i,n):e[s]=i},{allOwnKeys:r}),e),KS=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),GS=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},WS=(e,t,n,r)=>{let i,s,o;const c={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],(!r||r(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=n!==!1&&$l(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},XS=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zS=e=>{if(!e)return null;if(Ds(e))return e;let t=e.length;if(!Um(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},YS=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&$l(Uint8Array)),ZS=(e,t)=>{const r=(e&&e[ru]).call(e);let i;for(;(i=r.next())&&!i.done;){const s=i.value;t.call(e,s[0],s[1])}},JS=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},QS=Gn("HTMLFormElement"),eT=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),Kd=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),tT=Gn("RegExp"),Mm=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};hc(n,(i,s)=>{let o;(o=t(i,s,e))!==!1&&(r[s]=o||i)}),Object.defineProperties(e,r)},nT=e=>{Mm(e,(t,n)=>{if(dn(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(dn(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},rT=(e,t)=>{const n={},r=i=>{i.forEach(s=>{n[s]=!0})};return Ds(e)?r(e):r(String(e).split(t)),n},iT=()=>{},sT=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function oT(e){return!!(e&&dn(e.append)&&e[Rm]==="FormData"&&e[ru])}const cT=e=>{const t=new Array(10),n=(r,i)=>{if(lc(r)){if(t.indexOf(r)>=0)return;if(fc(r))return r;if(!("toJSON"in r)){t[i]=r;const s=Ds(r)?[]:{};return hc(r,(o,c)=>{const a=n(o,i+1);!Po(a)&&(s[c]=a)}),t[i]=void 0,s}}return r};return n(e,0)},aT=Gn("AsyncFunction"),uT=e=>e&&(lc(e)||dn(e))&&dn(e.then)&&dn(e.catch),Lm=((e,t)=>e?setImmediate:t?((n,r)=>(Pi.addEventListener("message",({source:i,data:s})=>{i===Pi&&s===n&&r.length&&r.shift()()},!1),i=>{r.push(i),Pi.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",dn(Pi.postMessage)),fT=typeof queueMicrotask<"u"?queueMicrotask.bind(Pi):typeof process<"u"&&process.nextTick||Lm,lT=e=>e!=null&&dn(e[ru]),z={isArray:Ds,isArrayBuffer:Cm,isBuffer:fc,isFormData:FS,isArrayBufferView:OS,isString:BS,isNumber:Um,isBoolean:NS,isObject:lc,isPlainObject:Jc,isEmptyObject:kS,isReadableStream:LS,isRequest:qS,isResponse:VS,isHeaders:DS,isUndefined:Po,isDate:PS,isFile:RS,isBlob:CS,isRegExp:tT,isFunction:dn,isStream:HS,isURLSearchParams:MS,isTypedArray:YS,isFileList:US,forEach:hc,merge:Yf,extend:jS,trim:$S,stripBOM:KS,inherits:GS,toFlatObject:WS,kindOf:iu,kindOfTest:Gn,endsWith:XS,toArray:zS,forEachEntry:ZS,matchAll:JS,isHTMLForm:QS,hasOwnProperty:Kd,hasOwnProp:Kd,reduceDescriptors:Mm,freezeMethods:nT,toObjectSet:rT,toCamelCase:eT,noop:iT,toFiniteNumber:sT,findKey:Hm,global:Pi,isContextDefined:Fm,isSpecCompliantForm:oT,toJSONObject:cT,isAsyncFn:aT,isThenable:uT,setImmediate:Lm,asap:fT,isIterable:lT};function Pe(e,t,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}z.inherits(Pe,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:z.toJSONObject(this.config),code:this.code,status:this.status}}});const qm=Pe.prototype,Vm={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{Vm[e]={value:e}});Object.defineProperties(Pe,Vm);Object.defineProperty(qm,"isAxiosError",{value:!0});Pe.from=(e,t,n,r,i,s)=>{const o=Object.create(qm);return z.toFlatObject(e,o,function(a){return a!==Error.prototype},c=>c!=="isAxiosError"),Pe.call(o,e.message,t,n,r,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};const hT=null;function Zf(e){return z.isPlainObject(e)||z.isArray(e)}function Dm(e){return z.endsWith(e,"[]")?e.slice(0,-2):e}function Gd(e,t,n){return e?e.concat(t).map(function(i,s){return i=Dm(i),!n&&s?"["+i+"]":i}).join(n?".":""):t}function dT(e){return z.isArray(e)&&!e.some(Zf)}const pT=z.toFlatObject(z,{},null,function(t){return/^is[A-Z]/.test(t)});function ou(e,t,n){if(!z.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=z.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,E){return!z.isUndefined(E[m])});const r=n.metaTokens,i=n.visitor||f,s=n.dots,o=n.indexes,a=(n.Blob||typeof Blob<"u"&&Blob)&&z.isSpecCompliantForm(t);if(!z.isFunction(i))throw new TypeError("visitor must be a function");function u(g){if(g===null)return"";if(z.isDate(g))return g.toISOString();if(z.isBoolean(g))return g.toString();if(!a&&z.isBlob(g))throw new Pe("Blob is not supported. Use a Buffer instead.");return z.isArrayBuffer(g)||z.isTypedArray(g)?a&&typeof Blob=="function"?new Blob([g]):Buffer.from(g):g}function f(g,m,E){let S=g;if(g&&!E&&typeof g=="object"){if(z.endsWith(m,"{}"))m=r?m:m.slice(0,-2),g=JSON.stringify(g);else if(z.isArray(g)&&dT(g)||(z.isFileList(g)||z.endsWith(m,"[]"))&&(S=z.toArray(g)))return m=Dm(m),S.forEach(function(w,T){!(z.isUndefined(w)||w===null)&&t.append(o===!0?Gd([m],T,s):o===null?m:m+"[]",u(w))}),!1}return Zf(g)?!0:(t.append(Gd(E,m,s),u(g)),!1)}const l=[],d=Object.assign(pT,{defaultVisitor:f,convertValue:u,isVisitable:Zf});function y(g,m){if(!z.isUndefined(g)){if(l.indexOf(g)!==-1)throw Error("Circular reference detected in "+m.join("."));l.push(g),z.forEach(g,function(S,_){(!(z.isUndefined(S)||S===null)&&i.call(t,S,z.isString(_)?_.trim():_,m,d))===!0&&y(S,m?m.concat(_):[_])}),l.pop()}}if(!z.isObject(e))throw new TypeError("data must be an object");return y(e),t}function Wd(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function jl(e,t){this._pairs=[],e&&ou(e,this,t)}const $m=jl.prototype;$m.append=function(t,n){this._pairs.push([t,n])};$m.toString=function(t){const n=t?function(r){return t.call(this,r,Wd)}:Wd;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function yT(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function jm(e,t,n){if(!t)return e;const r=n&&n.encode||yT;z.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let s;if(i?s=i(t,n):s=z.isURLSearchParams(t)?t.toString():new jl(t,n).toString(r),s){const o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class Xd{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){z.forEach(this.handlers,function(r){r!==null&&t(r)})}}const Km={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},gT=typeof URLSearchParams<"u"?URLSearchParams:jl,mT=typeof FormData<"u"?FormData:null,wT=typeof Blob<"u"?Blob:null,bT={isBrowser:!0,classes:{URLSearchParams:gT,FormData:mT,Blob:wT},protocols:["http","https","file","blob","url","data"]},Kl=typeof window<"u"&&typeof document<"u",Jf=typeof navigator=="object"&&navigator||void 0,ET=Kl&&(!Jf||["ReactNative","NativeScript","NS"].indexOf(Jf.product)<0),_T=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",ST=Kl&&window.location.href||"http://localhost",TT=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Kl,hasStandardBrowserEnv:ET,hasStandardBrowserWebWorkerEnv:_T,navigator:Jf,origin:ST},Symbol.toStringTag,{value:"Module"})),jt={...TT,...bT};function xT(e,t){return ou(e,new jt.classes.URLSearchParams,{visitor:function(n,r,i,s){return jt.isNode&&z.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...t})}function AT(e){return z.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function vT(e){const t={},n=Object.keys(e);let r;const i=n.length;let s;for(r=0;r<i;r++)s=n[r],t[s]=e[s];return t}function Gm(e){function t(n,r,i,s){let o=n[s++];if(o==="__proto__")return!0;const c=Number.isFinite(+o),a=s>=n.length;return o=!o&&z.isArray(i)?i.length:o,a?(z.hasOwnProp(i,o)?i[o]=[i[o],r]:i[o]=r,!c):((!i[o]||!z.isObject(i[o]))&&(i[o]=[]),t(n,r,i[o],s)&&z.isArray(i[o])&&(i[o]=vT(i[o])),!c)}if(z.isFormData(e)&&z.isFunction(e.entries)){const n={};return z.forEachEntry(e,(r,i)=>{t(AT(r),i,n,0)}),n}return null}function IT(e,t,n){if(z.isString(e))try{return(t||JSON.parse)(e),z.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const dc={transitional:Km,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",i=r.indexOf("application/json")>-1,s=z.isObject(t);if(s&&z.isHTMLForm(t)&&(t=new FormData(t)),z.isFormData(t))return i?JSON.stringify(Gm(t)):t;if(z.isArrayBuffer(t)||z.isBuffer(t)||z.isStream(t)||z.isFile(t)||z.isBlob(t)||z.isReadableStream(t))return t;if(z.isArrayBufferView(t))return t.buffer;if(z.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return xT(t,this.formSerializer).toString();if((c=z.isFileList(t))||r.indexOf("multipart/form-data")>-1){const a=this.env&&this.env.FormData;return ou(c?{"files[]":t}:t,a&&new a,this.formSerializer)}}return s||i?(n.setContentType("application/json",!1),IT(t)):t}],transformResponse:[function(t){const n=this.transitional||dc.transitional,r=n&&n.forcedJSONParsing,i=this.responseType==="json";if(z.isResponse(t)||z.isReadableStream(t))return t;if(t&&z.isString(t)&&(r&&!this.responseType||i)){const o=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(t)}catch(c){if(o)throw c.name==="SyntaxError"?Pe.from(c,Pe.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:jt.classes.FormData,Blob:jt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};z.forEach(["delete","get","head","post","put","patch"],e=>{dc.headers[e]={}});const OT=z.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),BT=e=>{const t={};let n,r,i;return e&&e.split(`
26
- `).forEach(function(o){i=o.indexOf(":"),n=o.substring(0,i).trim().toLowerCase(),r=o.substring(i+1).trim(),!(!n||t[n]&&OT[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},zd=Symbol("internals");function eo(e){return e&&String(e).trim().toLowerCase()}function Qc(e){return e===!1||e==null?e:z.isArray(e)?e.map(Qc):String(e)}function NT(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const kT=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Xu(e,t,n,r,i){if(z.isFunction(r))return r.call(this,t,n);if(i&&(t=n),!!z.isString(t)){if(z.isString(r))return t.indexOf(r)!==-1;if(z.isRegExp(r))return r.test(t)}}function PT(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function RT(e,t){const n=z.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(i,s,o){return this[r].call(this,t,i,s,o)},configurable:!0})})}let pn=class{constructor(t){t&&this.set(t)}set(t,n,r){const i=this;function s(c,a,u){const f=eo(a);if(!f)throw new Error("header name must be a non-empty string");const l=z.findKey(i,f);(!l||i[l]===void 0||u===!0||u===void 0&&i[l]!==!1)&&(i[l||a]=Qc(c))}const o=(c,a)=>z.forEach(c,(u,f)=>s(u,f,a));if(z.isPlainObject(t)||t instanceof this.constructor)o(t,n);else if(z.isString(t)&&(t=t.trim())&&!kT(t))o(BT(t),n);else if(z.isObject(t)&&z.isIterable(t)){let c={},a,u;for(const f of t){if(!z.isArray(f))throw TypeError("Object iterator must return a key-value pair");c[u=f[0]]=(a=c[u])?z.isArray(a)?[...a,f[1]]:[a,f[1]]:f[1]}o(c,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=eo(t),t){const r=z.findKey(this,t);if(r){const i=this[r];if(!n)return i;if(n===!0)return NT(i);if(z.isFunction(n))return n.call(this,i,r);if(z.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=eo(t),t){const r=z.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Xu(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let i=!1;function s(o){if(o=eo(o),o){const c=z.findKey(r,o);c&&(!n||Xu(r,r[c],c,n))&&(delete r[c],i=!0)}}return z.isArray(t)?t.forEach(s):s(t),i}clear(t){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const s=n[r];(!t||Xu(this,this[s],s,t,!0))&&(delete this[s],i=!0)}return i}normalize(t){const n=this,r={};return z.forEach(this,(i,s)=>{const o=z.findKey(r,s);if(o){n[o]=Qc(i),delete n[s];return}const c=t?PT(s):String(s).trim();c!==s&&delete n[s],n[c]=Qc(i),r[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return z.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=t&&z.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
27
- `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(i=>r.set(i)),r}static accessor(t){const r=(this[zd]=this[zd]={accessors:{}}).accessors,i=this.prototype;function s(o){const c=eo(o);r[c]||(RT(i,o),r[c]=!0)}return z.isArray(t)?t.forEach(s):s(t),this}};pn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);z.reduceDescriptors(pn.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});z.freezeMethods(pn);function zu(e,t){const n=this||dc,r=t||n,i=pn.from(r.headers);let s=r.data;return z.forEach(e,function(c){s=c.call(n,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function Wm(e){return!!(e&&e.__CANCEL__)}function $s(e,t,n){Pe.call(this,e??"canceled",Pe.ERR_CANCELED,t,n),this.name="CanceledError"}z.inherits($s,Pe,{__CANCEL__:!0});function Xm(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Pe("Request failed with status code "+n.status,[Pe.ERR_BAD_REQUEST,Pe.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function CT(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function UT(e,t){e=e||10;const n=new Array(e),r=new Array(e);let i=0,s=0,o;return t=t!==void 0?t:1e3,function(a){const u=Date.now(),f=r[s];o||(o=u),n[i]=a,r[i]=u;let l=s,d=0;for(;l!==i;)d+=n[l++],l=l%e;if(i=(i+1)%e,i===s&&(s=(s+1)%e),u-o<t)return;const y=f&&u-f;return y?Math.round(d*1e3/y):void 0}}function HT(e,t){let n=0,r=1e3/t,i,s;const o=(u,f=Date.now())=>{n=f,i=null,s&&(clearTimeout(s),s=null),e(...u)};return[(...u)=>{const f=Date.now(),l=f-n;l>=r?o(u,f):(i=u,s||(s=setTimeout(()=>{s=null,o(i)},r-l)))},()=>i&&o(i)]}const _a=(e,t,n=3)=>{let r=0;const i=UT(50,250);return HT(s=>{const o=s.loaded,c=s.lengthComputable?s.total:void 0,a=o-r,u=i(a),f=o<=c;r=o;const l={loaded:o,total:c,progress:c?o/c:void 0,bytes:a,rate:u||void 0,estimated:u&&c&&f?(c-o)/u:void 0,event:s,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(l)},n)},Yd=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Zd=e=>(...t)=>z.asap(()=>e(...t)),FT=jt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,jt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(jt.origin),jt.navigator&&/(msie|trident)/i.test(jt.navigator.userAgent)):()=>!0,MT=jt.hasStandardBrowserEnv?{write(e,t,n,r,i,s){const o=[e+"="+encodeURIComponent(t)];z.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),z.isString(r)&&o.push("path="+r),z.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function LT(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function qT(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function zm(e,t,n){let r=!LT(t);return e&&(r||n==!1)?qT(e,t):t}const Jd=e=>e instanceof pn?{...e}:e;function Ki(e,t){t=t||{};const n={};function r(u,f,l,d){return z.isPlainObject(u)&&z.isPlainObject(f)?z.merge.call({caseless:d},u,f):z.isPlainObject(f)?z.merge({},f):z.isArray(f)?f.slice():f}function i(u,f,l,d){if(z.isUndefined(f)){if(!z.isUndefined(u))return r(void 0,u,l,d)}else return r(u,f,l,d)}function s(u,f){if(!z.isUndefined(f))return r(void 0,f)}function o(u,f){if(z.isUndefined(f)){if(!z.isUndefined(u))return r(void 0,u)}else return r(void 0,f)}function c(u,f,l){if(l in t)return r(u,f);if(l in e)return r(void 0,u)}const a={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(u,f,l)=>i(Jd(u),Jd(f),l,!0)};return z.forEach(Object.keys({...e,...t}),function(f){const l=a[f]||i,d=l(e[f],t[f],f);z.isUndefined(d)&&l!==c||(n[f]=d)}),n}const Ym=e=>{const t=Ki({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:s,headers:o,auth:c}=t;t.headers=o=pn.from(o),t.url=jm(zm(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):"")));let a;if(z.isFormData(n)){if(jt.hasStandardBrowserEnv||jt.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if((a=o.getContentType())!==!1){const[u,...f]=a?a.split(";").map(l=>l.trim()).filter(Boolean):[];o.setContentType([u||"multipart/form-data",...f].join("; "))}}if(jt.hasStandardBrowserEnv&&(r&&z.isFunction(r)&&(r=r(t)),r||r!==!1&&FT(t.url))){const u=i&&s&&MT.read(s);u&&o.set(i,u)}return t},VT=typeof XMLHttpRequest<"u",DT=VT&&function(e){return new Promise(function(n,r){const i=Ym(e);let s=i.data;const o=pn.from(i.headers).normalize();let{responseType:c,onUploadProgress:a,onDownloadProgress:u}=i,f,l,d,y,g;function m(){y&&y(),g&&g(),i.cancelToken&&i.cancelToken.unsubscribe(f),i.signal&&i.signal.removeEventListener("abort",f)}let E=new XMLHttpRequest;E.open(i.method.toUpperCase(),i.url,!0),E.timeout=i.timeout;function S(){if(!E)return;const w=pn.from("getAllResponseHeaders"in E&&E.getAllResponseHeaders()),O={data:!c||c==="text"||c==="json"?E.responseText:E.response,status:E.status,statusText:E.statusText,headers:w,config:e,request:E};Xm(function(R){n(R),m()},function(R){r(R),m()},O),E=null}"onloadend"in E?E.onloadend=S:E.onreadystatechange=function(){!E||E.readyState!==4||E.status===0&&!(E.responseURL&&E.responseURL.indexOf("file:")===0)||setTimeout(S)},E.onabort=function(){E&&(r(new Pe("Request aborted",Pe.ECONNABORTED,e,E)),E=null)},E.onerror=function(){r(new Pe("Network Error",Pe.ERR_NETWORK,e,E)),E=null},E.ontimeout=function(){let T=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const O=i.transitional||Km;i.timeoutErrorMessage&&(T=i.timeoutErrorMessage),r(new Pe(T,O.clarifyTimeoutError?Pe.ETIMEDOUT:Pe.ECONNABORTED,e,E)),E=null},s===void 0&&o.setContentType(null),"setRequestHeader"in E&&z.forEach(o.toJSON(),function(T,O){E.setRequestHeader(O,T)}),z.isUndefined(i.withCredentials)||(E.withCredentials=!!i.withCredentials),c&&c!=="json"&&(E.responseType=i.responseType),u&&([d,g]=_a(u,!0),E.addEventListener("progress",d)),a&&E.upload&&([l,y]=_a(a),E.upload.addEventListener("progress",l),E.upload.addEventListener("loadend",y)),(i.cancelToken||i.signal)&&(f=w=>{E&&(r(!w||w.type?new $s(null,e,E):w),E.abort(),E=null)},i.cancelToken&&i.cancelToken.subscribe(f),i.signal&&(i.signal.aborted?f():i.signal.addEventListener("abort",f)));const _=CT(i.url);if(_&&jt.protocols.indexOf(_)===-1){r(new Pe("Unsupported protocol "+_+":",Pe.ERR_BAD_REQUEST,e));return}E.send(s||null)})},$T=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,i;const s=function(u){if(!i){i=!0,c();const f=u instanceof Error?u:this.reason;r.abort(f instanceof Pe?f:new $s(f instanceof Error?f.message:f))}};let o=t&&setTimeout(()=>{o=null,s(new Pe(`timeout ${t} of ms exceeded`,Pe.ETIMEDOUT))},t);const c=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(s):u.removeEventListener("abort",s)}),e=null)};e.forEach(u=>u.addEventListener("abort",s));const{signal:a}=r;return a.unsubscribe=()=>z.asap(c),a}},jT=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,i;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},KT=async function*(e,t){for await(const n of GT(e))yield*jT(n,t)},GT=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Qd=(e,t,n,r)=>{const i=KT(e,t);let s=0,o,c=a=>{o||(o=!0,r&&r(a))};return new ReadableStream({async pull(a){try{const{done:u,value:f}=await i.next();if(u){c(),a.close();return}let l=f.byteLength;if(n){let d=s+=l;n(d)}a.enqueue(new Uint8Array(f))}catch(u){throw c(u),u}},cancel(a){return c(a),i.return()}},{highWaterMark:2})},cu=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Zm=cu&&typeof ReadableStream=="function",WT=cu&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Jm=(e,...t)=>{try{return!!e(...t)}catch{return!1}},XT=Zm&&Jm(()=>{let e=!1;const t=new Request(jt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),e0=64*1024,Qf=Zm&&Jm(()=>z.isReadableStream(new Response("").body)),Sa={stream:Qf&&(e=>e.body)};cu&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!Sa[t]&&(Sa[t]=z.isFunction(e[t])?n=>n[t]():(n,r)=>{throw new Pe(`Response type '${t}' is not supported`,Pe.ERR_NOT_SUPPORT,r)})})})(new Response);const zT=async e=>{if(e==null)return 0;if(z.isBlob(e))return e.size;if(z.isSpecCompliantForm(e))return(await new Request(jt.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(z.isArrayBufferView(e)||z.isArrayBuffer(e))return e.byteLength;if(z.isURLSearchParams(e)&&(e=e+""),z.isString(e))return(await WT(e)).byteLength},YT=async(e,t)=>{const n=z.toFiniteNumber(e.getContentLength());return n??zT(t)},ZT=cu&&(async e=>{let{url:t,method:n,data:r,signal:i,cancelToken:s,timeout:o,onDownloadProgress:c,onUploadProgress:a,responseType:u,headers:f,withCredentials:l="same-origin",fetchOptions:d}=Ym(e);u=u?(u+"").toLowerCase():"text";let y=$T([i,s&&s.toAbortSignal()],o),g;const m=y&&y.unsubscribe&&(()=>{y.unsubscribe()});let E;try{if(a&&XT&&n!=="get"&&n!=="head"&&(E=await YT(f,r))!==0){let O=new Request(t,{method:"POST",body:r,duplex:"half"}),A;if(z.isFormData(r)&&(A=O.headers.get("content-type"))&&f.setContentType(A),O.body){const[R,M]=Yd(E,_a(Zd(a)));r=Qd(O.body,e0,R,M)}}z.isString(l)||(l=l?"include":"omit");const S="credentials"in Request.prototype;g=new Request(t,{...d,signal:y,method:n.toUpperCase(),headers:f.normalize().toJSON(),body:r,duplex:"half",credentials:S?l:void 0});let _=await fetch(g,d);const w=Qf&&(u==="stream"||u==="response");if(Qf&&(c||w&&m)){const O={};["status","statusText","headers"].forEach(v=>{O[v]=_[v]});const A=z.toFiniteNumber(_.headers.get("content-length")),[R,M]=c&&Yd(A,_a(Zd(c),!0))||[];_=new Response(Qd(_.body,e0,R,()=>{M&&M(),m&&m()}),O)}u=u||"text";let T=await Sa[z.findKey(Sa,u)||"text"](_,e);return!w&&m&&m(),await new Promise((O,A)=>{Xm(O,A,{data:T,headers:pn.from(_.headers),status:_.status,statusText:_.statusText,config:e,request:g})})}catch(S){throw m&&m(),S&&S.name==="TypeError"&&/Load failed|fetch/i.test(S.message)?Object.assign(new Pe("Network Error",Pe.ERR_NETWORK,e,g),{cause:S.cause||S}):Pe.from(S,S&&S.code,e,g)}}),el={http:hT,xhr:DT,fetch:ZT};z.forEach(el,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const t0=e=>`- ${e}`,JT=e=>z.isFunction(e)||e===null||e===!1,Qm={getAdapter:e=>{e=z.isArray(e)?e:[e];const{length:t}=e;let n,r;const i={};for(let s=0;s<t;s++){n=e[s];let o;if(r=n,!JT(n)&&(r=el[(o=String(n)).toLowerCase()],r===void 0))throw new Pe(`Unknown adapter '${o}'`);if(r)break;i[o||"#"+s]=r}if(!r){const s=Object.entries(i).map(([c,a])=>`adapter ${c} `+(a===!1?"is not supported by the environment":"is not available in the build"));let o=t?s.length>1?`since :
24
+ `)}return a.encodeValue(u)}));return Ve(r,i,s,o,c)}function sm(e,t){const n=new Ds(t);if(t.byteLength<Yc.length)throw new Error("Message length smaller than magic number");const r=Vi(n,Yc.length),i=new TextDecoder().decode(r);if(i!==Yc)throw new Error("Wrong magic number: "+JSON.stringify(i));function s(d){const y=[],g=Number(Nt(d));for(let S=0;S<g;S++){const _=Number(ni(d));switch(_){case qe.Opt:case qe.Vector:{const w=Number(ni(d));y.push([_,w]);break}case qe.Record:case qe.Variant:{const w=[];let T=Number(Nt(d)),O;for(;T--;){const A=Number(Nt(d));if(A>=Math.pow(2,32))throw new Error("field id out of 32-bit range");if(typeof O=="number"&&O>=A)throw new Error("field id collision or not sorted");O=A;const R=Number(ni(d));w.push([A,R])}y.push([_,w]);break}case qe.Func:{const w=[];let T=Number(Nt(d));for(;T--;)w.push(Number(ni(d)));const O=[];let A=Number(Nt(d));for(;A--;)O.push(Number(ni(d)));const R=[];let M=Number(Nt(d));for(;M--;)switch(Number(Nt(d))){case 1:{R.push("query");break}case 2:{R.push("oneway");break}case 3:{R.push("composite_query");break}default:throw new Error("unknown annotation")}y.push([_,[w,O,R]]);break}case qe.Service:{let w=Number(Nt(d));const T=[];for(;w--;){const O=Number(Nt(d)),A=new TextDecoder().decode(Vi(d,O)),R=ni(d);T.push([A,R])}y.push([_,T]);break}default:throw new Error("Illegal op_code: "+_)}}const m=[],E=Number(Nt(d));for(let S=0;S<E;S++)m.push(Number(ni(d)));return[y,m]}const[o,c]=s(n);if(c.length<e.length)throw new Error("Wrong number of return values");const a=o.map(d=>Bm());function u(d){if(d<-24)throw new Error("future value not supported");if(d<0)switch(d){case-1:return um;case-2:return am;case-3:return hm;case-4:return lm;case-5:return bm;case-6:return Em;case-7:return _m;case-8:return Sm;case-9:return ym;case-10:return gm;case-11:return mm;case-12:return wm;case-13:return dm;case-14:return pm;case-15:return fm;case-16:return cm;case-17:return om;case-24:return Tm;default:throw new Error("Illegal op_code: "+d)}if(d>=o.length)throw new Error("type index out of range");return a[d]}function f(d){switch(d[0]){case qe.Vector:{const y=u(d[1]);return Am(y)}case qe.Opt:{const y=u(d[1]);return vm(y)}case qe.Record:{const y={};for(const[E,S]of d[1]){const _=`_${E}_`;y[_]=u(S)}const g=Im(y),m=g.tryAsTuple();return Array.isArray(m)?xm(...m):g}case qe.Variant:{const y={};for(const[g,m]of d[1]){const E=`_${g}_`;y[E]=u(m)}return Om(y)}case qe.Func:{const[y,g,m]=d[1];return Nm(y.map(E=>u(E)),g.map(E=>u(E)),m)}case qe.Service:{const y={},g=d[1];for(const[m,E]of g){let S=u(E);if(S instanceof Nn&&(S=S.getType()),!(S instanceof ko))throw new Error("Illegal service definition: services can only contain functions");y[m]=S}return km(y)}default:throw new Error("Illegal op_code: "+d[0])}}o.forEach((d,y)=>{if(d[0]===qe.Func){const g=f(d);a[y].fill(g)}}),o.forEach((d,y)=>{if(d[0]!==qe.Func){const g=f(d);a[y].fill(g)}}),zf();const l=c.map(d=>u(d));try{const d=e.map((y,g)=>y.decodeValue(n,l[g]));for(let y=e.length;y<l.length;y++)l[y].decodeValue(n,l[y]);if(n.byteLength>0)throw new Error("decode: Left-over bytes");return d}finally{zf()}}const om=new Fl,cm=new li,xS=new tm,am=new nm,um=new No,fm=new rm,lm=new Ml,hm=new Ll,dm=new ql(32),pm=new ql(64),ym=new $i(8),gm=new $i(16),mm=new $i(32),wm=new $i(64),bm=new ci(8),Em=new ci(16),_m=new ci(32),Sm=new ci(64),Tm=new im;function xm(...e){return new tu(e)}function Am(e){return new Ps(e)}function vm(e){return new Br(e)}function Im(e){return new ji(e)}function Om(e){return new Rs(e)}function Bm(){return new Nn}function Nm(e,t,n=[]){return new ko(e,t,n)}function km(e){return new Ea(e)}class nu{constructor(t=new Map){this.rels=t}copy(){const t=new Map;for(const[n,r]of this.rels.entries()){const i=new Map(r);t.set(n,i)}return new nu(t)}known(t,n){return this.rels.get(t.name)?.get(n.name)}addNegative(t,n){this.addNames(t.name,n.name,!1)}add(t,n){this.addNames(t.name,n.name,!0)}display(){let t="";for(const[n,r]of this.rels)for(const[i,s]of r)t+=`${n} ${s?":<":"!<:"} ${i}
25
+ `;return t}addNames(t,n,r){const i=this.rels.get(t);if(i==null){const s=new Map;s.set(n,r),this.rels.set(t,s)}else i.set(n,r)}}let Zc=new nu;function zf(){Zc=new nu}function AS(e,t){const n=new Set(e.annotations),r=new Set(t.annotations);if(n.size!==r.size)return!1;for(const i of n)if(!r.has(i))return!1;return!0}function Wu(e){return e instanceof Br||e instanceof No||e instanceof li}function Dl(e,t){const n=Zc.copy(),r=pr(n,e,t);return r?Zc.add(e,t):Zc.addNegative(e,t),r}function pr(e,t,n){if(t.name===n.name)return!0;const r=e.known(t,n);if(r!==void 0)return r;if(e.add(t,n),n instanceof li||t instanceof Fl||t instanceof Ll&&n instanceof Ml)return!0;if(t instanceof Ps&&n instanceof Ps)return pr(e,t._type,n._type);if(n instanceof Br)return!0;if(t instanceof ji&&n instanceof ji){const i=t.fieldsAsObject;for(const[s,o]of n._fields){const c=i[cn(s)];if(c){if(!pr(e,c,o))return!1}else if(!Wu(o))return!1}return!0}if(t instanceof ko&&n instanceof ko){if(!AS(t,n))return!1;for(let i=0;i<t.argTypes.length;i++){const s=t.argTypes[i];if(i<n.argTypes.length){if(!pr(e,n.argTypes[i],s))return!1}else if(!Wu(s))return!1}for(let i=0;i<n.retTypes.length;i++){const s=n.retTypes[i];if(i<t.retTypes.length){if(!pr(e,t.retTypes[i],s))return!1}else if(!Wu(s))return!1}return!0}if(t instanceof Rs&&n instanceof Rs){const i=n.alternativesAsObject;for(const[s,o]of t._fields){const c=i[cn(s)];if(!c||!pr(e,o,c))return!1}return!0}if(t instanceof Ea&&n instanceof Ea){const i=t.fieldsAsObject();for(const[s,o]of n._fields){const c=i[s];if(!c||!pr(e,c,o))return!1}return!0}return t instanceof Nn?pr(e,t.getType(),n):n instanceof Nn?pr(e,t,n.getType()):!1}const vS=Object.freeze(Object.defineProperty({__proto__:null,Bool:am,BoolClass:nm,ConstructType:di,Empty:om,EmptyClass:Fl,FixedIntClass:$i,FixedNatClass:ci,Float32:dm,Float64:pm,FloatClass:ql,Func:Nm,FuncClass:ko,Int:lm,Int16:gm,Int32:mm,Int64:wm,Int8:ym,IntClass:Ml,Nat:hm,Nat16:Em,Nat32:_m,Nat64:Sm,Nat8:bm,NatClass:Ll,Null:um,NullClass:No,Opt:vm,OptClass:Br,PrimitiveType:Rn,Principal:Tm,PrincipalClass:im,Rec:Bm,RecClass:Nn,Record:Im,RecordClass:ji,Reserved:cm,ReservedClass:li,Service:km,ServiceClass:Ea,Text:fm,TextClass:rm,Tuple:xm,TupleClass:tu,Type:eu,Unknown:xS,UnknownClass:tm,Variant:Om,VariantClass:Rs,Vec:Am,VecClass:Ps,Visitor:TS,decode:sm,encode:Xf,resetSubtypeCache:zf,subtype:Dl},Symbol.toStringTag,{value:"Module"}));function Pm(e,t){return function(){return e.apply(t,arguments)}}const{toString:IS}=Object.prototype,{getPrototypeOf:$l}=Object,{iterator:ru,toStringTag:Rm}=Symbol,iu=(e=>t=>{const n=IS.call(t);return e[n]||(e[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Gn=e=>(e=e.toLowerCase(),t=>iu(t)===e),su=e=>t=>typeof t===e,{isArray:$s}=Array,Po=su("undefined");function fc(e){return e!==null&&!Po(e)&&e.constructor!==null&&!Po(e.constructor)&&dn(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Cm=Gn("ArrayBuffer");function OS(e){let t;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?t=ArrayBuffer.isView(e):t=e&&e.buffer&&Cm(e.buffer),t}const BS=su("string"),dn=su("function"),Um=su("number"),lc=e=>e!==null&&typeof e=="object",NS=e=>e===!0||e===!1,Jc=e=>{if(iu(e)!=="object")return!1;const t=$l(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Rm in e)&&!(ru in e)},kS=e=>{if(!lc(e)||fc(e))return!1;try{return Object.keys(e).length===0&&Object.getPrototypeOf(e)===Object.prototype}catch{return!1}},PS=Gn("Date"),RS=Gn("File"),CS=Gn("Blob"),US=Gn("FileList"),HS=e=>lc(e)&&dn(e.pipe),FS=e=>{let t;return e&&(typeof FormData=="function"&&e instanceof FormData||dn(e.append)&&((t=iu(e))==="formdata"||t==="object"&&dn(e.toString)&&e.toString()==="[object FormData]"))},MS=Gn("URLSearchParams"),[LS,qS,VS,DS]=["ReadableStream","Request","Response","Headers"].map(Gn),$S=e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function hc(e,t,{allOwnKeys:n=!1}={}){if(e===null||typeof e>"u")return;let r,i;if(typeof e!="object"&&(e=[e]),$s(e))for(r=0,i=e.length;r<i;r++)t.call(null,e[r],r,e);else{if(fc(e))return;const s=n?Object.getOwnPropertyNames(e):Object.keys(e),o=s.length;let c;for(r=0;r<o;r++)c=s[r],t.call(null,e[c],c,e)}}function Hm(e,t){if(fc(e))return null;t=t.toLowerCase();const n=Object.keys(e);let r=n.length,i;for(;r-- >0;)if(i=n[r],t===i.toLowerCase())return i;return null}const Pi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:globalThis,Fm=e=>!Po(e)&&e!==Pi;function Yf(){const{caseless:e}=Fm(this)&&this||{},t={},n=(r,i)=>{const s=e&&Hm(t,i)||i;Jc(t[s])&&Jc(r)?t[s]=Yf(t[s],r):Jc(r)?t[s]=Yf({},r):$s(r)?t[s]=r.slice():t[s]=r};for(let r=0,i=arguments.length;r<i;r++)arguments[r]&&hc(arguments[r],n);return t}const jS=(e,t,n,{allOwnKeys:r}={})=>(hc(t,(i,s)=>{n&&dn(i)?e[s]=Pm(i,n):e[s]=i},{allOwnKeys:r}),e),KS=e=>(e.charCodeAt(0)===65279&&(e=e.slice(1)),e),GS=(e,t,n,r)=>{e.prototype=Object.create(t.prototype,r),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),n&&Object.assign(e.prototype,n)},WS=(e,t,n,r)=>{let i,s,o;const c={};if(t=t||{},e==null)return t;do{for(i=Object.getOwnPropertyNames(e),s=i.length;s-- >0;)o=i[s],(!r||r(o,e,t))&&!c[o]&&(t[o]=e[o],c[o]=!0);e=n!==!1&&$l(e)}while(e&&(!n||n(e,t))&&e!==Object.prototype);return t},XS=(e,t,n)=>{e=String(e),(n===void 0||n>e.length)&&(n=e.length),n-=t.length;const r=e.indexOf(t,n);return r!==-1&&r===n},zS=e=>{if(!e)return null;if($s(e))return e;let t=e.length;if(!Um(t))return null;const n=new Array(t);for(;t-- >0;)n[t]=e[t];return n},YS=(e=>t=>e&&t instanceof e)(typeof Uint8Array<"u"&&$l(Uint8Array)),ZS=(e,t)=>{const r=(e&&e[ru]).call(e);let i;for(;(i=r.next())&&!i.done;){const s=i.value;t.call(e,s[0],s[1])}},JS=(e,t)=>{let n;const r=[];for(;(n=e.exec(t))!==null;)r.push(n);return r},QS=Gn("HTMLFormElement"),eT=e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),Kd=(({hasOwnProperty:e})=>(t,n)=>e.call(t,n))(Object.prototype),tT=Gn("RegExp"),Mm=(e,t)=>{const n=Object.getOwnPropertyDescriptors(e),r={};hc(n,(i,s)=>{let o;(o=t(i,s,e))!==!1&&(r[s]=o||i)}),Object.defineProperties(e,r)},nT=e=>{Mm(e,(t,n)=>{if(dn(e)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=e[n];if(dn(r)){if(t.enumerable=!1,"writable"in t){t.writable=!1;return}t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},rT=(e,t)=>{const n={},r=i=>{i.forEach(s=>{n[s]=!0})};return $s(e)?r(e):r(String(e).split(t)),n},iT=()=>{},sT=(e,t)=>e!=null&&Number.isFinite(e=+e)?e:t;function oT(e){return!!(e&&dn(e.append)&&e[Rm]==="FormData"&&e[ru])}const cT=e=>{const t=new Array(10),n=(r,i)=>{if(lc(r)){if(t.indexOf(r)>=0)return;if(fc(r))return r;if(!("toJSON"in r)){t[i]=r;const s=$s(r)?[]:{};return hc(r,(o,c)=>{const a=n(o,i+1);!Po(a)&&(s[c]=a)}),t[i]=void 0,s}}return r};return n(e,0)},aT=Gn("AsyncFunction"),uT=e=>e&&(lc(e)||dn(e))&&dn(e.then)&&dn(e.catch),Lm=((e,t)=>e?setImmediate:t?((n,r)=>(Pi.addEventListener("message",({source:i,data:s})=>{i===Pi&&s===n&&r.length&&r.shift()()},!1),i=>{r.push(i),Pi.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",dn(Pi.postMessage)),fT=typeof queueMicrotask<"u"?queueMicrotask.bind(Pi):typeof process<"u"&&process.nextTick||Lm,lT=e=>e!=null&&dn(e[ru]),z={isArray:$s,isArrayBuffer:Cm,isBuffer:fc,isFormData:FS,isArrayBufferView:OS,isString:BS,isNumber:Um,isBoolean:NS,isObject:lc,isPlainObject:Jc,isEmptyObject:kS,isReadableStream:LS,isRequest:qS,isResponse:VS,isHeaders:DS,isUndefined:Po,isDate:PS,isFile:RS,isBlob:CS,isRegExp:tT,isFunction:dn,isStream:HS,isURLSearchParams:MS,isTypedArray:YS,isFileList:US,forEach:hc,merge:Yf,extend:jS,trim:$S,stripBOM:KS,inherits:GS,toFlatObject:WS,kindOf:iu,kindOfTest:Gn,endsWith:XS,toArray:zS,forEachEntry:ZS,matchAll:JS,isHTMLForm:QS,hasOwnProperty:Kd,hasOwnProp:Kd,reduceDescriptors:Mm,freezeMethods:nT,toObjectSet:rT,toCamelCase:eT,noop:iT,toFiniteNumber:sT,findKey:Hm,global:Pi,isContextDefined:Fm,isSpecCompliantForm:oT,toJSONObject:cT,isAsyncFn:aT,isThenable:uT,setImmediate:Lm,asap:fT,isIterable:lT};function Pe(e,t,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=e,this.name="AxiosError",t&&(this.code=t),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}z.inherits(Pe,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:z.toJSONObject(this.config),code:this.code,status:this.status}}});const qm=Pe.prototype,Vm={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{Vm[e]={value:e}});Object.defineProperties(Pe,Vm);Object.defineProperty(qm,"isAxiosError",{value:!0});Pe.from=(e,t,n,r,i,s)=>{const o=Object.create(qm);return z.toFlatObject(e,o,function(a){return a!==Error.prototype},c=>c!=="isAxiosError"),Pe.call(o,e.message,t,n,r,i),o.cause=e,o.name=e.name,s&&Object.assign(o,s),o};const hT=null;function Zf(e){return z.isPlainObject(e)||z.isArray(e)}function Dm(e){return z.endsWith(e,"[]")?e.slice(0,-2):e}function Gd(e,t,n){return e?e.concat(t).map(function(i,s){return i=Dm(i),!n&&s?"["+i+"]":i}).join(n?".":""):t}function dT(e){return z.isArray(e)&&!e.some(Zf)}const pT=z.toFlatObject(z,{},null,function(t){return/^is[A-Z]/.test(t)});function ou(e,t,n){if(!z.isObject(e))throw new TypeError("target must be an object");t=t||new FormData,n=z.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(m,E){return!z.isUndefined(E[m])});const r=n.metaTokens,i=n.visitor||f,s=n.dots,o=n.indexes,a=(n.Blob||typeof Blob<"u"&&Blob)&&z.isSpecCompliantForm(t);if(!z.isFunction(i))throw new TypeError("visitor must be a function");function u(g){if(g===null)return"";if(z.isDate(g))return g.toISOString();if(z.isBoolean(g))return g.toString();if(!a&&z.isBlob(g))throw new Pe("Blob is not supported. Use a Buffer instead.");return z.isArrayBuffer(g)||z.isTypedArray(g)?a&&typeof Blob=="function"?new Blob([g]):Buffer.from(g):g}function f(g,m,E){let S=g;if(g&&!E&&typeof g=="object"){if(z.endsWith(m,"{}"))m=r?m:m.slice(0,-2),g=JSON.stringify(g);else if(z.isArray(g)&&dT(g)||(z.isFileList(g)||z.endsWith(m,"[]"))&&(S=z.toArray(g)))return m=Dm(m),S.forEach(function(w,T){!(z.isUndefined(w)||w===null)&&t.append(o===!0?Gd([m],T,s):o===null?m:m+"[]",u(w))}),!1}return Zf(g)?!0:(t.append(Gd(E,m,s),u(g)),!1)}const l=[],d=Object.assign(pT,{defaultVisitor:f,convertValue:u,isVisitable:Zf});function y(g,m){if(!z.isUndefined(g)){if(l.indexOf(g)!==-1)throw Error("Circular reference detected in "+m.join("."));l.push(g),z.forEach(g,function(S,_){(!(z.isUndefined(S)||S===null)&&i.call(t,S,z.isString(_)?_.trim():_,m,d))===!0&&y(S,m?m.concat(_):[_])}),l.pop()}}if(!z.isObject(e))throw new TypeError("data must be an object");return y(e),t}function Wd(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(r){return t[r]})}function jl(e,t){this._pairs=[],e&&ou(e,this,t)}const $m=jl.prototype;$m.append=function(t,n){this._pairs.push([t,n])};$m.toString=function(t){const n=t?function(r){return t.call(this,r,Wd)}:Wd;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function yT(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function jm(e,t,n){if(!t)return e;const r=n&&n.encode||yT;z.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let s;if(i?s=i(t,n):s=z.isURLSearchParams(t)?t.toString():new jl(t,n).toString(r),s){const o=e.indexOf("#");o!==-1&&(e=e.slice(0,o)),e+=(e.indexOf("?")===-1?"?":"&")+s}return e}class Xd{constructor(){this.handlers=[]}use(t,n,r){return this.handlers.push({fulfilled:t,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(t){this.handlers[t]&&(this.handlers[t]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(t){z.forEach(this.handlers,function(r){r!==null&&t(r)})}}const Km={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},gT=typeof URLSearchParams<"u"?URLSearchParams:jl,mT=typeof FormData<"u"?FormData:null,wT=typeof Blob<"u"?Blob:null,bT={isBrowser:!0,classes:{URLSearchParams:gT,FormData:mT,Blob:wT},protocols:["http","https","file","blob","url","data"]},Kl=typeof window<"u"&&typeof document<"u",Jf=typeof navigator=="object"&&navigator||void 0,ET=Kl&&(!Jf||["ReactNative","NativeScript","NS"].indexOf(Jf.product)<0),_T=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",ST=Kl&&window.location.href||"http://localhost",TT=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Kl,hasStandardBrowserEnv:ET,hasStandardBrowserWebWorkerEnv:_T,navigator:Jf,origin:ST},Symbol.toStringTag,{value:"Module"})),jt={...TT,...bT};function xT(e,t){return ou(e,new jt.classes.URLSearchParams,{visitor:function(n,r,i,s){return jt.isNode&&z.isBuffer(n)?(this.append(r,n.toString("base64")),!1):s.defaultVisitor.apply(this,arguments)},...t})}function AT(e){return z.matchAll(/\w+|\[(\w*)]/g,e).map(t=>t[0]==="[]"?"":t[1]||t[0])}function vT(e){const t={},n=Object.keys(e);let r;const i=n.length;let s;for(r=0;r<i;r++)s=n[r],t[s]=e[s];return t}function Gm(e){function t(n,r,i,s){let o=n[s++];if(o==="__proto__")return!0;const c=Number.isFinite(+o),a=s>=n.length;return o=!o&&z.isArray(i)?i.length:o,a?(z.hasOwnProp(i,o)?i[o]=[i[o],r]:i[o]=r,!c):((!i[o]||!z.isObject(i[o]))&&(i[o]=[]),t(n,r,i[o],s)&&z.isArray(i[o])&&(i[o]=vT(i[o])),!c)}if(z.isFormData(e)&&z.isFunction(e.entries)){const n={};return z.forEachEntry(e,(r,i)=>{t(AT(r),i,n,0)}),n}return null}function IT(e,t,n){if(z.isString(e))try{return(t||JSON.parse)(e),z.trim(e)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(e)}const dc={transitional:Km,adapter:["xhr","http","fetch"],transformRequest:[function(t,n){const r=n.getContentType()||"",i=r.indexOf("application/json")>-1,s=z.isObject(t);if(s&&z.isHTMLForm(t)&&(t=new FormData(t)),z.isFormData(t))return i?JSON.stringify(Gm(t)):t;if(z.isArrayBuffer(t)||z.isBuffer(t)||z.isStream(t)||z.isFile(t)||z.isBlob(t)||z.isReadableStream(t))return t;if(z.isArrayBufferView(t))return t.buffer;if(z.isURLSearchParams(t))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),t.toString();let c;if(s){if(r.indexOf("application/x-www-form-urlencoded")>-1)return xT(t,this.formSerializer).toString();if((c=z.isFileList(t))||r.indexOf("multipart/form-data")>-1){const a=this.env&&this.env.FormData;return ou(c?{"files[]":t}:t,a&&new a,this.formSerializer)}}return s||i?(n.setContentType("application/json",!1),IT(t)):t}],transformResponse:[function(t){const n=this.transitional||dc.transitional,r=n&&n.forcedJSONParsing,i=this.responseType==="json";if(z.isResponse(t)||z.isReadableStream(t))return t;if(t&&z.isString(t)&&(r&&!this.responseType||i)){const o=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(t)}catch(c){if(o)throw c.name==="SyntaxError"?Pe.from(c,Pe.ERR_BAD_RESPONSE,this,null,this.response):c}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:jt.classes.FormData,Blob:jt.classes.Blob},validateStatus:function(t){return t>=200&&t<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};z.forEach(["delete","get","head","post","put","patch"],e=>{dc.headers[e]={}});const OT=z.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),BT=e=>{const t={};let n,r,i;return e&&e.split(`
26
+ `).forEach(function(o){i=o.indexOf(":"),n=o.substring(0,i).trim().toLowerCase(),r=o.substring(i+1).trim(),!(!n||t[n]&&OT[n])&&(n==="set-cookie"?t[n]?t[n].push(r):t[n]=[r]:t[n]=t[n]?t[n]+", "+r:r)}),t},zd=Symbol("internals");function to(e){return e&&String(e).trim().toLowerCase()}function Qc(e){return e===!1||e==null?e:z.isArray(e)?e.map(Qc):String(e)}function NT(e){const t=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(e);)t[r[1]]=r[2];return t}const kT=e=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim());function Xu(e,t,n,r,i){if(z.isFunction(r))return r.call(this,t,n);if(i&&(t=n),!!z.isString(t)){if(z.isString(r))return t.indexOf(r)!==-1;if(z.isRegExp(r))return r.test(t)}}function PT(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(t,n,r)=>n.toUpperCase()+r)}function RT(e,t){const n=z.toCamelCase(" "+t);["get","set","has"].forEach(r=>{Object.defineProperty(e,r+n,{value:function(i,s,o){return this[r].call(this,t,i,s,o)},configurable:!0})})}let pn=class{constructor(t){t&&this.set(t)}set(t,n,r){const i=this;function s(c,a,u){const f=to(a);if(!f)throw new Error("header name must be a non-empty string");const l=z.findKey(i,f);(!l||i[l]===void 0||u===!0||u===void 0&&i[l]!==!1)&&(i[l||a]=Qc(c))}const o=(c,a)=>z.forEach(c,(u,f)=>s(u,f,a));if(z.isPlainObject(t)||t instanceof this.constructor)o(t,n);else if(z.isString(t)&&(t=t.trim())&&!kT(t))o(BT(t),n);else if(z.isObject(t)&&z.isIterable(t)){let c={},a,u;for(const f of t){if(!z.isArray(f))throw TypeError("Object iterator must return a key-value pair");c[u=f[0]]=(a=c[u])?z.isArray(a)?[...a,f[1]]:[a,f[1]]:f[1]}o(c,n)}else t!=null&&s(n,t,r);return this}get(t,n){if(t=to(t),t){const r=z.findKey(this,t);if(r){const i=this[r];if(!n)return i;if(n===!0)return NT(i);if(z.isFunction(n))return n.call(this,i,r);if(z.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(t,n){if(t=to(t),t){const r=z.findKey(this,t);return!!(r&&this[r]!==void 0&&(!n||Xu(this,this[r],r,n)))}return!1}delete(t,n){const r=this;let i=!1;function s(o){if(o=to(o),o){const c=z.findKey(r,o);c&&(!n||Xu(r,r[c],c,n))&&(delete r[c],i=!0)}}return z.isArray(t)?t.forEach(s):s(t),i}clear(t){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const s=n[r];(!t||Xu(this,this[s],s,t,!0))&&(delete this[s],i=!0)}return i}normalize(t){const n=this,r={};return z.forEach(this,(i,s)=>{const o=z.findKey(r,s);if(o){n[o]=Qc(i),delete n[s];return}const c=t?PT(s):String(s).trim();c!==s&&delete n[s],n[c]=Qc(i),r[c]=!0}),this}concat(...t){return this.constructor.concat(this,...t)}toJSON(t){const n=Object.create(null);return z.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=t&&z.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([t,n])=>t+": "+n).join(`
27
+ `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(i=>r.set(i)),r}static accessor(t){const r=(this[zd]=this[zd]={accessors:{}}).accessors,i=this.prototype;function s(o){const c=to(o);r[c]||(RT(i,o),r[c]=!0)}return z.isArray(t)?t.forEach(s):s(t),this}};pn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);z.reduceDescriptors(pn.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}});z.freezeMethods(pn);function zu(e,t){const n=this||dc,r=t||n,i=pn.from(r.headers);let s=r.data;return z.forEach(e,function(c){s=c.call(n,s,i.normalize(),t?t.status:void 0)}),i.normalize(),s}function Wm(e){return!!(e&&e.__CANCEL__)}function js(e,t,n){Pe.call(this,e??"canceled",Pe.ERR_CANCELED,t,n),this.name="CanceledError"}z.inherits(js,Pe,{__CANCEL__:!0});function Xm(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Pe("Request failed with status code "+n.status,[Pe.ERR_BAD_REQUEST,Pe.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function CT(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function UT(e,t){e=e||10;const n=new Array(e),r=new Array(e);let i=0,s=0,o;return t=t!==void 0?t:1e3,function(a){const u=Date.now(),f=r[s];o||(o=u),n[i]=a,r[i]=u;let l=s,d=0;for(;l!==i;)d+=n[l++],l=l%e;if(i=(i+1)%e,i===s&&(s=(s+1)%e),u-o<t)return;const y=f&&u-f;return y?Math.round(d*1e3/y):void 0}}function HT(e,t){let n=0,r=1e3/t,i,s;const o=(u,f=Date.now())=>{n=f,i=null,s&&(clearTimeout(s),s=null),e(...u)};return[(...u)=>{const f=Date.now(),l=f-n;l>=r?o(u,f):(i=u,s||(s=setTimeout(()=>{s=null,o(i)},r-l)))},()=>i&&o(i)]}const _a=(e,t,n=3)=>{let r=0;const i=UT(50,250);return HT(s=>{const o=s.loaded,c=s.lengthComputable?s.total:void 0,a=o-r,u=i(a),f=o<=c;r=o;const l={loaded:o,total:c,progress:c?o/c:void 0,bytes:a,rate:u||void 0,estimated:u&&c&&f?(c-o)/u:void 0,event:s,lengthComputable:c!=null,[t?"download":"upload"]:!0};e(l)},n)},Yd=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Zd=e=>(...t)=>z.asap(()=>e(...t)),FT=jt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,jt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(jt.origin),jt.navigator&&/(msie|trident)/i.test(jt.navigator.userAgent)):()=>!0,MT=jt.hasStandardBrowserEnv?{write(e,t,n,r,i,s){const o=[e+"="+encodeURIComponent(t)];z.isNumber(n)&&o.push("expires="+new Date(n).toGMTString()),z.isString(r)&&o.push("path="+r),z.isString(i)&&o.push("domain="+i),s===!0&&o.push("secure"),document.cookie=o.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function LT(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function qT(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function zm(e,t,n){let r=!LT(t);return e&&(r||n==!1)?qT(e,t):t}const Jd=e=>e instanceof pn?{...e}:e;function Ki(e,t){t=t||{};const n={};function r(u,f,l,d){return z.isPlainObject(u)&&z.isPlainObject(f)?z.merge.call({caseless:d},u,f):z.isPlainObject(f)?z.merge({},f):z.isArray(f)?f.slice():f}function i(u,f,l,d){if(z.isUndefined(f)){if(!z.isUndefined(u))return r(void 0,u,l,d)}else return r(u,f,l,d)}function s(u,f){if(!z.isUndefined(f))return r(void 0,f)}function o(u,f){if(z.isUndefined(f)){if(!z.isUndefined(u))return r(void 0,u)}else return r(void 0,f)}function c(u,f,l){if(l in t)return r(u,f);if(l in e)return r(void 0,u)}const a={url:s,method:s,data:s,baseURL:o,transformRequest:o,transformResponse:o,paramsSerializer:o,timeout:o,timeoutMessage:o,withCredentials:o,withXSRFToken:o,adapter:o,responseType:o,xsrfCookieName:o,xsrfHeaderName:o,onUploadProgress:o,onDownloadProgress:o,decompress:o,maxContentLength:o,maxBodyLength:o,beforeRedirect:o,transport:o,httpAgent:o,httpsAgent:o,cancelToken:o,socketPath:o,responseEncoding:o,validateStatus:c,headers:(u,f,l)=>i(Jd(u),Jd(f),l,!0)};return z.forEach(Object.keys({...e,...t}),function(f){const l=a[f]||i,d=l(e[f],t[f],f);z.isUndefined(d)&&l!==c||(n[f]=d)}),n}const Ym=e=>{const t=Ki({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:s,headers:o,auth:c}=t;t.headers=o=pn.from(o),t.url=jm(zm(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&o.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):"")));let a;if(z.isFormData(n)){if(jt.hasStandardBrowserEnv||jt.hasStandardBrowserWebWorkerEnv)o.setContentType(void 0);else if((a=o.getContentType())!==!1){const[u,...f]=a?a.split(";").map(l=>l.trim()).filter(Boolean):[];o.setContentType([u||"multipart/form-data",...f].join("; "))}}if(jt.hasStandardBrowserEnv&&(r&&z.isFunction(r)&&(r=r(t)),r||r!==!1&&FT(t.url))){const u=i&&s&&MT.read(s);u&&o.set(i,u)}return t},VT=typeof XMLHttpRequest<"u",DT=VT&&function(e){return new Promise(function(n,r){const i=Ym(e);let s=i.data;const o=pn.from(i.headers).normalize();let{responseType:c,onUploadProgress:a,onDownloadProgress:u}=i,f,l,d,y,g;function m(){y&&y(),g&&g(),i.cancelToken&&i.cancelToken.unsubscribe(f),i.signal&&i.signal.removeEventListener("abort",f)}let E=new XMLHttpRequest;E.open(i.method.toUpperCase(),i.url,!0),E.timeout=i.timeout;function S(){if(!E)return;const w=pn.from("getAllResponseHeaders"in E&&E.getAllResponseHeaders()),O={data:!c||c==="text"||c==="json"?E.responseText:E.response,status:E.status,statusText:E.statusText,headers:w,config:e,request:E};Xm(function(R){n(R),m()},function(R){r(R),m()},O),E=null}"onloadend"in E?E.onloadend=S:E.onreadystatechange=function(){!E||E.readyState!==4||E.status===0&&!(E.responseURL&&E.responseURL.indexOf("file:")===0)||setTimeout(S)},E.onabort=function(){E&&(r(new Pe("Request aborted",Pe.ECONNABORTED,e,E)),E=null)},E.onerror=function(){r(new Pe("Network Error",Pe.ERR_NETWORK,e,E)),E=null},E.ontimeout=function(){let T=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const O=i.transitional||Km;i.timeoutErrorMessage&&(T=i.timeoutErrorMessage),r(new Pe(T,O.clarifyTimeoutError?Pe.ETIMEDOUT:Pe.ECONNABORTED,e,E)),E=null},s===void 0&&o.setContentType(null),"setRequestHeader"in E&&z.forEach(o.toJSON(),function(T,O){E.setRequestHeader(O,T)}),z.isUndefined(i.withCredentials)||(E.withCredentials=!!i.withCredentials),c&&c!=="json"&&(E.responseType=i.responseType),u&&([d,g]=_a(u,!0),E.addEventListener("progress",d)),a&&E.upload&&([l,y]=_a(a),E.upload.addEventListener("progress",l),E.upload.addEventListener("loadend",y)),(i.cancelToken||i.signal)&&(f=w=>{E&&(r(!w||w.type?new js(null,e,E):w),E.abort(),E=null)},i.cancelToken&&i.cancelToken.subscribe(f),i.signal&&(i.signal.aborted?f():i.signal.addEventListener("abort",f)));const _=CT(i.url);if(_&&jt.protocols.indexOf(_)===-1){r(new Pe("Unsupported protocol "+_+":",Pe.ERR_BAD_REQUEST,e));return}E.send(s||null)})},$T=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,i;const s=function(u){if(!i){i=!0,c();const f=u instanceof Error?u:this.reason;r.abort(f instanceof Pe?f:new js(f instanceof Error?f.message:f))}};let o=t&&setTimeout(()=>{o=null,s(new Pe(`timeout ${t} of ms exceeded`,Pe.ETIMEDOUT))},t);const c=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(u=>{u.unsubscribe?u.unsubscribe(s):u.removeEventListener("abort",s)}),e=null)};e.forEach(u=>u.addEventListener("abort",s));const{signal:a}=r;return a.unsubscribe=()=>z.asap(c),a}},jT=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,i;for(;r<n;)i=r+t,yield e.slice(r,i),r=i},KT=async function*(e,t){for await(const n of GT(e))yield*jT(n,t)},GT=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},Qd=(e,t,n,r)=>{const i=KT(e,t);let s=0,o,c=a=>{o||(o=!0,r&&r(a))};return new ReadableStream({async pull(a){try{const{done:u,value:f}=await i.next();if(u){c(),a.close();return}let l=f.byteLength;if(n){let d=s+=l;n(d)}a.enqueue(new Uint8Array(f))}catch(u){throw c(u),u}},cancel(a){return c(a),i.return()}},{highWaterMark:2})},cu=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Zm=cu&&typeof ReadableStream=="function",WT=cu&&(typeof TextEncoder=="function"?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Jm=(e,...t)=>{try{return!!e(...t)}catch{return!1}},XT=Zm&&Jm(()=>{let e=!1;const t=new Request(jt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),e0=64*1024,Qf=Zm&&Jm(()=>z.isReadableStream(new Response("").body)),Sa={stream:Qf&&(e=>e.body)};cu&&(e=>{["text","arrayBuffer","blob","formData","stream"].forEach(t=>{!Sa[t]&&(Sa[t]=z.isFunction(e[t])?n=>n[t]():(n,r)=>{throw new Pe(`Response type '${t}' is not supported`,Pe.ERR_NOT_SUPPORT,r)})})})(new Response);const zT=async e=>{if(e==null)return 0;if(z.isBlob(e))return e.size;if(z.isSpecCompliantForm(e))return(await new Request(jt.origin,{method:"POST",body:e}).arrayBuffer()).byteLength;if(z.isArrayBufferView(e)||z.isArrayBuffer(e))return e.byteLength;if(z.isURLSearchParams(e)&&(e=e+""),z.isString(e))return(await WT(e)).byteLength},YT=async(e,t)=>{const n=z.toFiniteNumber(e.getContentLength());return n??zT(t)},ZT=cu&&(async e=>{let{url:t,method:n,data:r,signal:i,cancelToken:s,timeout:o,onDownloadProgress:c,onUploadProgress:a,responseType:u,headers:f,withCredentials:l="same-origin",fetchOptions:d}=Ym(e);u=u?(u+"").toLowerCase():"text";let y=$T([i,s&&s.toAbortSignal()],o),g;const m=y&&y.unsubscribe&&(()=>{y.unsubscribe()});let E;try{if(a&&XT&&n!=="get"&&n!=="head"&&(E=await YT(f,r))!==0){let O=new Request(t,{method:"POST",body:r,duplex:"half"}),A;if(z.isFormData(r)&&(A=O.headers.get("content-type"))&&f.setContentType(A),O.body){const[R,M]=Yd(E,_a(Zd(a)));r=Qd(O.body,e0,R,M)}}z.isString(l)||(l=l?"include":"omit");const S="credentials"in Request.prototype;g=new Request(t,{...d,signal:y,method:n.toUpperCase(),headers:f.normalize().toJSON(),body:r,duplex:"half",credentials:S?l:void 0});let _=await fetch(g,d);const w=Qf&&(u==="stream"||u==="response");if(Qf&&(c||w&&m)){const O={};["status","statusText","headers"].forEach(v=>{O[v]=_[v]});const A=z.toFiniteNumber(_.headers.get("content-length")),[R,M]=c&&Yd(A,_a(Zd(c),!0))||[];_=new Response(Qd(_.body,e0,R,()=>{M&&M(),m&&m()}),O)}u=u||"text";let T=await Sa[z.findKey(Sa,u)||"text"](_,e);return!w&&m&&m(),await new Promise((O,A)=>{Xm(O,A,{data:T,headers:pn.from(_.headers),status:_.status,statusText:_.statusText,config:e,request:g})})}catch(S){throw m&&m(),S&&S.name==="TypeError"&&/Load failed|fetch/i.test(S.message)?Object.assign(new Pe("Network Error",Pe.ERR_NETWORK,e,g),{cause:S.cause||S}):Pe.from(S,S&&S.code,e,g)}}),el={http:hT,xhr:DT,fetch:ZT};z.forEach(el,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const t0=e=>`- ${e}`,JT=e=>z.isFunction(e)||e===null||e===!1,Qm={getAdapter:e=>{e=z.isArray(e)?e:[e];const{length:t}=e;let n,r;const i={};for(let s=0;s<t;s++){n=e[s];let o;if(r=n,!JT(n)&&(r=el[(o=String(n)).toLowerCase()],r===void 0))throw new Pe(`Unknown adapter '${o}'`);if(r)break;i[o||"#"+s]=r}if(!r){const s=Object.entries(i).map(([c,a])=>`adapter ${c} `+(a===!1?"is not supported by the environment":"is not available in the build"));let o=t?s.length>1?`since :
28
28
  `+s.map(t0).join(`
29
- `):" "+t0(s[0]):"as no adapter specified";throw new Pe("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return r},adapters:el};function Yu(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new $s(null,e)}function n0(e){return Yu(e),e.headers=pn.from(e.headers),e.data=zu.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Qm.getAdapter(e.adapter||dc.adapter)(e).then(function(r){return Yu(e),r.data=zu.call(e,e.transformResponse,r),r.headers=pn.from(r.headers),r},function(r){return Wm(r)||(Yu(e),r&&r.response&&(r.response.data=zu.call(e,e.transformResponse,r.response),r.response.headers=pn.from(r.response.headers))),Promise.reject(r)})}const ew="1.11.0",au={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{au[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const r0={};au.transitional=function(t,n,r){function i(s,o){return"[Axios v"+ew+"] Transitional option '"+s+"'"+o+(r?". "+r:"")}return(s,o,c)=>{if(t===!1)throw new Pe(i(o," has been removed"+(n?" in "+n:"")),Pe.ERR_DEPRECATED);return n&&!r0[o]&&(r0[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,o,c):!0}};au.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function QT(e,t,n){if(typeof e!="object")throw new Pe("options must be an object",Pe.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let i=r.length;for(;i-- >0;){const s=r[i],o=t[s];if(o){const c=e[s],a=c===void 0||o(c,s,e);if(a!==!0)throw new Pe("option "+s+" must be "+a,Pe.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Pe("Unknown option "+s,Pe.ERR_BAD_OPTION)}}const ea={assertOptions:QT,validators:au},Yn=ea.validators;let Fi=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Xd,response:new Xd}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const s=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
30
- `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Ki(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:s}=n;r!==void 0&&ea.assertOptions(r,{silentJSONParsing:Yn.transitional(Yn.boolean),forcedJSONParsing:Yn.transitional(Yn.boolean),clarifyTimeoutError:Yn.transitional(Yn.boolean)},!1),i!=null&&(z.isFunction(i)?n.paramsSerializer={serialize:i}:ea.assertOptions(i,{encode:Yn.function,serialize:Yn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ea.assertOptions(n,{baseUrl:Yn.spelling("baseURL"),withXsrfToken:Yn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=s&&z.merge(s.common,s[n.method]);s&&z.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=pn.concat(o,s);const c=[];let a=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(a=a&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const u=[];this.interceptors.response.forEach(function(m){u.push(m.fulfilled,m.rejected)});let f,l=0,d;if(!a){const g=[n0.bind(this),void 0];for(g.unshift(...c),g.push(...u),d=g.length,f=Promise.resolve(n);l<d;)f=f.then(g[l++],g[l++]);return f}d=c.length;let y=n;for(l=0;l<d;){const g=c[l++],m=c[l++];try{y=g(y)}catch(E){m.call(this,E);break}}try{f=n0.call(this,y)}catch(g){return Promise.reject(g)}for(l=0,d=u.length;l<d;)f=f.then(u[l++],u[l++]);return f}getUri(t){t=Ki(this.defaults,t);const n=zm(t.baseURL,t.url,t.allowAbsoluteUrls);return jm(n,t.params,t.paramsSerializer)}};z.forEach(["delete","get","head","options"],function(t){Fi.prototype[t]=function(n,r){return this.request(Ki(r||{},{method:t,url:n,data:(r||{}).data}))}});z.forEach(["post","put","patch"],function(t){function n(r){return function(s,o,c){return this.request(Ki(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}Fi.prototype[t]=n(),Fi.prototype[t+"Form"]=n(!0)});let ex=class tw{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(i=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](i);r._listeners=null}),this.promise.then=i=>{let s;const o=new Promise(c=>{r.subscribe(c),s=c}).then(i);return o.cancel=function(){r.unsubscribe(s)},o},t(function(s,o,c){r.reason||(r.reason=new $s(s,o,c),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new tw(function(i){t=i}),cancel:t}}};function tx(e){return function(n){return e.apply(null,n)}}function nx(e){return z.isObject(e)&&e.isAxiosError===!0}const tl={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(tl).forEach(([e,t])=>{tl[t]=e});function nw(e){const t=new Fi(e),n=Pm(Fi.prototype.request,t);return z.extend(n,Fi.prototype,t,{allOwnKeys:!0}),z.extend(n,t,null,{allOwnKeys:!0}),n.create=function(i){return nw(Ki(e,i))},n}const ht=nw(dc);ht.Axios=Fi;ht.CanceledError=$s;ht.CancelToken=ex;ht.isCancel=Wm;ht.VERSION=ew;ht.toFormData=ou;ht.AxiosError=Pe;ht.Cancel=ht.CanceledError;ht.all=function(t){return Promise.all(t)};ht.spread=tx;ht.isAxiosError=nx;ht.mergeConfig=Ki;ht.AxiosHeaders=pn;ht.formToJSON=e=>Gm(z.isHTMLForm(e)?new FormData(e):e);ht.getAdapter=Qm.getAdapter;ht.HttpStatusCode=tl;ht.default=ht;const{Axios:r6,AxiosError:i6,CanceledError:s6,isCancel:o6,CancelToken:c6,VERSION:a6,all:u6,Cancel:f6,isAxiosError:l6,spread:h6,toFormData:d6,AxiosHeaders:p6,HttpStatusCode:y6,formToJSON:g6,getAdapter:m6,mergeConfig:w6}=ht;class rx{axios;constructor(t){this.axios=ht.create({baseURL:t.baseUrl,headers:{Accept:"application/json","Content-Type":"application/json","api-key":`${t.apiKey}`}})}async utxosByAddress(t,n,r=!0){return await this.axios.get(`/addresses/${t}/utxos?filter_dust=true&filter_dust_threshold=547&exclude_metaprotocols=${r}&order=asc&count=100${n?`&cursor=${n}`:""}`).then(s=>s.data)}async inscriptionIdsByCollectionSymbol(t,n){return await this.axios.get(`/assets/collections/${t}/inscriptions?count=100${n?`&cursor=${n}`:""}`).then(i=>i.data)}async runeUtxosByAddress(t,n,r){return await this.axios.get(`/addresses/${t}/runes/utxos?order_by=height&order=asc&count=100&rune=${n}${r?`&cursor=${r}`:""}`).then(s=>s.data)}async runeInfo(t){return await this.axios.get(`/assets/runes/${t}`).then(r=>r.data)}}var i0;(function(e){e[e.SysFatal=1]="SysFatal",e[e.SysTransient=2]="SysTransient",e[e.DestinationInvalid=3]="DestinationInvalid",e[e.CanisterReject=4]="CanisterReject",e[e.CanisterError=5]="CanisterError"})(i0||(i0={}));var Rs;(function(e){e.Replied="replied",e.Rejected="rejected"})(Rs||(Rs={}));function ix(e){return e!=null&&"reject_code"in e}function sx(e){return e!=null&&"certificate"in e}var Nr;(function(e){e.Trust="Trust",e.Protocol="Protocol",e.Reject="Reject",e.Transport="Transport",e.External="External",e.Limit="Limit",e.Input="Input",e.Unknown="Unknown"})(Nr||(Nr={}));class Ue{constructor(t=!1){this.isCertified=t}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`
29
+ `):" "+t0(s[0]):"as no adapter specified";throw new Pe("There is no suitable adapter to dispatch the request "+o,"ERR_NOT_SUPPORT")}return r},adapters:el};function Yu(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new js(null,e)}function n0(e){return Yu(e),e.headers=pn.from(e.headers),e.data=zu.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Qm.getAdapter(e.adapter||dc.adapter)(e).then(function(r){return Yu(e),r.data=zu.call(e,e.transformResponse,r),r.headers=pn.from(r.headers),r},function(r){return Wm(r)||(Yu(e),r&&r.response&&(r.response.data=zu.call(e,e.transformResponse,r.response),r.response.headers=pn.from(r.response.headers))),Promise.reject(r)})}const ew="1.11.0",au={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{au[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const r0={};au.transitional=function(t,n,r){function i(s,o){return"[Axios v"+ew+"] Transitional option '"+s+"'"+o+(r?". "+r:"")}return(s,o,c)=>{if(t===!1)throw new Pe(i(o," has been removed"+(n?" in "+n:"")),Pe.ERR_DEPRECATED);return n&&!r0[o]&&(r0[o]=!0,console.warn(i(o," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,o,c):!0}};au.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function QT(e,t,n){if(typeof e!="object")throw new Pe("options must be an object",Pe.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let i=r.length;for(;i-- >0;){const s=r[i],o=t[s];if(o){const c=e[s],a=c===void 0||o(c,s,e);if(a!==!0)throw new Pe("option "+s+" must be "+a,Pe.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Pe("Unknown option "+s,Pe.ERR_BAD_OPTION)}}const ea={assertOptions:QT,validators:au},Yn=ea.validators;let Fi=class{constructor(t){this.defaults=t||{},this.interceptors={request:new Xd,response:new Xd}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const s=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
30
+ `+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=Ki(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:s}=n;r!==void 0&&ea.assertOptions(r,{silentJSONParsing:Yn.transitional(Yn.boolean),forcedJSONParsing:Yn.transitional(Yn.boolean),clarifyTimeoutError:Yn.transitional(Yn.boolean)},!1),i!=null&&(z.isFunction(i)?n.paramsSerializer={serialize:i}:ea.assertOptions(i,{encode:Yn.function,serialize:Yn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),ea.assertOptions(n,{baseUrl:Yn.spelling("baseURL"),withXsrfToken:Yn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let o=s&&z.merge(s.common,s[n.method]);s&&z.forEach(["delete","get","head","post","put","patch","common"],g=>{delete s[g]}),n.headers=pn.concat(o,s);const c=[];let a=!0;this.interceptors.request.forEach(function(m){typeof m.runWhen=="function"&&m.runWhen(n)===!1||(a=a&&m.synchronous,c.unshift(m.fulfilled,m.rejected))});const u=[];this.interceptors.response.forEach(function(m){u.push(m.fulfilled,m.rejected)});let f,l=0,d;if(!a){const g=[n0.bind(this),void 0];for(g.unshift(...c),g.push(...u),d=g.length,f=Promise.resolve(n);l<d;)f=f.then(g[l++],g[l++]);return f}d=c.length;let y=n;for(l=0;l<d;){const g=c[l++],m=c[l++];try{y=g(y)}catch(E){m.call(this,E);break}}try{f=n0.call(this,y)}catch(g){return Promise.reject(g)}for(l=0,d=u.length;l<d;)f=f.then(u[l++],u[l++]);return f}getUri(t){t=Ki(this.defaults,t);const n=zm(t.baseURL,t.url,t.allowAbsoluteUrls);return jm(n,t.params,t.paramsSerializer)}};z.forEach(["delete","get","head","options"],function(t){Fi.prototype[t]=function(n,r){return this.request(Ki(r||{},{method:t,url:n,data:(r||{}).data}))}});z.forEach(["post","put","patch"],function(t){function n(r){return function(s,o,c){return this.request(Ki(c||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:o}))}}Fi.prototype[t]=n(),Fi.prototype[t+"Form"]=n(!0)});let ex=class tw{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(i=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](i);r._listeners=null}),this.promise.then=i=>{let s;const o=new Promise(c=>{r.subscribe(c),s=c}).then(i);return o.cancel=function(){r.unsubscribe(s)},o},t(function(s,o,c){r.reason||(r.reason=new js(s,o,c),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new tw(function(i){t=i}),cancel:t}}};function tx(e){return function(n){return e.apply(null,n)}}function nx(e){return z.isObject(e)&&e.isAxiosError===!0}const tl={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(tl).forEach(([e,t])=>{tl[t]=e});function nw(e){const t=new Fi(e),n=Pm(Fi.prototype.request,t);return z.extend(n,Fi.prototype,t,{allOwnKeys:!0}),z.extend(n,t,null,{allOwnKeys:!0}),n.create=function(i){return nw(Ki(e,i))},n}const ht=nw(dc);ht.Axios=Fi;ht.CanceledError=js;ht.CancelToken=ex;ht.isCancel=Wm;ht.VERSION=ew;ht.toFormData=ou;ht.AxiosError=Pe;ht.Cancel=ht.CanceledError;ht.all=function(t){return Promise.all(t)};ht.spread=tx;ht.isAxiosError=nx;ht.mergeConfig=Ki;ht.AxiosHeaders=pn;ht.formToJSON=e=>Gm(z.isHTMLForm(e)?new FormData(e):e);ht.getAdapter=Qm.getAdapter;ht.HttpStatusCode=tl;ht.default=ht;const{Axios:r6,AxiosError:i6,CanceledError:s6,isCancel:o6,CancelToken:c6,VERSION:a6,all:u6,Cancel:f6,isAxiosError:l6,spread:h6,toFormData:d6,AxiosHeaders:p6,HttpStatusCode:y6,formToJSON:g6,getAdapter:m6,mergeConfig:w6}=ht;class rx{axios;constructor(t){this.axios=ht.create({baseURL:t.baseUrl,headers:{Accept:"application/json","Content-Type":"application/json","api-key":`${t.apiKey}`}})}async utxosByAddress(t,n,r=!0){return await this.axios.get(`/addresses/${t}/utxos?filter_dust=true&filter_dust_threshold=547&exclude_metaprotocols=${r}&order=asc&count=100${n?`&cursor=${n}`:""}`).then(s=>s.data)}async inscriptionIdsByCollectionSymbol(t,n){return await this.axios.get(`/assets/collections/${t}/inscriptions?count=100${n?`&cursor=${n}`:""}`).then(i=>i.data)}async runeUtxosByAddress(t,n,r){return await this.axios.get(`/addresses/${t}/runes/utxos?order_by=height&order=asc&count=100&rune=${n}${r?`&cursor=${r}`:""}`).then(s=>s.data)}async runeInfo(t){return await this.axios.get(`/assets/runes/${t}`).then(r=>r.data)}}var i0;(function(e){e[e.SysFatal=1]="SysFatal",e[e.SysTransient=2]="SysTransient",e[e.DestinationInvalid=3]="DestinationInvalid",e[e.CanisterReject=4]="CanisterReject",e[e.CanisterError=5]="CanisterError"})(i0||(i0={}));var Cs;(function(e){e.Replied="replied",e.Rejected="rejected"})(Cs||(Cs={}));function ix(e){return e!=null&&"reject_code"in e}function sx(e){return e!=null&&"certificate"in e}var Nr;(function(e){e.Trust="Trust",e.Protocol="Protocol",e.Reject="Reject",e.Transport="Transport",e.External="External",e.Limit="Limit",e.Input="Input",e.Unknown="Unknown"})(Nr||(Nr={}));class Ue{constructor(t=!1){this.isCertified=t}toString(){let t=this.toErrorMessage();return this.requestContext&&(t+=`
31
31
  Request context:
32
32
  Request ID (hex): ${this.requestContext.requestId?rt(this.requestContext.requestId):"undefined"}
33
33
  Sender pubkey (hex): ${rt(this.requestContext.senderPubKey)}
@@ -36,7 +36,7 @@ Request context:
36
36
  Call context:
37
37
  Canister ID: ${this.callContext.canisterId.toText()}
38
38
  Method name: ${this.callContext.methodName}
39
- HTTP details: ${JSON.stringify(this.callContext.httpDetails,null,2)}`),t}}class br extends Error{get code(){return this.cause.code}set code(t){this.cause.code=t}get kind(){return this.cause.kind}set kind(t){this.cause.kind=t}get isCertified(){return this.code.isCertified}constructor(t,n){super(t.toString()),this.name="AgentError",this.cause={code:t,kind:n},Object.setPrototypeOf(this,br.prototype)}hasCode(t){return this.code instanceof t}toString(){return`${this.name} (${this.kind}): ${this.message}`}}class Yi extends br{static fromCode(t){return new this(t)}}class An extends Yi{constructor(t){super(t,Nr.Trust),this.name="TrustError",Object.setPrototypeOf(this,An.prototype)}}class yt extends Yi{constructor(t){super(t,Nr.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,yt.prototype)}}class bs extends Yi{constructor(t){super(t,Nr.Reject),this.name="RejectError",Object.setPrototypeOf(this,bs.prototype)}}class Ta extends Yi{constructor(t){super(t,Nr.Transport),this.name="TransportError",Object.setPrototypeOf(this,Ta.prototype)}}class cn extends Yi{constructor(t){super(t,Nr.External),this.name="ExternalError",Object.setPrototypeOf(this,cn.prototype)}}class tt extends Yi{constructor(t){super(t,Nr.Input),this.name="InputError",Object.setPrototypeOf(this,tt.prototype)}}class an extends Yi{constructor(t){super(t,Nr.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,an.prototype)}}class Es extends Ue{constructor(t,n){super(),this.reason=t,this.error=n,this.name="CertificateVerificationErrorCode",Object.setPrototypeOf(this,Es.prototype)}toErrorMessage(){let t=this.reason;return this.error&&(t+=`: ${yc(this.error)}`),`Certificate verification error: "${t}"`}}class Ro extends Ue{constructor(t,n,r,i,s){super(),this.maxAgeInMinutes=t,this.certificateTime=n,this.currentTime=r,this.timeDiffMsecs=i,this.ageType=s,this.name="CertificateTimeErrorCode",Object.setPrototypeOf(this,Ro.prototype)}toErrorMessage(){return`Certificate is signed more than ${this.maxAgeInMinutes} minutes in the ${this.ageType}. Certificate time: ${this.certificateTime.toISOString()} Current time: ${this.currentTime.toISOString()} Clock drift: ${this.timeDiffMsecs}ms`}}class Gl extends Ue{constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,Gl.prototype)}toErrorMessage(){return"Certificate has too many delegations"}}class uu extends Ue{constructor(t,n){super(),this.canisterId=t,this.subnetId=n,this.name="CertificateNotAuthorizedErrorCode",Object.setPrototypeOf(this,uu.prototype)}toErrorMessage(){return`The certificate contains a delegation that does not include the canister ${this.canisterId.toText()} in the canister_ranges field. Subnet ID: ${this.subnetId.toText()}`}}class Cs extends Ue{constructor(t,n){super(),this.message=t,this.lookupStatus=n,this.name="LookupErrorCode",Object.setPrototypeOf(this,Cs.prototype)}toErrorMessage(){return`${this.message}. Lookup status: ${this.lookupStatus}`}}class fu extends Ue{constructor(t){super(),this.message=t,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,fu.prototype)}toErrorMessage(){return this.message}}class Wl extends Ue{constructor(t){super(),this.message=t,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,Wl.prototype)}toErrorMessage(){return this.message}}class lu extends Ue{constructor(t,n){super(),this.expectedLength=t,this.actualLength=n,this.name="DerKeyLengthMismatchErrorCode",Object.setPrototypeOf(this,lu.prototype)}toErrorMessage(){return`BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`}}class Xl extends Ue{constructor(t,n){super(),this.expectedPrefix=t,this.actualPrefix=n,this.name="DerPrefixMismatchErrorCode",Object.setPrototypeOf(this,Xl.prototype)}toErrorMessage(){return`BLS DER-encoded public key is invalid. Expected the following prefix: ${rt(this.expectedPrefix)}, but got ${rt(this.actualPrefix)}`}}class zl extends Ue{constructor(t,n){super(),this.expectedLength=t,this.actualLength=n,this.name="DerDecodeLengthMismatchErrorCode",Object.setPrototypeOf(this,zl.prototype)}toErrorMessage(){return`DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`}}class kr extends Ue{constructor(t){super(),this.error=t,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,kr.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}}class hu extends Ue{constructor(t){super(),this.error=t,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,hu.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}}class Yl extends Ue{constructor(t,n){super(),this.error=t,this.input=n,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,Yl.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${yc(this.error)}, input: ${rt(this.input)}`}}class Zl extends Ue{constructor(t,n){super(),this.error=t,this.value=n,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,Zl.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${yc(this.error)}, input: ${this.value}`}}class Co extends Ue{constructor(t,n,r){super(),this.message=t,this.requestId=n,this.status=r,this.name="TimeoutWaitingForResponseErrorCode",Object.setPrototypeOf(this,Co.prototype)}toErrorMessage(){let t=`${this.message}
39
+ HTTP details: ${JSON.stringify(this.callContext.httpDetails,null,2)}`),t}}class br extends Error{get code(){return this.cause.code}set code(t){this.cause.code=t}get kind(){return this.cause.kind}set kind(t){this.cause.kind=t}get isCertified(){return this.code.isCertified}constructor(t,n){super(t.toString()),this.name="AgentError",this.cause={code:t,kind:n},Object.setPrototypeOf(this,br.prototype)}hasCode(t){return this.code instanceof t}toString(){return`${this.name} (${this.kind}): ${this.message}`}}class Yi extends br{static fromCode(t){return new this(t)}}class An extends Yi{constructor(t){super(t,Nr.Trust),this.name="TrustError",Object.setPrototypeOf(this,An.prototype)}}class yt extends Yi{constructor(t){super(t,Nr.Protocol),this.name="ProtocolError",Object.setPrototypeOf(this,yt.prototype)}}class Es extends Yi{constructor(t){super(t,Nr.Reject),this.name="RejectError",Object.setPrototypeOf(this,Es.prototype)}}class Ta extends Yi{constructor(t){super(t,Nr.Transport),this.name="TransportError",Object.setPrototypeOf(this,Ta.prototype)}}class an extends Yi{constructor(t){super(t,Nr.External),this.name="ExternalError",Object.setPrototypeOf(this,an.prototype)}}class tt extends Yi{constructor(t){super(t,Nr.Input),this.name="InputError",Object.setPrototypeOf(this,tt.prototype)}}class un extends Yi{constructor(t){super(t,Nr.Unknown),this.name="UnknownError",Object.setPrototypeOf(this,un.prototype)}}class _s extends Ue{constructor(t,n){super(),this.reason=t,this.error=n,this.name="CertificateVerificationErrorCode",Object.setPrototypeOf(this,_s.prototype)}toErrorMessage(){let t=this.reason;return this.error&&(t+=`: ${yc(this.error)}`),`Certificate verification error: "${t}"`}}class Ro extends Ue{constructor(t,n,r,i,s){super(),this.maxAgeInMinutes=t,this.certificateTime=n,this.currentTime=r,this.timeDiffMsecs=i,this.ageType=s,this.name="CertificateTimeErrorCode",Object.setPrototypeOf(this,Ro.prototype)}toErrorMessage(){return`Certificate is signed more than ${this.maxAgeInMinutes} minutes in the ${this.ageType}. Certificate time: ${this.certificateTime.toISOString()} Current time: ${this.currentTime.toISOString()} Clock drift: ${this.timeDiffMsecs}ms`}}class Gl extends Ue{constructor(){super(),this.name="CertificateHasTooManyDelegationsErrorCode",Object.setPrototypeOf(this,Gl.prototype)}toErrorMessage(){return"Certificate has too many delegations"}}class uu extends Ue{constructor(t,n){super(),this.canisterId=t,this.subnetId=n,this.name="CertificateNotAuthorizedErrorCode",Object.setPrototypeOf(this,uu.prototype)}toErrorMessage(){return`The certificate contains a delegation that does not include the canister ${this.canisterId.toText()} in the canister_ranges field. Subnet ID: ${this.subnetId.toText()}`}}class Us extends Ue{constructor(t,n){super(),this.message=t,this.lookupStatus=n,this.name="LookupErrorCode",Object.setPrototypeOf(this,Us.prototype)}toErrorMessage(){return`${this.message}. Lookup status: ${this.lookupStatus}`}}class fu extends Ue{constructor(t){super(),this.message=t,this.name="MalformedLookupFoundValueErrorCode",Object.setPrototypeOf(this,fu.prototype)}toErrorMessage(){return this.message}}class Wl extends Ue{constructor(t){super(),this.message=t,this.name="MissingLookupValueErrorCode",Object.setPrototypeOf(this,Wl.prototype)}toErrorMessage(){return this.message}}class lu extends Ue{constructor(t,n){super(),this.expectedLength=t,this.actualLength=n,this.name="DerKeyLengthMismatchErrorCode",Object.setPrototypeOf(this,lu.prototype)}toErrorMessage(){return`BLS DER-encoded public key must be ${this.expectedLength} bytes long, but is ${this.actualLength} bytes long`}}class Xl extends Ue{constructor(t,n){super(),this.expectedPrefix=t,this.actualPrefix=n,this.name="DerPrefixMismatchErrorCode",Object.setPrototypeOf(this,Xl.prototype)}toErrorMessage(){return`BLS DER-encoded public key is invalid. Expected the following prefix: ${rt(this.expectedPrefix)}, but got ${rt(this.actualPrefix)}`}}class zl extends Ue{constructor(t,n){super(),this.expectedLength=t,this.actualLength=n,this.name="DerDecodeLengthMismatchErrorCode",Object.setPrototypeOf(this,zl.prototype)}toErrorMessage(){return`DER payload mismatch: Expected length ${this.expectedLength}, actual length: ${this.actualLength}`}}class kr extends Ue{constructor(t){super(),this.error=t,this.name="DerDecodeErrorCode",Object.setPrototypeOf(this,kr.prototype)}toErrorMessage(){return`Failed to decode DER: ${this.error}`}}class hu extends Ue{constructor(t){super(),this.error=t,this.name="DerEncodeErrorCode",Object.setPrototypeOf(this,hu.prototype)}toErrorMessage(){return`Failed to encode DER: ${this.error}`}}class Yl extends Ue{constructor(t,n){super(),this.error=t,this.input=n,this.name="CborDecodeErrorCode",Object.setPrototypeOf(this,Yl.prototype)}toErrorMessage(){return`Failed to decode CBOR: ${yc(this.error)}, input: ${rt(this.input)}`}}class Zl extends Ue{constructor(t,n){super(),this.error=t,this.value=n,this.name="CborEncodeErrorCode",Object.setPrototypeOf(this,Zl.prototype)}toErrorMessage(){return`Failed to encode CBOR: ${yc(this.error)}, input: ${this.value}`}}class Co extends Ue{constructor(t,n,r){super(),this.message=t,this.requestId=n,this.status=r,this.name="TimeoutWaitingForResponseErrorCode",Object.setPrototypeOf(this,Co.prototype)}toErrorMessage(){let t=`${this.message}
40
40
  `;return this.requestId&&(t+=` Request ID: ${rt(this.requestId)}
41
41
  `),this.status&&(t+=` Request status: ${this.status}
42
42
  `),t}}class Jl extends Ue{constructor(t,n,r){super(),this.maxIngressExpiryInMinutes=t,this.requestId=n,this.retryTimes=r,this.name="CertificateOutdatedErrorCode",Object.setPrototypeOf(this,Jl.prototype)}toErrorMessage(){let t=`Certificate is stale (over ${this.maxIngressExpiryInMinutes} minutes). Is the computer's clock synchronized?
@@ -58,32 +58,32 @@ Call context:
58
58
  Error code: ${this.rejectErrorCode}
59
59
  `}}class th extends Ue{constructor(t){super(),this.requestId=t,this.name="RequestStatusDoneNoReplyErrorCode",Object.setPrototypeOf(this,th.prototype)}toErrorMessage(){return`Call was marked as done but we never saw the reply:
60
60
  Request ID: ${rt(this.requestId)}
61
- `}}class js extends Ue{constructor(t){super(),this.shouldFetchRootKey=t,this.name="MissingRootKeyErrorCode",Object.setPrototypeOf(this,js.prototype)}toErrorMessage(){return this.shouldFetchRootKey===void 0?"Agent is missing root key":`Agent is missing root key and the shouldFetchRootKey value is set to ${this.shouldFetchRootKey}. The root key should only be unknown if you are in local development. Otherwise you should avoid fetching and use the default IC Root Key or the known root key of your environment.`}}class nh extends Ue{constructor(t){super(),this.value=t,this.name="HashValueErrorCode",Object.setPrototypeOf(this,nh.prototype)}toErrorMessage(){return`Attempt to hash a value of unsupported type: ${this.value}`}}class To extends Ue{constructor(t){super(),this.error=t,this.name="HttpDefaultFetchErrorCode",Object.setPrototypeOf(this,To.prototype)}toErrorMessage(){return this.error}}class Ni extends Ue{constructor(){super(),this.name="IdentityInvalidErrorCode",Object.setPrototypeOf(this,Ni.prototype)}toErrorMessage(){return"This identity has expired due this application's security policy. Please refresh your authentication."}}class ds extends Ue{constructor(t,n){super(),this.message=t,this.providedIngressExpiryInMinutes=n,this.name="IngressExpiryInvalidErrorCode",Object.setPrototypeOf(this,ds.prototype)}toErrorMessage(){return`${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`}}class rh extends Ue{constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,rh.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}}class ih extends Ue{constructor(t){super(),this.error=t,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,ih.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}}class sh extends Ue{constructor(){super(),this.name="MissingSignatureErrorCode",Object.setPrototypeOf(this,sh.prototype)}toErrorMessage(){return"Query response did not contain any node signatures"}}class oh extends Ue{constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,oh.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}}class ch extends Ue{constructor(t){super(),this.nodeId=t,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,ch.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}}class qn extends Ue{constructor(t){super(),this.error=t,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,qn.prototype)}toErrorMessage(){return`Unexpected error: ${yc(this.error)}`}}class pc extends Ue{constructor(t){super(),this.error=t,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,pc.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}}class xa extends Ue{constructor(t,n,r,i){super(),this.status=t,this.statusText=n,this.headers=r,this.bodyText=i,this.name="HttpErrorCode",Object.setPrototypeOf(this,xa.prototype)}toErrorMessage(){let t=`HTTP request failed:
61
+ `}}class Ks extends Ue{constructor(t){super(),this.shouldFetchRootKey=t,this.name="MissingRootKeyErrorCode",Object.setPrototypeOf(this,Ks.prototype)}toErrorMessage(){return this.shouldFetchRootKey===void 0?"Agent is missing root key":`Agent is missing root key and the shouldFetchRootKey value is set to ${this.shouldFetchRootKey}. The root key should only be unknown if you are in local development. Otherwise you should avoid fetching and use the default IC Root Key or the known root key of your environment.`}}class nh extends Ue{constructor(t){super(),this.value=t,this.name="HashValueErrorCode",Object.setPrototypeOf(this,nh.prototype)}toErrorMessage(){return`Attempt to hash a value of unsupported type: ${this.value}`}}class To extends Ue{constructor(t){super(),this.error=t,this.name="HttpDefaultFetchErrorCode",Object.setPrototypeOf(this,To.prototype)}toErrorMessage(){return this.error}}class Ni extends Ue{constructor(){super(),this.name="IdentityInvalidErrorCode",Object.setPrototypeOf(this,Ni.prototype)}toErrorMessage(){return"This identity has expired due this application's security policy. Please refresh your authentication."}}class ps extends Ue{constructor(t,n){super(),this.message=t,this.providedIngressExpiryInMinutes=n,this.name="IngressExpiryInvalidErrorCode",Object.setPrototypeOf(this,ps.prototype)}toErrorMessage(){return`${this.message}. Provided ingress expiry time is ${this.providedIngressExpiryInMinutes} minutes.`}}class rh extends Ue{constructor(){super(),this.name="CreateHttpAgentErrorCode",Object.setPrototypeOf(this,rh.prototype)}toErrorMessage(){return"Failed to create agent from provided agent"}}class ih extends Ue{constructor(t){super(),this.error=t,this.name="MalformedSignatureErrorCode",Object.setPrototypeOf(this,ih.prototype)}toErrorMessage(){return`Query response contained a malformed signature: ${this.error}`}}class sh extends Ue{constructor(){super(),this.name="MissingSignatureErrorCode",Object.setPrototypeOf(this,sh.prototype)}toErrorMessage(){return"Query response did not contain any node signatures"}}class oh extends Ue{constructor(){super(),this.name="MalformedPublicKeyErrorCode",Object.setPrototypeOf(this,oh.prototype)}toErrorMessage(){return"Read state response contained a malformed public key"}}class ch extends Ue{constructor(t){super(),this.nodeId=t,this.name="QuerySignatureVerificationFailedErrorCode",Object.setPrototypeOf(this,ch.prototype)}toErrorMessage(){return`Query signature verification failed. Node ID: ${this.nodeId}`}}class qn extends Ue{constructor(t){super(),this.error=t,this.name="UnexpectedErrorCode",Object.setPrototypeOf(this,qn.prototype)}toErrorMessage(){return`Unexpected error: ${yc(this.error)}`}}class pc extends Ue{constructor(t){super(),this.error=t,this.name="HashTreeDecodeErrorCode",Object.setPrototypeOf(this,pc.prototype)}toErrorMessage(){return`Failed to decode certificate: ${this.error}`}}class xa extends Ue{constructor(t,n,r,i){super(),this.status=t,this.statusText=n,this.headers=r,this.bodyText=i,this.name="HttpErrorCode",Object.setPrototypeOf(this,xa.prototype)}toErrorMessage(){let t=`HTTP request failed:
62
62
  Status: ${this.status} (${this.statusText})
63
63
  Headers: ${JSON.stringify(this.headers)}
64
64
  `;return this.bodyText&&(t+=` Body: ${this.bodyText}
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: ${yc(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 yc(e){if(e instanceof Error)return e.stack??e.message;try{return JSON.stringify(e)}catch{return String(e)}}const _s=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 rw(e);if(typeof e=="number")return bn(ft(e));if(e instanceof Uint8Array||ArrayBuffer.isView(e))return bn(Ba(e));if(Array.isArray(e)){const t=e.map(nl);return bn($e(...t))}else{if(e&&typeof e=="object"&&e._isPrincipal)return bn(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 bn(ft(e))}throw tt.fromCode(new nh(e))}const rw=e=>{const t=new TextEncoder().encode(e);return bn(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=rw(o),u=nl(c);return[a,u]}).sort(([o],[c])=>mS(o,c)),i=$e(...r.map(o=>$e(...o)));return bn(i)}new TextEncoder().encode(`
66
- ic-request`);const ox=new TextEncoder().encode("\vic-response");new TextEncoder().encode("ic-request-auth-delegation");class s0{getPrincipal(){return Ge.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}}class Zi extends Error{constructor(t){super(t),this.name="DecodingError"}}const iw=55799,sw=Symbol("CBOR_STOP_CODE");var Vn=(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))(Vn||{}),xt=(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))(xt||{});const cx=23,ax=255,ux=65535,fx=4294967295,lx=BigInt("0xffffffffffffffff");var Ln=(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))(Ln||{});const Ss=!1;function hx(e){return e==null}function ow(e,t){const n=new Uint8Array(t);return n.set(e),n}const dx=new TextDecoder;function px(e){return(e&224)>>5}function yx(e){return e&31}let Uo=new Uint8Array,to,Dn=0;function gx(e,t){Uo=e,Dn=0;const n=Mi();return t?.(n)??n}function Mi(e){const[t,n]=ta();switch(t){case xt.UnsignedInteger:return Ks(n);case xt.NegativeInteger:return Ex(n);case xt.ByteString:return cw(n);case xt.TextString:return rl(n);case xt.Array:return mx(n);case xt.Map:return bx(n);case xt.Tag:return _x(n);case xt.Simple:return wx(n)}throw new Zi(`Unsupported major type: ${t}`)}function ta(){const e=Uo.at(Dn);if(hx(e))throw new Zi("Provided CBOR data is empty");const t=px(e),n=yx(e);return Dn++,[t,n]}function mx(e,t){const n=Ks(e);if(n===1/0){const i=[];let s=Mi();for(;s!==sw;)i.push(s),s=Mi();return i}const r=new Array(n);for(let i=0;i<n;i++){const s=Mi();r[i]=s}return r}function wx(e){switch(e){case Vn.False:return!1;case Vn.True:return!0;case Vn.Null:return null;case Vn.Undefined:return;case Vn.Break:return sw}throw new Zi(`Unrecognized simple type: ${e.toString(2)}`)}function bx(e,t){const n=Ks(e),r={};if(n===1/0){let[i,s]=ta();for(;i!==xt.Simple&&s!==Vn.Break;){const o=rl(s),c=Mi();r[o]=c,[i,s]=ta()}return r}for(let i=0;i<n;i++){const[s,o]=ta();if(s!==xt.TextString)throw new Zi("Map keys must be text strings");const c=rl(o),a=Mi();r[c]=a}return r}function Ks(e){if(e<=Ln.Value)return e;switch(to=new DataView(Uo.buffer,Uo.byteOffset+Dn),e){case Ln.OneByte:return Dn++,to.getUint8(0);case Ln.TwoBytes:return Dn+=2,to.getUint16(0,Ss);case Ln.FourBytes:return Dn+=4,to.getUint32(0,Ss);case Ln.EightBytes:return Dn+=8,to.getBigUint64(0,Ss);case Ln.Indefinite:return 1/0;default:throw new Zi(`Unsupported integer info: ${e.toString(2)}`)}}function Ex(e){const t=Ks(e);return typeof t=="number"?-1-t:-1n-t}function cw(e){const t=Ks(e);if(t>Number.MAX_SAFE_INTEGER)throw new Zi("Byte length is too large");const n=Number(t);return Dn+=n,Uo.slice(Dn-n,Dn)}function rl(e){const t=cw(e);return dx.decode(t)}function _x(e,t){const n=Ks(e);if(n===iw)return Mi();throw new Zi(`Unsupported tag: ${n}.`)}class uh extends Error{constructor(t){super(t),this.name="SerializationError"}}const Sx=2*1024,Tx=100,xx=new TextEncoder;function no(e){return e<<5}let mn=new Uint8Array(Sx),Hn=new DataView(mn.buffer),Tt=0,Ju=[];function Ax(e,t){Tt=0;const n=t?.(e)??e;return Rx(iw,n,t),mn.slice(0,Tt)}function fh(e,t){if(Tt>mn.length-Tx&&(mn=ow(mn,mn.length*2),Hn=new DataView(mn.buffer)),e===!1||e===!0||e===null||e===void 0){Ox(e);return}if(typeof e=="number"||typeof e=="bigint"){Px(e);return}if(typeof e=="string"){fw(e);return}if(e instanceof Uint8Array){o0(e);return}if(e instanceof ArrayBuffer){o0(new Uint8Array(e));return}if(Array.isArray(e)){vx(e,t);return}if(typeof e=="object"){Ix(e,t);return}throw new uh(`Unsupported type: ${typeof e}`)}function vx(e,t){Gs(xt.Array,e.length),e.forEach((n,r)=>{fh(t?.(n,r.toString())??n,t)})}function Ix(e,t){Ju=Object.entries(e),Gs(xt.Map,Ju.length),Ju.forEach(([n,r])=>{fw(n),fh(t?.(r,n)??r,t)})}function Gs(e,t){if(t<=cx){Hn.setUint8(Tt++,no(e)|Number(t));return}if(t<=ax){Hn.setUint8(Tt++,no(e)|Ln.OneByte),Hn.setUint8(Tt,Number(t)),Tt+=1;return}if(t<=ux){Hn.setUint8(Tt++,no(e)|Ln.TwoBytes),Hn.setUint16(Tt,Number(t),Ss),Tt+=2;return}if(t<=fx){Hn.setUint8(Tt++,no(e)|Ln.FourBytes),Hn.setUint32(Tt,Number(t),Ss),Tt+=4;return}if(t<=lx){Hn.setUint8(Tt++,no(e)|Ln.EightBytes),Hn.setBigUint64(Tt,BigInt(t),Ss),Tt+=8;return}throw new uh(`Value too large to encode: ${t}`)}function Ox(e){Gs(xt.Simple,Bx(e))}function Bx(e){if(e===!1)return Vn.False;if(e===!0)return Vn.True;if(e===null)return Vn.Null;if(e===void 0)return Vn.Undefined;throw new uh(`Unrecognized simple value: ${e.toString()}`)}function aw(e,t){Gs(e,t.length),Tt>mn.length-t.length&&(mn=ow(mn,mn.length+t.length),Hn=new DataView(mn.buffer)),mn.set(t,Tt),Tt+=t.length}function uw(e,t){Gs(e,t)}function Nx(e){uw(xt.UnsignedInteger,e)}function kx(e){uw(xt.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function Px(e){e>=0?Nx(e):kx(e)}function fw(e){aw(xt.TextString,xx.encode(e))}function o0(e){aw(xt.ByteString,e)}function Rx(e,t,n){Gs(xt.Tag,e),fh(t,n)}function Cx(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function Qu(e){try{return Ax(e,t=>Ge.isPrincipal(t)?t.toUint8Array():Ts.isExpiry(t)?t.toBigInt():Cx(t)?t.toCborValue():t)}catch(t){throw tt.fromCode(new Zl(t,e))}}function tr(e){try{return gx(e)}catch(t){throw tt.fromCode(new Yl(t,e))}}const Rc=()=>{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 Ri;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})(Ri||(Ri={}));var il;(function(e){e.Call="call"})(il||(il={}));var Ho;(function(e){e.Query="query",e.ReadState="read_state"})(Ho||(Ho={}));function sl(){const e=new ArrayBuffer(16),t=new DataView(e),n=Rc(),r=Rc(),i=Rc(),s=Rc();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),Ux=BigInt(1e6),lw=BigInt(60),Hx=BigInt(90)*lh;function hw(e){return e/lh}function Fx(e){return hw(e)/lw}class Ts{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<Hx?s=hw(i):s=Fx(i)*lw,new Ts(s*lh*Ux)}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 Ts(r)}catch(r){throw new tt(new Oa(`Not a valid BigInt: ${r}`))}throw new tt(new Oa(`The input does not contain the key ${Cc}`))}static isExpiry(t){return t instanceof Ts||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===Ri.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 Fo(e,t=""){if(typeof e!="boolean"){const n=t&&`"${t}"`;throw new Error(n+"expected boolean, got type="+typeof e)}return e}function xs(e,t,n=""){const r=rc(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 dw(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?hh:BigInt("0x"+e)}function ir(e){return dw(rt(e))}function Mo(e){return On(e),dw(rt(Uint8Array.from(e).reverse()))}function Ut(e,t){return ic(e.toString(16).padStart(t*2,"0"))}function pw(e,t){return Ut(e,t).reverse()}function sn(e,t,n){let r;if(typeof t=="string")try{r=ic(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(rc(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 yw(e,t,n){return tf(e)&&tf(t)&&tf(n)&&t<=e&&e<n}function u0(e,t,n,r){if(!yw(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Lo(e){let t;for(t=0;e>hh;e>>=ka,t+=1);return t}function Mx(e,t){return e>>BigInt(t)&ka}const Ji=e=>(ka<<BigInt(e))-ka;function Lx(e){return typeof e=="function"&&Number.isSafeInteger(e.outputLen)}function gc(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 gw=()=>{throw new Error("not implemented")};function qo(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 fn=BigInt(0),Mt=BigInt(1),Ci=BigInt(2),mw=BigInt(3),ww=BigInt(4),bw=BigInt(5),qx=BigInt(7),Ew=BigInt(8),Vx=BigInt(9),_w=BigInt(16);function mt(e,t){const n=e%t;return n>=fn?n:t+n}function Zn(e,t,n){let r=e;for(;t-- >fn;)r*=r,r%=n;return r}function f0(e,t){if(e===fn)throw new Error("invert: expected non-zero number");if(t<=fn)throw new Error("invert: expected positive modulus, got "+t);let n=mt(e,t),r=t,i=fn,s=Mt;for(;n!==fn;){const c=r/n,a=r%n,u=i-s*c;r=n,n=a,i=s,s=u}if(r!==Mt)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 Sw(e,t){const n=(e.ORDER+Mt)/ww,r=e.pow(t,n);return dh(e,r,t),r}function Dx(e,t){const n=(e.ORDER-bw)/Ew,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 $x(e){const t=pi(e),n=Tw(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+qx)/_w;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 Tw(e){if(e<mw)throw new Error("sqrt is not defined for small field");let t=e-Mt,n=0;for(;t%Ci===fn;)t/=Ci,n++;let r=Ci;const i=pi(e);for(;Pa(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Sw;let s=i.pow(r,t);const o=(t+Mt)/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=Mt<<BigInt(f-g-1),S=a.pow(l,E);f=g,l=a.sqr(S),d=a.mul(d,l),y=a.mul(y,S)}return y}}function jx(e){return e%ww===mw?Sw:e%Ew===bw?Dx:e%_w===Vx?$x(e):Tw(e)}const Kx=(e,t)=>(mt(e,t)&Mt)===Mt,Gx=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xw(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Gx.reduce((r,i)=>(r[i]="function",r),t);return gc(e,n),e}function yu(e,t,n){if(n<fn)throw new Error("invalid exponent, negatives unsupported");if(n===fn)return e.ONE;if(n===Mt)return t;let r=e.ONE,i=t;for(;n>fn;)n&Mt&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Mt;return r}function Qi(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-Mt)/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 Wx(e,t){t!==void 0&&Nb(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function pi(e,t,n=!1,r={}){if(e<=fn)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}=Wx(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:Ji(a),ZERO:fn,ONE:Mt,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 fn<=d&&d<e},is0:d=>d===fn,isValidNot0:d=>!l.is0(d)&&l.isValid(d),isOdd:d=>(d&Mt)===Mt,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=jx(e)),f(l,d))),toBytes:d=>n?pw(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?Mo(d):ir(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=>Qi(l,d),cmov:(d,y,g)=>g?y:d});return Object.freeze(l)}function Aw(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 vw(e){const t=Aw(e);return t+Math.ceil(t/2)}function Xx(e,t,n=!1){const r=e.length,i=Aw(t),s=vw(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Mo(e):ir(e),c=mt(o,t-Mt)+Mt;return n?pw(c,i):Ut(c,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Us=BigInt(0),Ui=BigInt(1);function Ra(e,t){const n=t.negate();return e?n:t}function Sr(e,t){const n=Qi(e.Fp,t.map(r=>r.Z));return t.map((r,i)=>e.fromAffine(r.toAffine(n[i])))}function Iw(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){Iw(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e,s=Ji(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+=Ui);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 zx(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 Yx(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,Ow=new WeakMap;function sf(e){return Ow.get(e)||1}function h0(e){if(e!==Us)throw new Error("invalid wNAF")}class Bw{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>Us;)n&Ui&&(r=r.add(i)),i=i.double(),n>>=Ui;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!==Us;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){Iw(n,this.bits),Ow.set(t,n),rf.delete(t)}hasCache(t){return sf(t)!==1}}function Zx(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>Us||r>Us;)n&Ui&&(s=s.add(i)),r&Ui&&(o=o.add(i)),i=i.double(),n>>=Ui,r>>=Ui;return{p1:s,p2:o}}function Nw(e,t,n,r){zx(n,e),Yx(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=Lo(BigInt(i));let a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);const u=Ji(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],S=Number(E>>BigInt(y)&u);f[S]=f[S].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 xw(t),t}else return pi(e,{isLE:n})}function kw(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>Us))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 Jx=ir;function ri(e,t){if(Vo(e),Vo(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 Qx(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 Vo(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function Pw(e){if(!rc(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?dt(e):e}function e3(e,t,n,r){On(e),Vo(n),t=Pw(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,ri(t.length,1)),a=ri(0,s),u=ri(n,2),f=new Array(o),l=r($e(a,e,u,ri(0,1),c));f[0]=r($e(l,ri(1,1),c));for(let y=1;y<=o;y++){const g=[Qx(l,f[y-1]),ri(y+1,1),c];f[y]=r($e(...g))}return $e(...f).slice(0,n)}function t3(e,t,n,r,i){if(On(e),Vo(n),t=Pw(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(ri(n,2)).update(t).update(ri(t.length,1)).digest()}function of(e,t,n){gc(n,{p:"bigint",m:"number",k:"number",hash:"function"});const{p:r,k:i,m:s,hash:o,expand:c,DST:a}=n;if(!Lx(n.hash))throw new Error("expected valid hash");On(e),Vo(t);const u=r.toString(2).length,f=Math.ceil((u+i)/8),l=t*s*f;let d;if(c==="xmd")d=e3(e,a,l,o);else if(c==="xof")d=t3(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 S=f*(E+g*s),_=d.subarray(S,S+f);m[E]=mt(Jx(_),r)}y[g]=m}return y}function Rw(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]=Qi(e,[o,a],!0);return r=e.mul(s,u),i=e.mul(i,e.mul(c,f)),{x:r,y:i}}}const n3=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:n3},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)/yr)/t;function r3(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<Hi,d=f<Hi;l&&(u=-u),d&&(f=-f);const y=Ji(Math.ceil(Lo(n)/2))+Qt;if(u<Hi||u>=y||f<Hi||f>=y)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:u,k2neg:d,k2:f}}const Hi=BigInt(0),Qt=BigInt(1),yr=BigInt(2),ps=BigInt(3),ol=BigInt(4);function Ca(e,t){const{BYTES:n}=e;let r;if(typeof t=="bigint")r=t;else{let i=sn("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 i3(e,t={}){const n=kw("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:c}=s;gc(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=c3(r,i);function f(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(K,H,D){const{x:P,y:$}=H.toAffine(),F=r.toBytes(P);if(Fo(D,"isCompressed"),D){f();const x=!r.isOdd($);return $e(s3(x),F)}else return $e(Uint8Array.of(4),F,r.toBytes($))}function d(K){xs(K,void 0,"Point");const{publicKey:H,publicKeyUncompressed:D}=u,P=K.length,$=K[0],F=K.subarray(1);if(P===H&&($===2||$===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 L;try{L=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(L);return($&1)===1!==N&&(L=r.neg(L)),{x,y:L}}else if(P===D&&$===4){const x=r.BYTES,B=r.fromBytes(F.subarray(0,x)),L=r.fromBytes(F.subarray(x,x*2));if(!E(B,L))throw new Error("bad point: is not on curve");return{x:B,y:L}}else throw new Error(`bad point: got length ${P}, expected compressed=${H} or uncompressed=${D}`)}const y=t.toBytes||l,g=t.fromBytes||d;function m(K){const H=r.sqr(K),D=r.mul(H,K);return r.add(r.add(D,r.mul(K,s.a)),s.b)}function E(K,H){const D=r.sqr(H),P=m(K);return r.eql(D,P)}if(!E(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const S=r.mul(r.pow(s.a,ps),ol),_=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,D=!1){if(!r.isValid(H)||D&&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 r3(K,a.basises,i.ORDER)}const A=qo((K,H)=>{const{X:D,Y:P,Z:$}=K;if(r.eql($,r.ONE))return{x:D,y:P};const F=K.is0();H==null&&(H=F?r.ONE:r.inv($));const x=r.mul(D,H),B=r.mul(P,H),L=r.mul($,H);if(F)return{x:r.ZERO,y:r.ZERO};if(!r.eql(L,r.ONE))throw new Error("invZ was invalid");return{x,y:B}}),R=qo(K=>{if(K.is0()){if(t.allowInfinityPoint&&!r.is0(K.Y))return;throw new Error("bad point: ZERO")}const{x:H,y:D}=K.toAffine();if(!r.isValid(H)||!r.isValid(D))throw new Error("bad point: x or y not field elements");if(!E(H,D))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,D,P,$){return D=new v(r.mul(D.X,K),D.Y,D.Z),H=Ra(P,H),D=Ra($,D),H.add(D)}class v{constructor(H,D,P){this.X=w("x",H),this.Y=w("y",D,!0),this.Z=w("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(H){const{x:D,y:P}=H||{};if(!H||!r.isValid(D)||!r.isValid(P))throw new Error("invalid affine point");if(H instanceof v)throw new Error("projective point not allowed");return r.is0(D)&&r.is0(P)?v.ZERO:new v(D,P,r.ONE)}static fromBytes(H){const D=v.fromAffine(g(xs(H,void 0,"point")));return D.assertValidity(),D}static fromHex(H){return v.fromBytes(sn("pointHex",H))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(H=8,D=!0){return q.createCache(this,H),D||this.multiply(ps),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:D,Y:P,Z:$}=this,{X:F,Y:x,Z:B}=H,L=r.eql(r.mul(D,B),r.mul(F,$)),N=r.eql(r.mul(P,B),r.mul(x,$));return L&&N}negate(){return new v(this.X,r.neg(this.Y),this.Z)}double(){const{a:H,b:D}=s,P=r.mul(D,ps),{X:$,Y:F,Z:x}=this;let B=r.ZERO,L=r.ZERO,N=r.ZERO,V=r.mul($,$),G=r.mul(F,F),X=r.mul(x,x),Y=r.mul($,F);return Y=r.add(Y,Y),N=r.mul($,x),N=r.add(N,N),B=r.mul(H,N),L=r.mul(P,X),L=r.add(B,L),B=r.sub(G,L),L=r.add(G,L),L=r.mul(B,L),B=r.mul(Y,B),N=r.mul(P,N),X=r.mul(H,X),Y=r.sub(V,X),Y=r.mul(H,Y),Y=r.add(Y,N),N=r.add(V,V),V=r.add(N,V),V=r.add(V,X),V=r.mul(V,Y),L=r.add(L,V),X=r.mul(F,x),X=r.add(X,X),V=r.mul(X,Y),B=r.sub(B,V),N=r.mul(X,G),N=r.add(N,N),N=r.add(N,N),new v(B,L,N)}add(H){T(H);const{X:D,Y:P,Z:$}=this,{X:F,Y:x,Z:B}=H;let L=r.ZERO,N=r.ZERO,V=r.ZERO;const G=s.a,X=r.mul(s.b,ps);let Y=r.mul(D,F),ce=r.mul(P,x),ue=r.mul($,B),te=r.add(D,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,$),L=r.add(x,B),ae=r.mul(ae,L),L=r.add(ce,ue),ae=r.sub(ae,L),V=r.mul(G,Z),L=r.mul(X,ue),V=r.add(L,V),L=r.sub(ce,V),V=r.add(ce,V),N=r.mul(L,V),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),L=r.mul(te,L),L=r.sub(L,Y),Y=r.mul(te,ce),V=r.mul(ae,V),V=r.add(V,Y),new v(L,N,V)}subtract(H){return this.add(H.negate())}is0(){return this.equals(v.ZERO)}multiply(H){const{endo:D}=t;if(!i.isValidNot0(H))throw new Error("invalid scalar: out of range");let P,$;const F=x=>q.cached(this,x,B=>Sr(v,B));if(D){const{k1neg:x,k1:B,k2neg:L,k2:N}=O(H),{p:V,f:G}=F(B),{p:X,f:Y}=F(N);$=G.add(Y),P=M(D.beta,V,X,x,L)}else{const{p:x,f:B}=F(H);P=x,$=B}return Sr(v,[P,$])[0]}multiplyUnsafe(H){const{endo:D}=t,P=this;if(!i.isValid(H))throw new Error("invalid scalar: out of range");if(H===Hi||P.is0())return v.ZERO;if(H===Qt)return P;if(q.hasCache(this))return this.multiply(H);if(D){const{k1neg:$,k1:F,k2neg:x,k2:B}=O(H),{p1:L,p2:N}=Zx(v,P,F,B);return M(D.beta,L,N,$,x)}else return q.unsafe(P,H)}multiplyAndAddUnsafe(H,D,P){const $=this.multiplyUnsafe(D).add(H.multiplyUnsafe(P));return $.is0()?void 0:$}toAffine(H){return A(this,H)}isTorsionFree(){const{isTorsionFree:H}=t;return o===Qt?!0:H?H(v,this):q.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 Fo(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 Sr(v,H)}static msm(H,D){return Nw(v,i,H,D)}static fromPrivateKey(H){return v.BASE.multiply(Ca(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 C=i.BITS,q=new Bw(v,t.endo?Math.ceil(C/2):C);return v.BASE.precompute(8),v}function s3(e){return Uint8Array.of(e?2:3)}function o3(e,t){const n=e.ORDER;let r=Hi;for(let g=n-Qt;g%yr===Hi;g/=yr)r+=Qt;const i=r,s=yr<<i-Qt-Qt,o=s*yr,c=(n-Qt)/o,a=(c-Qt)/yr,u=o-Qt,f=s,l=e.pow(t,c),d=e.pow(t,(c+Qt)/yr);let y=(g,m)=>{let E=l,S=e.pow(m,u),_=e.sqr(S);_=e.mul(_,m);let w=e.mul(g,_);w=e.pow(w,a),w=e.mul(w,S),S=e.mul(w,m),_=e.mul(w,g);let T=e.mul(_,S);w=e.pow(T,f);let O=e.eql(w,e.ONE);S=e.mul(_,d),w=e.mul(T,E),_=e.cmov(S,_,O),T=e.cmov(w,T,O);for(let A=i;A>Qt;A--){let R=A-yr;R=yr<<R-Qt;let M=e.pow(T,R);const v=e.eql(M,e.ONE);S=e.mul(_,E),E=e.mul(E,E),M=e.mul(T,E),_=e.cmov(S,_,v),T=e.cmov(M,T,v)}return{isValid:O,value:_}};if(e.ORDER%ol===ps){const g=(e.ORDER-ps)/ol,m=e.sqrt(e.neg(t));y=(E,S)=>{let _=e.sqr(S);const w=e.mul(E,S);_=e.mul(_,w);let T=e.pow(_,g);T=e.mul(T,w);const O=e.mul(T,m),A=e.mul(e.sqr(T),S),R=e.eql(A,E);let M=e.cmov(O,T,R);return{isValid:R,value:M}}}return y}function Cw(e,t){xw(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=o3(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 S=e.isOdd(o)===e.isOdd(g);g=e.cmov(e.neg(g),g,S);const _=Qi(e,[f],!0)[0];return y=e.mul(y,_),{x:y,y:g}}}function c3(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}=a3(e),r=i3(t,n);return f3(e,r)}function a3(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=pi(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 u3(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 f3(e,t){const{Fp:n,Fn:r}=t;function i(o){return yw(o,Qt,r.ORDER)}const s=u3(n,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:o=>Ca(r,o),weierstrassEquation:s,isWithinCurveOrder:i})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const l3=BigInt(0),Uc=BigInt(1),m0=BigInt(2),ys=BigInt(3);function h3(e){const t=[];for(;e>Uc;e>>=Uc)(e&Uc)===l3?t.unshift(0):(e&ys)===ys?(t.unshift(-1),e+=Uc):t.unshift(1);return t}function cf(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function d3(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,ys)),C=i.mul(v,ys),q=i.sub(i.sub(i.sqr(i.add(O,A)),M),R),K=i.sub(v,R),H=i.mul(i.sqr(T),ys),D=i.neg(q);return w.push([K,H,D]),T=i.mul(i.mul(i.mul(i.sub(R,C),T),O),l),O=i.sub(i.sqr(i.mul(i.add(R,C),l)),i.mul(i.sqr(v),ys)),A=i.mul(R,q),{Rx:T,Ry:O,Rz:A}}function y(w,T,O,A,R,M){const v=i.sub(O,i.mul(M,A)),C=i.sub(T,i.mul(R,A)),q=i.sub(i.mul(v,R),i.mul(C,M)),K=i.neg(v),H=C;w.push([q,K,H]);const D=i.sqr(C),P=i.mul(D,C),$=i.mul(D,T),F=i.add(i.sub(P,i.mul($,m0)),i.mul(i.sqr(v),A));return T=i.mul(C,F),O=i.sub(i.mul(i.sub($,F),v),i.mul(P,O)),A=i.mul(A,P),{Rx:T,Ry:O,Rz:A}}const g=h3(c),m=qo(w=>{const T=w,{x:O,y:A}=T.toAffine(),R=O,M=A,v=i.neg(A);let C=R,q=M,K=i.ONE;const H=[];for(const D of g){const P=[];({Rx:C,Ry:q,Rz:K}=d(P,C,q,K)),D&&({Rx:C,Ry:q,Rz:K}=y(P,C,q,K,R,D===-1?v:M)),H.push(P)}if(u){const D=H[H.length-1];u(C,q,K,R,M,y.bind(null,D))}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,C]of w)for(const[q,K,H]of M[R])O=f(q,K,H,O,v,C)}}return a&&(O=s.conjugate(O)),T?s.finalExponentiate(O):O}function S(w,T=!0){const O=[];Sr(t,w.map(({g1:A})=>A)),Sr(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 _(w,T,O=!0){return S([{g1:w,g2:T}],O)}return{Fp12:s,millerLoopBatch:E,pairing:_,pairingBatch:S,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=Ca(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=Ca(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,S=u(d),_=l,w=o([f(m,S),f(E,_)]);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),S=new Map;for(let T=0;T<E.length;T++){const O=E[T],A=m[T];let R=S.get(A);R===void 0&&(R=[],S.set(A,R)),R.push(O)}const _=[],w=t.Point.BASE;try{for(const[T,O]of S){const A=O.reduce((R,M)=>R.add(M));_.push(f(A,T))}return _.push(f(w.negate(),g)),s.eql(o(_),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 p3(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=d3(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),S=e.randomBytes||sg,_=()=>{const x=vw(n.ORDER);return Xx(S(x),n.ORDER)},w={randomSecretKey:_,randomPrivateKey:_,calcPairingPrecomputes:g},{ShortSignature:T}=e.G1,{Signature:O}=e.G2;function A(x,B){return x instanceof c.Point?x:E.hash(sn("point",x),B?.DST)}function R(x,B){return x instanceof u.Point?x:m.hash(sn("point",x),B?.DST)}function M(x){return m.getPublicKey(x).toBytes(!0)}function v(x){return E.getPublicKey(x).toBytes(!0)}function C(x,B,L){const N=R(x,L),V=m.sign(N,B);return x instanceof u.Point?V:O.toBytes(V)}function q(x,B,L){const N=A(x,L),V=E.sign(N,B);return x instanceof c.Point?V:T.toBytes(V)}function K(x,B,L,N){const V=R(B,N);return m.verify(x,V,L)}function H(x,B,L,N){const V=A(B,N);return E.verify(x,V,L)}function D(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 $(x){const B=E.aggregateSignatures(x);return x[0]instanceof c.Point?B:T.toBytes(B)}function F(x,B,L,N){const V=B.map(G=>R(G,N));return m.verifyBatch(x,V,L)}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:C,signShortSignature:q,verify:K,verifyShortSignature:H,aggregatePublicKeys:D,aggregateSignatures:P,aggregateShortSignatures:$,G1:c,G2:u,Signature:O,ShortSignature:T}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const b0=BigInt(0),Tr=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=Tr;d<r;d++){const g=(f*y-f)/o%c;l.push(e.pow(t,g)),y*=n}a.push(l)}return a}function y3(e,t,n){const r=t.pow(n,(e.ORDER-Tr)/E0),i=t.pow(n,(e.ORDER-Tr)/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-Tr)/E0),c=t.pow(n,(e.ORDER**tn-Tr)/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 g3{constructor(t,n={}){this.MASK=Tr;const r=t.ORDER,i=r*r;this.Fp=t,this.ORDER=i,this.BITS=Lo(i),this.BYTES=Math.ceil(Lo(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 Qi(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)==Tr}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 m3{constructor(t){this.MASK=Tr,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 gw()}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 Qi(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 w3{constructor(t,n){this.MASK=Tr;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){gw()}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 Qi(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),S=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(S,a),tn),S),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),Mx(n,i)&&(r=this.mul(r,t));return r}}function b3(e){const t=pi(e.ORDER),n=new g3(t,e),r=new m3(n),i=new w3(r,e);return{Fp:t,Fp2:n,Fp6:r,Fp12:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Kt=BigInt(0),Ua=BigInt(1),kn=BigInt(2),gu=BigInt(3),Do=BigInt(4),ii=BigInt("0xd201000000010000"),E3=Lo(ii),Gi={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:Kt,b:Do,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},_3=pi(Gi.n,{modFromBytes:!0,isLE:!0}),{Fp:Ee,Fp2:Ce,Fp6:S3,Fp12:Le}=b3({ORDER:Gi.p,X_LEN:E3,FP2_NONRESIDUE:[Ua,Ua],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=ii,n=Le.div(Le.frobeniusMap(e,6),e),r=Le.mul(Le.frobeniusMap(n,2),n),i=Le.conjugate(Le._cyclotomicExp(r,t)),s=Le.mul(Le.conjugate(Le._cyclotomicSquare(r)),i),o=Le.conjugate(Le._cyclotomicExp(s,t)),c=Le.conjugate(Le._cyclotomicExp(o,t)),a=Le.mul(Le.conjugate(Le._cyclotomicExp(c,t)),Le._cyclotomicSquare(i)),u=Le.conjugate(Le._cyclotomicExp(a,t)),f=Le.frobeniusMap(Le.mul(i,c),2),l=Le.frobeniusMap(Le.mul(o,r),3),d=Le.frobeniusMap(Le.mul(a,Le.conjugate(r)),1),y=Le.mul(Le.mul(u,Le.conjugate(s)),r);return Le.mul(Le.mul(Le.mul(f,l),d),y)}}),{G2psi:S0,G2psi2:T3}=y3(Ee,Ce,Ce.div(Ce.ONE,Ce.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:bn}),yh={p:Ce.ORDER,n:Gi.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:Ce.ZERO,b:Ce.fromBigTuple([Do,Do]),Gx:Ce.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:Ce.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},mu=mc(Ee.toBytes(Kt),{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 mc(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 x3(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 mc(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 mc(Ut(r,t),{compressed:!0,sort:s})}function A3(e){const{compressed:t,infinity:n,sort:r,value:i}=wu(e),{BYTES:s,ORDER:o}=Ee;if(i.length===48&&t){const c=ir(i),a=Ee.create(c&Ji(Ee.BITS));if(n){if(a!==Kt)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:Kt,y:Kt}}const u=Ee.add(Ee.pow(a,gu),Ee.create(Gi.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=ir(i.subarray(0,s)),a=ir(i.subarray(s));if(n){if(c!==Kt||a!==Kt)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(sn("signatureHex",e,48)),i=Ee.ORDER,s=bu.G1.Point,o=ir(r);if(t)return s.ZERO;const c=Ee.create(o&Ji(Ee.BITS)),a=Ee.add(Ee.pow(c,gu),Ee.create(Gi.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 v3(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(Kt,r));const a=!!(c.c1===Kt?c.c0*kn/i:c.c1*kn/i);return $e(mc(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}=Ce.reim(o),{re:f,im:l}=Ce.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(Kt,t));const{x:n,y:r}=e.toAffine(),{re:i,im:s}=Ce.reim(n),{re:o,im:c}=Ce.reim(r),u=!!((c>Kt?c*kn:o*kn)/Ee.ORDER&Ua),f=i;return $e(mc(Ut(s,t),{sort:u,compressed:!0}),Ut(f,t))}function I3(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)=>ir(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:Ce.ZERO,y:Ce.ZERO}}const a=c(o,0,t),u=c(o,t,2*t),f=Ce.create({c0:Ee.create(u),c1:Ee.create(a)}),l=Ce.add(Ce.pow(f,gu),yh.b);let d=Ce.sqrt(l);const y=d.c1===Kt?d.c0*kn/n:d.c1*kn/n?Ua:Kt;return d=s&&y>0?d:Ce.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:Ce.ZERO,y:Ce.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:Ce.fromBigTuple([u,a]),y:Ce.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(sn("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=ir(i.slice(0,o)),a=ir(i.slice(o));if(n)return s.ZERO;const u=Ee.create(c&Ji(Ee.BITS)),f=Ee.create(a),l=Ce.create({c0:f,c1:u}),d=Ce.add(Ce.pow(l,gu),yh.b);let y=Ce.sqrt(d);if(!y)throw new Error("Failed to find a square root");const{re:g,im:m}=Ce.reim(y),E=BigInt(r),S=m>Kt&&m*kn/t!==E,_=m===Kt&&g*kn/t!==E;(S||_)&&(y=Ce.neg(y));const w=s.fromAffine({x:l,y});return w.assertValidity(),w}const bu=p3({fields:{Fp:Ee,Fp2:Ce,Fp6:S3,Fp12:Le,Fr:_3},G1:{...Gi,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(ii).negate().multiplyUnsafe(ii).equals(r)},clearCofactor:(e,t)=>t.multiplyUnsafe(ii).add(t),mapToCurve:P3,fromBytes:A3,toBytes:x3,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:Ce,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...af},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:R3,isTorsionFree:(e,t)=>t.multiplyUnsafe(ii).negate().equals(S0(e,t)),clearCofactor:(e,t)=>{const n=ii;let r=t.multiplyUnsafe(n).negate(),i=S0(e,t),s=t.double();return s=T3(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:I3,toBytes:v3,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:ii,r:Gi.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:af}),O3=Rw(Ce,[[["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=>Ce.fromBigTuple(t.map(BigInt))))),B3=Rw(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)))),N3=Cw(Ee,{A:Ee.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:Ee.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:Ee.create(BigInt(11))}),k3=Cw(Ce,{A:Ce.create({c0:Ee.create(Kt),c1:Ee.create(BigInt(240))}),B:Ce.create({c0:Ee.create(BigInt(1012)),c1:Ee.create(BigInt(1012))}),Z:Ce.create({c0:Ee.create(BigInt(-2)),c1:Ee.create(BigInt(-1))})});function P3(e){const{x:t,y:n}=N3(Ee.create(e[0]));return B3(t,n)}function R3(e){const{x:t,y:n}=k3(Ce.fromBigTuple(e));return O3(t,n)}function C3(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 U3=BigInt(1e6),Uw=e=>Nt(new Vs(e)),gh=e=>{const n=Uw(e)/U3;return new Date(Number(n))},A0=60*1e3,H3=60,F3=24,M3=F3*H3,L3=5,q3=5,V3=30*M3;var Ht;(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"})(Ht||(Ht={}));function D3(e,t){for(let n=0;n<e.length;n++)if(e[n]>t[n])return!0;return!1}class Li{#t=!1;#e=void 0;static async create(t){const n=Li.createUnverified(t);return await n.verify(),n}static createUnverified(t){return new Li(t.certificate,t.rootKey,t.canisterId,t.blsVerify??C3,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,n,r,i,s=L3,o=!1,c){this._rootKey=n,this._canisterId=r,this._blsVerify=i,this._maxAgeInMinutes=s,this.#t=o,this.cert=tr(t),c&&"getTimeDiffMsecs"in c&&"hasSyncedTime"in c&&"syncTime"in c&&(this.#e=c)}lookup_path(t){return wc(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=j3(n),s=$e(wo("ic-state-root"),t),o=En(this.lookup_path(["time"]));if(!o)throw yt.fromCode(new Es("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+q3*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 Ro(this._maxAgeInMinutes,y,u,c,"past"));if(m)throw this.#e?.hasSyncedTime()?an.fromCode(new qn("System time has been synced with the IC network, but certificate is still too far in the future.")):An.fromCode(new Ro(5,y,u,c,"future"))}try{if(!await this._blsVerify(i,r,s))throw An.fromCode(new Es("Invalid signature"))}catch(c){throw An.fromCode(new Es("Signature verification failed",c))}}async _checkDelegationAndGetKey(t){if(!t)return this._rootKey;const n=Li.createUnverified({certificate:t.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,disableTimeVerification:this.#t,maxAgeInMinutes:V3,agent:this.#e});if(n.cert.delegation)throw yt.fromCode(new Gl);await n.verify();const r=t.subnet_id,i=Ge.fromUint8Array(r);if(!Fw({canisterId:this._canisterId,subnetId:i,tree:n.cert.tree}))throw An.fromCode(new uu(this._canisterId,i));const o=En(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 ro=ic("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),$3=96;function j3(e){const t=ro.byteLength+$3;if(e.byteLength!==t)throw yt.fromCode(new lu(t,e.byteLength));const n=e.slice(0,ro.byteLength);if(!pu(n,ro))throw yt.fromCode(new Xl(ro,n));return e.slice(ro.byteLength)}function En(e){if(e.status===vn.Found&&e.value instanceof Uint8Array)return e.value}async function na(e){switch(e[0]){case Ht.Empty:return bn(wo("ic-hashtree-empty"));case Ht.Pruned:return e[1];case Ht.Leaf:return bn($e(wo("ic-hashtree-leaf"),e[1]));case Ht.Labeled:return bn($e(wo("ic-hashtree-labeled"),e[1],await na(e[2])));case Ht.Fork:return bn($e(wo("ic-hashtree-fork"),await na(e[1]),await na(e[2])));default:throw _s}}function wo(e){const t=new Uint8Array([e.length]),n=new TextEncoder().encode(e);return $e(t,n)}function Hw(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 As;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found"})(As||(As={}));var ot;(function(e){e.Absent="Absent",e.Unknown="Unknown",e.Found="Found",e.Less="Less",e.Greater="Greater"})(ot||(ot={}));function wc(e,t){if(e.length===0)switch(t[0]){case Ht.Empty:return{status:vn.Absent};case Ht.Leaf:{if(!t[1])throw an.fromCode(new pc("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 _s}case Ht.Pruned:return{status:vn.Unknown};case Ht.Labeled:case Ht.Fork:return{status:vn.Error};default:throw _s}const n=Hw(e),r=xo(n,t);switch(r.status){case ot.Found:return wc(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 _s}}function mh(e,t){if(e.length===0)return{status:As.Found,value:t};const n=Hw(e),r=xo(n,t);switch(r.status){case ot.Found:return mh(e.slice(1),r.value);case ot.Unknown:return{status:As.Unknown};case ot.Absent:case ot.Greater:case ot.Less:return{status:As.Absent};default:throw _s}}function cl(e){switch(e[0]){case Ht.Empty:return[];case Ht.Fork:return cl(e[1]).concat(cl(e[2]));default:return[e]}}function xo(e,t){switch(t[0]){case Ht.Labeled:return D3(e,t[1])?{status:ot.Greater}:pu(e,t[1])?{status:ot.Found,value:t[2]}:{status:ot.Less};case Ht.Fork:{const n=xo(e,t[1]);switch(n.status){case ot.Greater:{const r=xo(e,t[2]);return r.status===ot.Less?{status:ot.Absent}:r}case ot.Unknown:{const r=xo(e,t[2]);return r.status===ot.Less?{status:ot.Unknown}:r}default:return n}}case Ht.Pruned:return{status:ot.Unknown};default:return{status:ot.Absent}}}function Fw(e){const{canisterId:t,subnetId:n,tree:r}=e,i=wc(["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 tr(i.value).map(a=>[Ge.fromUint8Array(a[0]),Ge.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=Ge.from(e.canisterId),s=[...new Set(n)],o=new Map,c=s.map((a,u)=>{const f=G3(a,i);return(async()=>{try{if(t.rootKey===null)throw cn.fromCode(new js);const l=t.rootKey,d=await t.readState(i,{paths:[f]}),y=await Li.create({certificate:d.certificate,rootKey:l,canisterId:i,disableTimeVerification:r,agent:t}),g=(S,_)=>{if(_==="subnet"){const w=K3(d.certificate,i,l);return{path:_,data:w}}else return{path:_,data:En(S.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,W3(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,Uw(E));break}case"cbor":{o.set(m.key,tr(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 br&&(l.hasCode(Es)||l.hasCode(Ro)))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},K3=(e,t,n)=>{if(!t._isPrincipal)throw tt.fromCode(new qn("Invalid canisterId"));const r=tr(e),i=r.tree;let s=r.delegation,o;if(s&&s.subnet_id?o=Ge.fromUint8Array(new Uint8Array(s.subnet_id)):!s&&typeof n<"u"?(o=Ge.selfAuthenticating(new Uint8Array(n)),s={subnet_id:o.toUint8Array(),certificate:new Uint8Array(0)}):(o=Ge.selfAuthenticating(Ge.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),s={subnet_id:o.toUint8Array(),certificate:new Uint8Array(0)}),!Fw({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!==As.Found)throw yt.fromCode(new Cs("Node not found",a.status));if(a.value instanceof Uint8Array)throw an.fromCode(new pc("Invalid node tree"));const u=cl(a.value),f=new Map;return u.forEach(l=>{const d=Ge.from(l[1]).toText(),y=wc(["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:Ge.fromUint8Array(new Uint8Array(s.subnet_id)).toText(),nodeKeys:f}},G3=(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 an.fromCode(new qn(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))},W3=e=>tr(e).map(n=>Ge.fromUint8Array(n));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vr=BigInt(0),Bt=BigInt(1),lf=BigInt(2),X3=BigInt(8);function z3(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 Y3(e,t={}){const n=kw("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o}=s;gc(t,{},{uvRatio:"function"});const c=lf<<BigInt(i.BYTES*8)-Bt,a=E=>r.create(E),u=t.uvRatio||((E,S)=>{try{return{isValid:!0,value:r.sqrt(r.div(E,S))}}catch{return{isValid:!1,value:Vr}}});if(!z3(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(E,S,_=!1){const w=_?Bt:Vr;return u0("coordinate "+E,S,w,c),S}function l(E){if(!(E instanceof g))throw new Error("ExtendedPoint expected")}const d=qo((E,S)=>{const{X:_,Y:w,Z:T}=E,O=E.is0();S==null&&(S=O?X3:r.inv(T));const A=a(_*S),R=a(w*S),M=r.mul(T,S);if(O)return{x:Vr,y:Bt};if(M!==Bt)throw new Error("invZ was invalid");return{x:A,y:R}}),y=qo(E=>{const{a:S,d:_}=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),C=a(v*v),q=a(R*S),K=a(v*a(q+M)),H=a(C+a(_*a(R*M)));if(K!==H)throw new Error("bad point: equation left != right (1)");const D=a(w*T),P=a(O*A);if(D!==P)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(S,_,w,T){this.X=f("x",S),this.Y=f("y",_),this.Z=f("z",w,!0),this.T=f("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(S){if(S instanceof g)throw new Error("extended point not allowed");const{x:_,y:w}=S||{};return f("x",_),f("y",w),new g(_,w,Bt,a(_*w))}static fromBytes(S,_=!1){const w=r.BYTES,{a:T,d:O}=s;S=a0(xs(S,w,"point")),Fo(_,"zip215");const A=a0(S),R=S[w-1];A[w-1]=R&-129;const M=Mo(A),v=_?c:r.ORDER;u0("point.y",M,Vr,v);const C=a(M*M),q=a(C-Bt),K=a(O*C-T);let{isValid:H,value:D}=u(q,K);if(!H)throw new Error("bad point: invalid y coordinate");const P=(D&Bt)===Bt,$=(R&128)!==0;if(!_&&D===Vr&&$)throw new Error("bad point: x=0 and x_0=1");return $!==P&&(D=a(-D)),g.fromAffine({x:D,y:M})}static fromHex(S,_=!1){return g.fromBytes(sn("point",S),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(S=8,_=!0){return m.createCache(this,S),_||this.multiply(lf),this}assertValidity(){y(this)}equals(S){l(S);const{X:_,Y:w,Z:T}=this,{X:O,Y:A,Z:R}=S,M=a(_*R),v=a(O*T),C=a(w*R),q=a(A*T);return M===v&&C===q}is0(){return this.equals(g.ZERO)}negate(){return new g(a(-this.X),this.Y,this.Z,a(-this.T))}double(){const{a:S}=s,{X:_,Y:w,Z:T}=this,O=a(_*_),A=a(w*w),R=a(lf*a(T*T)),M=a(S*O),v=_+w,C=a(a(v*v)-O-A),q=M+A,K=q-R,H=M-A,D=a(C*K),P=a(q*H),$=a(C*H),F=a(K*q);return new g(D,P,F,$)}add(S){l(S);const{a:_,d:w}=s,{X:T,Y:O,Z:A,T:R}=this,{X:M,Y:v,Z:C,T:q}=S,K=a(T*M),H=a(O*v),D=a(R*w*q),P=a(A*C),$=a((T+O)*(M+v)-K-H),F=P-D,x=P+D,B=a(H-_*K),L=a($*F),N=a(x*B),V=a($*B),G=a(F*x);return new g(L,N,G,V)}subtract(S){return this.add(S.negate())}multiply(S){if(!i.isValidNot0(S))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:_,f:w}=m.cached(this,S,T=>Sr(g,T));return Sr(g,[_,w])[0]}multiplyUnsafe(S,_=g.ZERO){if(!i.isValid(S))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return S===Vr?g.ZERO:this.is0()||S===Bt?this:m.unsafe(this,S,w=>Sr(g,w),_)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(S){return d(this,S)}clearCofactor(){return o===Bt?this:this.multiplyUnsafe(o)}toBytes(){const{x:S,y:_}=this.toAffine(),w=r.toBytes(_);return w[w.length-1]|=S&Bt?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(S){return Sr(g,S)}static msm(S,_){return Nw(g,i,S,_)}_setWindowSize(S){this.precompute(S)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,Bt,a(s.Gx*s.Gy)),g.ZERO=new g(Vr,Bt,Bt,Vr),g.Fp=r,g.Fn=i;const m=new Bw(g,i.BITS);return g.BASE.precompute(8),g}function Z3(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');gc(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||sg,a=n.adjustScalarBytes||(v=>v),u=n.domain||((v,C,q)=>{if(Fo(q,"phflag"),C.length||q)throw new Error("Contexts/pre-hash are not supported");return v});function f(v){return o.create(Mo(v))}function l(v){const C=w.secretKey;v=sn("private key",v,C);const q=sn("hashed private key",t(v),2*C),K=a(q.slice(0,C)),H=q.slice(C,2*C),D=f(K);return{head:K,prefix:H,scalar:D}}function d(v){const{head:C,prefix:q,scalar:K}=l(v),H=i.multiply(K),D=H.toBytes();return{head:C,prefix:q,scalar:K,point:H,pointBytes:D}}function y(v){return d(v).pointBytes}function g(v=Uint8Array.of(),...C){const q=$e(...C);return f(t(u(q,sn("context",v),!!r)))}function m(v,C,q={}){v=sn("message",v),r&&(v=r(v));const{prefix:K,scalar:H,pointBytes:D}=d(C),P=g(q.context,K,v),$=i.multiply(P).toBytes(),F=g(q.context,$,D,v),x=o.create(P+F*H);if(!o.isValid(x))throw new Error("sign failed: invalid s");const B=$e($,o.toBytes(x));return xs(B,w.signature,"result")}const E={zip215:!0};function S(v,C,q,K=E){const{context:H,zip215:D}=K,P=w.signature;v=sn("signature",v,P),C=sn("message",C),q=sn("publicKey",q,w.publicKey),D!==void 0&&Fo(D,"zip215"),r&&(C=r(C));const $=P/2,F=v.subarray(0,$),x=Mo(v.subarray($,P));let B,L,N;try{B=e.fromBytes(q,D),L=e.fromBytes(F,D),N=i.multiplyUnsafe(x)}catch{return!1}if(!D&&B.isSmallOrder())return!1;const V=g(H,L.toBytes(),B.toBytes(),C);return L.add(B.multiplyUnsafe(V)).subtract(N).clearCofactor().is0()}const _=s.BYTES,w={secretKey:_,publicKey:_,signature:2*_,seed:_};function T(v=c(w.seed)){return xs(v,w.seed,"seed")}function O(v){const C=M.randomSecretKey(v);return{secretKey:C,publicKey:y(C)}}function A(v){return rc(v)&&v.length===o.BYTES}function R(v,C){try{return!!e.fromBytes(v,C)}catch{return!1}}const M={getExtendedPublicKey:d,randomSecretKey:T,isValidSecretKey:A,isValidPublicKey:R,toMontgomery(v){const{y:C}=e.fromBytes(v),q=w.publicKey,K=q===32;if(!K&&q!==57)throw new Error("only defined for 25519 and 448");const H=K?s.div(Bt+C,Bt-C):s.div(C-Bt,C+Bt);return s.toBytes(H)},toMontgomerySecret(v){const C=w.secretKey;xs(v,C);const q=t(v.subarray(0,C));return a(q).subarray(0,C)},randomPrivateKey:T,precompute(v=8,C=e.BASE){return C.precompute(v,!1)}};return Object.freeze({keygen:O,getPublicKey:y,sign:m,verify:S,utils:M,Point:e,lengths:w})}function J3(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=pi(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 Q3(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function e8(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:i}=J3(e),s=Y3(t,n),o=Z3(s,r,i);return Q3(e,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t8=BigInt(1),I0=BigInt(2);BigInt(3);const n8=BigInt(5),r8=BigInt(8),wh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Mw={p:wh,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:r8,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function i8(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,t8,s)*e%s,f=Zn(u,n8,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 s8(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const O0=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function o8(e,t){const n=wh,r=mt(t*t*t,n),i=mt(r*r*t,n),s=i8(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),Kx(o,n)&&(o=mt(-o,n)),{isValid:f||l,value:o}}const c8=pi(Mw.p,{isLE:!0}),a8={...Mw,Fp:c8,hash:oE,adjustScalarBytes:s8,uvRatio:o8},u8=e8(a8);var B0,N0,Rt,Is;class f8{constructor(t={}){rn(this,Rt);rn(this,Is);this[B0]=this.entries.bind(this),this[N0]="ExpirableMap";const{source:n=[],expirationTime:r=600*1e3}=t,i=Date.now();Yt(this,Rt,new Map([...n].map(([s,o])=>[s,{value:o,timestamp:i}]))),Yt(this,Is,r)}prune(){const t=Date.now();for(const[n,r]of Me(this,Rt).entries())t-r.timestamp>Me(this,Is)&&Me(this,Rt).delete(n);return this}set(t,n){this.prune();const r={value:n,timestamp:Date.now()};return Me(this,Rt).set(t,r),this}get(t){const n=Me(this,Rt).get(t);if(n!==void 0){if(Date.now()-n.timestamp>Me(this,Is)){Me(this,Rt).delete(t);return}return n.value}}clear(){Me(this,Rt).clear()}entries(){const t=Me(this,Rt).entries();return function*(){for(const[r,i]of t)yield[r,i.value]}()}values(){const t=Me(this,Rt).values();return function*(){for(const r of t)yield r.value}()}keys(){return Me(this,Rt).keys()}forEach(t,n){for(const[r,i]of Me(this,Rt).entries())t.call(n,i.value,r,this)}has(t){return Me(this,Rt).has(t)}delete(t){return Me(this,Rt).delete(t)}get size(){return Me(this,Rt).size}}Rt=new WeakMap,Is=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 tt.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 tt.fromCode(new hu("Length too long (> 4 bytes)"))},al=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw tt.fromCode(new kr("Invalid length 0"));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw tt.fromCode(new kr("Length too long (> 4 bytes)"))},l8=(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 tt.fromCode(new kr("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 h8(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 d8=(e,t)=>{let n=0;const r=(c,a)=>{if(i[n++]!==c)throw tt.fromCode(new kr(`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 tt.fromCode(new kr("Not the expected OID."));n+=t.byteLength,r(3,"bit string");const s=l8(i,n)-1;n+=al(i,n),r(0,"0 padding");const o=i.slice(n);if(s!==o.length)throw tt.fromCode(new zl(s,o.length));return o};var Ko,Go;const ki=class ki{constructor(t){rn(this,Ko);rn(this,Go);if(t.byteLength!==ki.RAW_KEY_LENGTH)throw tt.fromCode(new kr("An Ed25519 public key must be exactly 32 bytes long"));Yt(this,Ko,t),Yt(this,Go,ki.derEncode(t))}static from(t){return this.fromDer(t.toDer())}static fromRaw(t){return new ki(t)}static fromDer(t){return new ki(this.derDecode(t))}static derEncode(t){return h8(t,R0)}static derDecode(t){const n=d8(t,R0);if(n.length!==this.RAW_KEY_LENGTH)throw tt.fromCode(new kr("An Ed25519 public key must be exactly 32 bytes long"));return n}get rawKey(){return Me(this,Ko)}get derKey(){return Me(this,Go)}toDer(){return this.derKey}toRaw(){return this.rawKey}};Ko=new WeakMap,Go=new WeakMap,ki.RAW_KEY_LENGTH=32;let ul=ki;class p8{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 y8 extends p8{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 C0=.5,U0=1.5,H0=500,F0=6e4,M0=9e5,L0=10;var Fn,Wo,Xo,zo,Yo,Zo,Jo,Qo,Os;const Va=class Va{constructor(t=Va.default){rn(this,Fn);rn(this,Wo);rn(this,Xo);rn(this,zo);rn(this,Yo);rn(this,Zo);rn(this,Jo);rn(this,Qo);rn(this,Os,0);const{initialInterval:n=H0,randomizationFactor:r=C0,multiplier:i=U0,maxInterval:s=F0,maxElapsedTime:o=M0,maxIterations:c=L0,date:a=Date}=t;Yt(this,Fn,n),Yt(this,Wo,r),Yt(this,Xo,i),Yt(this,zo,s),Yt(this,Qo,a),Yt(this,Yo,a.now()),Yt(this,Zo,o),Yt(this,Jo,c)}get ellapsedTimeInMsec(){return Me(this,Qo).now()-Me(this,Yo)}get currentInterval(){return Me(this,Fn)}get count(){return Me(this,Os)}get randomValueFromInterval(){const t=Me(this,Wo)*Me(this,Fn),n=Me(this,Fn)-t,r=Me(this,Fn)+t;return Math.random()*(r-n)+n}incrementCurrentInterval(){return Yt(this,Fn,Math.min(Me(this,Fn)*Me(this,Xo),Me(this,zo))),Mh(this,Os)._++,Me(this,Fn)}next(){return this.ellapsedTimeInMsec>=Me(this,Zo)||Me(this,Os)>=Me(this,Jo)?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};Fn=new WeakMap,Wo=new WeakMap,Xo=new WeakMap,zo=new WeakMap,Yo=new WeakMap,Zo=new WeakMap,Jo=new WeakMap,Qo=new WeakMap,Os=new WeakMap,Va.default={initialInterval:H0,randomizationFactor:C0,multiplier:U0,maxInterval:F0,maxElapsedTime:M0,maxIterations:L0,date:Date};let fl=Va;var wr;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(wr||(wr={}));const ll=60*1e3,g8=1e6,m8=0,w8="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae",b8="ic0.app",E8=".ic0.app",_8="icp0.io",S8=".icp0.io",T8="icp-api.io",x8=".icp-api.io",hf=200,A8=202,v8=404;function I8(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw cn.fromCode(new To("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 cn.fromCode(new To("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 cn.fromCode(new To("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function O8(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 xr{#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=m8,this.#g=!1,this.#a=null,this.#w=!1,this._isAgent=!0,this.config={},this.log=new y8,this.#f=[],this.#l=[],this.#h=new f8({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=Ge.fromUint8Array(l).toText();let y;if(o===Rs.Replied){const{reply:_}=i;y=Na({status:o,reply:_,timestamp:BigInt(f),request_id:a})}else if(o===Rs.Rejected){const{reject_code:_,reject_message:w,error_code:T}=i;y=Na({status:o,reject_code:_,reject_message:w,error_code:T,timestamp:BigInt(f),request_id:a})}else throw an.fromCode(new qn(`Unknown status: ${o}`));const g=$e(ox,y),m=s.nodeKeys.get(d);if(!m)throw yt.fromCode(new oh);const E=ul.fromDer(m).rawKey;if(u8.verify(u.signature,g,E))return i;throw An.fromCode(new ch(d))}return i},this.config=t,this.#s=t.fetch||I8()||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=ic(w8);const n=O8(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(E8)?this.host.hostname=b8:this.host.hostname.endsWith(S8)?this.host.hostname=_8:this.host.hostname.endsWith(x8)&&(this.host.hostname=T8),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 tt.fromCode(new ds("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw tt.fromCode(new ds("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=xr.createSync(t);return await n.#y(),n}static async from(t){try{return"config"in t?await xr.create(t.config):await xr.create({fetch:t._fetch,fetchOptions:t._fetchOptions,callOptions:t._callOptions,host:t._host.toString(),identity:t._identity??void 0})}catch{throw tt.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 cn.fromCode(new Ni);return(await this.#n).getPrincipal()}async call(t,n,r){const i=n.callSync??!0,s=await(r??this.#n);if(!s)throw cn.fromCode(new Ni);const o=Ge.from(t),c=n.effectiveCanisterId?Ge.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:Ri.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(S){return Object.assign(S,{__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?tr(T):null;return{requestId:E,response:{...O,body:A},requestDetails:f}}catch(S){let _;if(S instanceof br){if(S.hasCode(Aa))return this.log.warn("v3 api not supported. Fall back to v2"),this.call(t,{...n,callSync:!1},r);if(S.hasCode(ds)&&!this.#g)return await this.syncTime(o),this.call(o,n,r);S.code.requestContext={requestId:E,senderPubKey:l.body.sender_pubkey,senderSignature:l.body.sender_sig,ingressExpiry:l.body.content.ingress_expiry},_=S}else _=an.fromCode(new qn(S));throw this.log.error(`Error while making call: ${_.message}`,_),_}}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 an.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={...tr(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:
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: ${yc(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 yc(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 rw(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 tt.fromCode(new nh(e))}const rw=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=rw(o),u=nl(c);return[a,u]}).sort(([o],[c])=>mS(o,c)),i=$e(...r.map(o=>$e(...o)));return En(i)}new TextEncoder().encode(`
66
+ ic-request`);const ox=new TextEncoder().encode("\vic-response");new TextEncoder().encode("ic-request-auth-delegation");class s0{getPrincipal(){return Ge.anonymous()}async transformRequest(t){return{...t,body:{content:t.body}}}}class Zi extends Error{constructor(t){super(t),this.name="DecodingError"}}const iw=55799,sw=Symbol("CBOR_STOP_CODE");var Vn=(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))(Vn||{}),xt=(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))(xt||{});const cx=23,ax=255,ux=65535,fx=4294967295,lx=BigInt("0xffffffffffffffff");var Ln=(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))(Ln||{});const Ts=!1;function hx(e){return e==null}function ow(e,t){const n=new Uint8Array(t);return n.set(e),n}const dx=new TextDecoder;function px(e){return(e&224)>>5}function yx(e){return e&31}let Uo=new Uint8Array,no,Dn=0;function gx(e,t){Uo=e,Dn=0;const n=Mi();return t?.(n)??n}function Mi(e){const[t,n]=ta();switch(t){case xt.UnsignedInteger:return Gs(n);case xt.NegativeInteger:return Ex(n);case xt.ByteString:return cw(n);case xt.TextString:return rl(n);case xt.Array:return mx(n);case xt.Map:return bx(n);case xt.Tag:return _x(n);case xt.Simple:return wx(n)}throw new Zi(`Unsupported major type: ${t}`)}function ta(){const e=Uo.at(Dn);if(hx(e))throw new Zi("Provided CBOR data is empty");const t=px(e),n=yx(e);return Dn++,[t,n]}function mx(e,t){const n=Gs(e);if(n===1/0){const i=[];let s=Mi();for(;s!==sw;)i.push(s),s=Mi();return i}const r=new Array(n);for(let i=0;i<n;i++){const s=Mi();r[i]=s}return r}function wx(e){switch(e){case Vn.False:return!1;case Vn.True:return!0;case Vn.Null:return null;case Vn.Undefined:return;case Vn.Break:return sw}throw new Zi(`Unrecognized simple type: ${e.toString(2)}`)}function bx(e,t){const n=Gs(e),r={};if(n===1/0){let[i,s]=ta();for(;i!==xt.Simple&&s!==Vn.Break;){const o=rl(s),c=Mi();r[o]=c,[i,s]=ta()}return r}for(let i=0;i<n;i++){const[s,o]=ta();if(s!==xt.TextString)throw new Zi("Map keys must be text strings");const c=rl(o),a=Mi();r[c]=a}return r}function Gs(e){if(e<=Ln.Value)return e;switch(no=new DataView(Uo.buffer,Uo.byteOffset+Dn),e){case Ln.OneByte:return Dn++,no.getUint8(0);case Ln.TwoBytes:return Dn+=2,no.getUint16(0,Ts);case Ln.FourBytes:return Dn+=4,no.getUint32(0,Ts);case Ln.EightBytes:return Dn+=8,no.getBigUint64(0,Ts);case Ln.Indefinite:return 1/0;default:throw new Zi(`Unsupported integer info: ${e.toString(2)}`)}}function Ex(e){const t=Gs(e);return typeof t=="number"?-1-t:-1n-t}function cw(e){const t=Gs(e);if(t>Number.MAX_SAFE_INTEGER)throw new Zi("Byte length is too large");const n=Number(t);return Dn+=n,Uo.slice(Dn-n,Dn)}function rl(e){const t=cw(e);return dx.decode(t)}function _x(e,t){const n=Gs(e);if(n===iw)return Mi();throw new Zi(`Unsupported tag: ${n}.`)}class uh extends Error{constructor(t){super(t),this.name="SerializationError"}}const Sx=2*1024,Tx=100,xx=new TextEncoder;function ro(e){return e<<5}let wn=new Uint8Array(Sx),Hn=new DataView(wn.buffer),Tt=0,Ju=[];function Ax(e,t){Tt=0;const n=t?.(e)??e;return Rx(iw,n,t),wn.slice(0,Tt)}function fh(e,t){if(Tt>wn.length-Tx&&(wn=ow(wn,wn.length*2),Hn=new DataView(wn.buffer)),e===!1||e===!0||e===null||e===void 0){Ox(e);return}if(typeof e=="number"||typeof e=="bigint"){Px(e);return}if(typeof e=="string"){fw(e);return}if(e instanceof Uint8Array){o0(e);return}if(e instanceof ArrayBuffer){o0(new Uint8Array(e));return}if(Array.isArray(e)){vx(e,t);return}if(typeof e=="object"){Ix(e,t);return}throw new uh(`Unsupported type: ${typeof e}`)}function vx(e,t){Ws(xt.Array,e.length),e.forEach((n,r)=>{fh(t?.(n,r.toString())??n,t)})}function Ix(e,t){Ju=Object.entries(e),Ws(xt.Map,Ju.length),Ju.forEach(([n,r])=>{fw(n),fh(t?.(r,n)??r,t)})}function Ws(e,t){if(t<=cx){Hn.setUint8(Tt++,ro(e)|Number(t));return}if(t<=ax){Hn.setUint8(Tt++,ro(e)|Ln.OneByte),Hn.setUint8(Tt,Number(t)),Tt+=1;return}if(t<=ux){Hn.setUint8(Tt++,ro(e)|Ln.TwoBytes),Hn.setUint16(Tt,Number(t),Ts),Tt+=2;return}if(t<=fx){Hn.setUint8(Tt++,ro(e)|Ln.FourBytes),Hn.setUint32(Tt,Number(t),Ts),Tt+=4;return}if(t<=lx){Hn.setUint8(Tt++,ro(e)|Ln.EightBytes),Hn.setBigUint64(Tt,BigInt(t),Ts),Tt+=8;return}throw new uh(`Value too large to encode: ${t}`)}function Ox(e){Ws(xt.Simple,Bx(e))}function Bx(e){if(e===!1)return Vn.False;if(e===!0)return Vn.True;if(e===null)return Vn.Null;if(e===void 0)return Vn.Undefined;throw new uh(`Unrecognized simple value: ${e.toString()}`)}function aw(e,t){Ws(e,t.length),Tt>wn.length-t.length&&(wn=ow(wn,wn.length+t.length),Hn=new DataView(wn.buffer)),wn.set(t,Tt),Tt+=t.length}function uw(e,t){Ws(e,t)}function Nx(e){uw(xt.UnsignedInteger,e)}function kx(e){uw(xt.NegativeInteger,typeof e=="bigint"?-1n-e:-1-e)}function Px(e){e>=0?Nx(e):kx(e)}function fw(e){aw(xt.TextString,xx.encode(e))}function o0(e){aw(xt.ByteString,e)}function Rx(e,t,n){Ws(xt.Tag,e),fh(t,n)}function Cx(e){return typeof e=="object"&&e!==null&&"toCborValue"in e}function Qu(e){try{return Ax(e,t=>Ge.isPrincipal(t)?t.toUint8Array():xs.isExpiry(t)?t.toBigInt():Cx(t)?t.toCborValue():t)}catch(t){throw tt.fromCode(new Zl(t,e))}}function tr(e){try{return gx(e)}catch(t){throw tt.fromCode(new Yl(t,e))}}const Rc=()=>{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 Ri;(function(e){e.Query="read",e.ReadState="read_state",e.Call="call"})(Ri||(Ri={}));var il;(function(e){e.Call="call"})(il||(il={}));var Ho;(function(e){e.Query="query",e.ReadState="read_state"})(Ho||(Ho={}));function sl(){const e=new ArrayBuffer(16),t=new DataView(e),n=Rc(),r=Rc(),i=Rc(),s=Rc();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),Ux=BigInt(1e6),lw=BigInt(60),Hx=BigInt(90)*lh;function hw(e){return e/lh}function Fx(e){return hw(e)/lw}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<Hx?s=hw(i):s=Fx(i)*lw,new xs(s*lh*Ux)}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 tt(new Oa(`Not a valid BigInt: ${r}`))}throw new tt(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===Ri.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 Fo(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=rc(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 dw(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);return e===""?hh:BigInt("0x"+e)}function ir(e){return dw(rt(e))}function Mo(e){return On(e),dw(rt(Uint8Array.from(e).reverse()))}function Ut(e,t){return ic(e.toString(16).padStart(t*2,"0"))}function pw(e,t){return Ut(e,t).reverse()}function on(e,t,n){let r;if(typeof t=="string")try{r=ic(t)}catch(s){throw new Error(e+" must be hex string or Uint8Array, cause: "+s)}else if(rc(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 yw(e,t,n){return tf(e)&&tf(t)&&tf(n)&&t<=e&&e<n}function u0(e,t,n,r){if(!yw(t,n,r))throw new Error("expected valid "+e+": "+n+" <= n < "+r+", got "+t)}function Lo(e){let t;for(t=0;e>hh;e>>=ka,t+=1);return t}function Mx(e,t){return e>>BigInt(t)&ka}const Ji=e=>(ka<<BigInt(e))-ka;function Lx(e){return typeof e=="function"&&Number.isSafeInteger(e.outputLen)}function gc(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 gw=()=>{throw new Error("not implemented")};function qo(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 ln=BigInt(0),Mt=BigInt(1),Ci=BigInt(2),mw=BigInt(3),ww=BigInt(4),bw=BigInt(5),qx=BigInt(7),Ew=BigInt(8),Vx=BigInt(9),_w=BigInt(16);function mt(e,t){const n=e%t;return n>=ln?n:t+n}function Zn(e,t,n){let r=e;for(;t-- >ln;)r*=r,r%=n;return r}function f0(e,t){if(e===ln)throw new Error("invert: expected non-zero number");if(t<=ln)throw new Error("invert: expected positive modulus, got "+t);let n=mt(e,t),r=t,i=ln,s=Mt;for(;n!==ln;){const c=r/n,a=r%n,u=i-s*c;r=n,n=a,i=s,s=u}if(r!==Mt)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 Sw(e,t){const n=(e.ORDER+Mt)/ww,r=e.pow(t,n);return dh(e,r,t),r}function Dx(e,t){const n=(e.ORDER-bw)/Ew,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 $x(e){const t=pi(e),n=Tw(e),r=n(t,t.neg(t.ONE)),i=n(t,r),s=n(t,t.neg(r)),o=(e+qx)/_w;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 Tw(e){if(e<mw)throw new Error("sqrt is not defined for small field");let t=e-Mt,n=0;for(;t%Ci===ln;)t/=Ci,n++;let r=Ci;const i=pi(e);for(;Pa(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Sw;let s=i.pow(r,t);const o=(t+Mt)/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=Mt<<BigInt(f-g-1),S=a.pow(l,E);f=g,l=a.sqr(S),d=a.mul(d,l),y=a.mul(y,S)}return y}}function jx(e){return e%ww===mw?Sw:e%Ew===bw?Dx:e%_w===Vx?$x(e):Tw(e)}const Kx=(e,t)=>(mt(e,t)&Mt)===Mt,Gx=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function xw(e){const t={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=Gx.reduce((r,i)=>(r[i]="function",r),t);return gc(e,n),e}function yu(e,t,n){if(n<ln)throw new Error("invalid exponent, negatives unsupported");if(n===ln)return e.ONE;if(n===Mt)return t;let r=e.ONE,i=t;for(;n>ln;)n&Mt&&(r=e.mul(r,i)),i=e.sqr(i),n>>=Mt;return r}function Qi(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-Mt)/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 Wx(e,t){t!==void 0&&Nb(t);const n=t!==void 0?t:e.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function pi(e,t,n=!1,r={}){if(e<=ln)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}=Wx(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:Ji(a),ZERO:ln,ONE:Mt,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 ln<=d&&d<e},is0:d=>d===ln,isValidNot0:d=>!l.is0(d)&&l.isValid(d),isOdd:d=>(d&Mt)===Mt,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=jx(e)),f(l,d))),toBytes:d=>n?pw(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?Mo(d):ir(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=>Qi(l,d),cmov:(d,y,g)=>g?y:d});return Object.freeze(l)}function Aw(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 vw(e){const t=Aw(e);return t+Math.ceil(t/2)}function Xx(e,t,n=!1){const r=e.length,i=Aw(t),s=vw(t);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Mo(e):ir(e),c=mt(o,t-Mt)+Mt;return n?pw(c,i):Ut(c,i)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Hs=BigInt(0),Ui=BigInt(1);function Ra(e,t){const n=t.negate();return e?n:t}function Sr(e,t){const n=Qi(e.Fp,t.map(r=>r.Z));return t.map((r,i)=>e.fromAffine(r.toAffine(n[i])))}function Iw(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){Iw(e,t);const n=Math.ceil(t/e)+1,r=2**(e-1),i=2**e,s=Ji(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+=Ui);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 zx(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 Yx(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,Ow=new WeakMap;function sf(e){return Ow.get(e)||1}function h0(e){if(e!==Hs)throw new Error("invalid wNAF")}class Bw{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&Ui&&(r=r.add(i)),i=i.double(),n>>=Ui;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){Iw(n,this.bits),Ow.set(t,n),rf.delete(t)}hasCache(t){return sf(t)!==1}}function Zx(e,t,n,r){let i=t,s=e.ZERO,o=e.ZERO;for(;n>Hs||r>Hs;)n&Ui&&(s=s.add(i)),r&Ui&&(o=o.add(i)),i=i.double(),n>>=Ui,r>>=Ui;return{p1:s,p2:o}}function Nw(e,t,n,r){zx(n,e),Yx(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=Lo(BigInt(i));let a=1;c>12?a=c-3:c>4?a=c-2:c>0&&(a=2);const u=Ji(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],S=Number(E>>BigInt(y)&u);f[S]=f[S].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 xw(t),t}else return pi(e,{isLE:n})}function kw(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 Jx=ir;function ri(e,t){if(Vo(e),Vo(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 Qx(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 Vo(e){if(!Number.isSafeInteger(e))throw new Error("number expected")}function Pw(e){if(!rc(e)&&typeof e!="string")throw new Error("DST must be Uint8Array or string");return typeof e=="string"?dt(e):e}function e3(e,t,n,r){On(e),Vo(n),t=Pw(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,ri(t.length,1)),a=ri(0,s),u=ri(n,2),f=new Array(o),l=r($e(a,e,u,ri(0,1),c));f[0]=r($e(l,ri(1,1),c));for(let y=1;y<=o;y++){const g=[Qx(l,f[y-1]),ri(y+1,1),c];f[y]=r($e(...g))}return $e(...f).slice(0,n)}function t3(e,t,n,r,i){if(On(e),Vo(n),t=Pw(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(ri(n,2)).update(t).update(ri(t.length,1)).digest()}function of(e,t,n){gc(n,{p:"bigint",m:"number",k:"number",hash:"function"});const{p:r,k:i,m:s,hash:o,expand:c,DST:a}=n;if(!Lx(n.hash))throw new Error("expected valid hash");On(e),Vo(t);const u=r.toString(2).length,f=Math.ceil((u+i)/8),l=t*s*f;let d;if(c==="xmd")d=e3(e,a,l,o);else if(c==="xof")d=t3(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 S=f*(E+g*s),_=d.subarray(S,S+f);m[E]=mt(Jx(_),r)}y[g]=m}return y}function Rw(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]=Qi(e,[o,a],!0);return r=e.mul(s,u),i=e.mul(i,e.mul(c,f)),{x:r,y:i}}}const n3=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:n3},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)/yr)/t;function r3(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<Hi,d=f<Hi;l&&(u=-u),d&&(f=-f);const y=Ji(Math.ceil(Lo(n)/2))+Qt;if(u<Hi||u>=y||f<Hi||f>=y)throw new Error("splitScalar (endomorphism): failed, k="+e);return{k1neg:l,k1:u,k2neg:d,k2:f}}const Hi=BigInt(0),Qt=BigInt(1),yr=BigInt(2),ys=BigInt(3),ol=BigInt(4);function Ca(e,t){const{BYTES:n}=e;let r;if(typeof t=="bigint")r=t;else{let i=on("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 i3(e,t={}){const n=kw("weierstrass",e,t),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:c}=s;gc(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=c3(r,i);function f(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function l(K,H,D){const{x:P,y:$}=H.toAffine(),F=r.toBytes(P);if(Fo(D,"isCompressed"),D){f();const x=!r.isOdd($);return $e(s3(x),F)}else return $e(Uint8Array.of(4),F,r.toBytes($))}function d(K){As(K,void 0,"Point");const{publicKey:H,publicKeyUncompressed:D}=u,P=K.length,$=K[0],F=K.subarray(1);if(P===H&&($===2||$===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 L;try{L=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(L);return($&1)===1!==N&&(L=r.neg(L)),{x,y:L}}else if(P===D&&$===4){const x=r.BYTES,B=r.fromBytes(F.subarray(0,x)),L=r.fromBytes(F.subarray(x,x*2));if(!E(B,L))throw new Error("bad point: is not on curve");return{x:B,y:L}}else throw new Error(`bad point: got length ${P}, expected compressed=${H} or uncompressed=${D}`)}const y=t.toBytes||l,g=t.fromBytes||d;function m(K){const H=r.sqr(K),D=r.mul(H,K);return r.add(r.add(D,r.mul(K,s.a)),s.b)}function E(K,H){const D=r.sqr(H),P=m(K);return r.eql(D,P)}if(!E(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const S=r.mul(r.pow(s.a,ys),ol),_=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,D=!1){if(!r.isValid(H)||D&&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 r3(K,a.basises,i.ORDER)}const A=qo((K,H)=>{const{X:D,Y:P,Z:$}=K;if(r.eql($,r.ONE))return{x:D,y:P};const F=K.is0();H==null&&(H=F?r.ONE:r.inv($));const x=r.mul(D,H),B=r.mul(P,H),L=r.mul($,H);if(F)return{x:r.ZERO,y:r.ZERO};if(!r.eql(L,r.ONE))throw new Error("invZ was invalid");return{x,y:B}}),R=qo(K=>{if(K.is0()){if(t.allowInfinityPoint&&!r.is0(K.Y))return;throw new Error("bad point: ZERO")}const{x:H,y:D}=K.toAffine();if(!r.isValid(H)||!r.isValid(D))throw new Error("bad point: x or y not field elements");if(!E(H,D))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,D,P,$){return D=new v(r.mul(D.X,K),D.Y,D.Z),H=Ra(P,H),D=Ra($,D),H.add(D)}class v{constructor(H,D,P){this.X=w("x",H),this.Y=w("y",D,!0),this.Z=w("z",P),Object.freeze(this)}static CURVE(){return s}static fromAffine(H){const{x:D,y:P}=H||{};if(!H||!r.isValid(D)||!r.isValid(P))throw new Error("invalid affine point");if(H instanceof v)throw new Error("projective point not allowed");return r.is0(D)&&r.is0(P)?v.ZERO:new v(D,P,r.ONE)}static fromBytes(H){const D=v.fromAffine(g(As(H,void 0,"point")));return D.assertValidity(),D}static fromHex(H){return v.fromBytes(on("pointHex",H))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(H=8,D=!0){return q.createCache(this,H),D||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:D,Y:P,Z:$}=this,{X:F,Y:x,Z:B}=H,L=r.eql(r.mul(D,B),r.mul(F,$)),N=r.eql(r.mul(P,B),r.mul(x,$));return L&&N}negate(){return new v(this.X,r.neg(this.Y),this.Z)}double(){const{a:H,b:D}=s,P=r.mul(D,ys),{X:$,Y:F,Z:x}=this;let B=r.ZERO,L=r.ZERO,N=r.ZERO,V=r.mul($,$),G=r.mul(F,F),X=r.mul(x,x),Y=r.mul($,F);return Y=r.add(Y,Y),N=r.mul($,x),N=r.add(N,N),B=r.mul(H,N),L=r.mul(P,X),L=r.add(B,L),B=r.sub(G,L),L=r.add(G,L),L=r.mul(B,L),B=r.mul(Y,B),N=r.mul(P,N),X=r.mul(H,X),Y=r.sub(V,X),Y=r.mul(H,Y),Y=r.add(Y,N),N=r.add(V,V),V=r.add(N,V),V=r.add(V,X),V=r.mul(V,Y),L=r.add(L,V),X=r.mul(F,x),X=r.add(X,X),V=r.mul(X,Y),B=r.sub(B,V),N=r.mul(X,G),N=r.add(N,N),N=r.add(N,N),new v(B,L,N)}add(H){T(H);const{X:D,Y:P,Z:$}=this,{X:F,Y:x,Z:B}=H;let L=r.ZERO,N=r.ZERO,V=r.ZERO;const G=s.a,X=r.mul(s.b,ys);let Y=r.mul(D,F),ce=r.mul(P,x),ue=r.mul($,B),te=r.add(D,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,$),L=r.add(x,B),ae=r.mul(ae,L),L=r.add(ce,ue),ae=r.sub(ae,L),V=r.mul(G,Z),L=r.mul(X,ue),V=r.add(L,V),L=r.sub(ce,V),V=r.add(ce,V),N=r.mul(L,V),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),L=r.mul(te,L),L=r.sub(L,Y),Y=r.mul(te,ce),V=r.mul(ae,V),V=r.add(V,Y),new v(L,N,V)}subtract(H){return this.add(H.negate())}is0(){return this.equals(v.ZERO)}multiply(H){const{endo:D}=t;if(!i.isValidNot0(H))throw new Error("invalid scalar: out of range");let P,$;const F=x=>q.cached(this,x,B=>Sr(v,B));if(D){const{k1neg:x,k1:B,k2neg:L,k2:N}=O(H),{p:V,f:G}=F(B),{p:X,f:Y}=F(N);$=G.add(Y),P=M(D.beta,V,X,x,L)}else{const{p:x,f:B}=F(H);P=x,$=B}return Sr(v,[P,$])[0]}multiplyUnsafe(H){const{endo:D}=t,P=this;if(!i.isValid(H))throw new Error("invalid scalar: out of range");if(H===Hi||P.is0())return v.ZERO;if(H===Qt)return P;if(q.hasCache(this))return this.multiply(H);if(D){const{k1neg:$,k1:F,k2neg:x,k2:B}=O(H),{p1:L,p2:N}=Zx(v,P,F,B);return M(D.beta,L,N,$,x)}else return q.unsafe(P,H)}multiplyAndAddUnsafe(H,D,P){const $=this.multiplyUnsafe(D).add(H.multiplyUnsafe(P));return $.is0()?void 0:$}toAffine(H){return A(this,H)}isTorsionFree(){const{isTorsionFree:H}=t;return o===Qt?!0:H?H(v,this):q.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 Fo(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 Sr(v,H)}static msm(H,D){return Nw(v,i,H,D)}static fromPrivateKey(H){return v.BASE.multiply(Ca(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 C=i.BITS,q=new Bw(v,t.endo?Math.ceil(C/2):C);return v.BASE.precompute(8),v}function s3(e){return Uint8Array.of(e?2:3)}function o3(e,t){const n=e.ORDER;let r=Hi;for(let g=n-Qt;g%yr===Hi;g/=yr)r+=Qt;const i=r,s=yr<<i-Qt-Qt,o=s*yr,c=(n-Qt)/o,a=(c-Qt)/yr,u=o-Qt,f=s,l=e.pow(t,c),d=e.pow(t,(c+Qt)/yr);let y=(g,m)=>{let E=l,S=e.pow(m,u),_=e.sqr(S);_=e.mul(_,m);let w=e.mul(g,_);w=e.pow(w,a),w=e.mul(w,S),S=e.mul(w,m),_=e.mul(w,g);let T=e.mul(_,S);w=e.pow(T,f);let O=e.eql(w,e.ONE);S=e.mul(_,d),w=e.mul(T,E),_=e.cmov(S,_,O),T=e.cmov(w,T,O);for(let A=i;A>Qt;A--){let R=A-yr;R=yr<<R-Qt;let M=e.pow(T,R);const v=e.eql(M,e.ONE);S=e.mul(_,E),E=e.mul(E,E),M=e.mul(T,E),_=e.cmov(S,_,v),T=e.cmov(M,T,v)}return{isValid:O,value:_}};if(e.ORDER%ol===ys){const g=(e.ORDER-ys)/ol,m=e.sqrt(e.neg(t));y=(E,S)=>{let _=e.sqr(S);const w=e.mul(E,S);_=e.mul(_,w);let T=e.pow(_,g);T=e.mul(T,w);const O=e.mul(T,m),A=e.mul(e.sqr(T),S),R=e.eql(A,E);let M=e.cmov(O,T,R);return{isValid:R,value:M}}}return y}function Cw(e,t){xw(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=o3(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 S=e.isOdd(o)===e.isOdd(g);g=e.cmov(e.neg(g),g,S);const _=Qi(e,[f],!0)[0];return y=e.mul(y,_),{x:y,y:g}}}function c3(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}=a3(e),r=i3(t,n);return f3(e,r)}function a3(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=pi(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 u3(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 f3(e,t){const{Fp:n,Fn:r}=t;function i(o){return yw(o,Qt,r.ORDER)}const s=u3(n,e.a,e.b);return Object.assign({},{CURVE:e,Point:t,ProjectivePoint:t,normPrivateKeyToScalar:o=>Ca(r,o),weierstrassEquation:s,isWithinCurveOrder:i})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const l3=BigInt(0),Uc=BigInt(1),m0=BigInt(2),gs=BigInt(3);function h3(e){const t=[];for(;e>Uc;e>>=Uc)(e&Uc)===l3?t.unshift(0):(e&gs)===gs?(t.unshift(-1),e+=Uc):t.unshift(1);return t}function cf(e){if(!Array.isArray(e)||e.length===0)throw new Error("expected non-empty array")}function d3(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)),C=i.mul(v,gs),q=i.sub(i.sub(i.sqr(i.add(O,A)),M),R),K=i.sub(v,R),H=i.mul(i.sqr(T),gs),D=i.neg(q);return w.push([K,H,D]),T=i.mul(i.mul(i.mul(i.sub(R,C),T),O),l),O=i.sub(i.sqr(i.mul(i.add(R,C),l)),i.mul(i.sqr(v),gs)),A=i.mul(R,q),{Rx:T,Ry:O,Rz:A}}function y(w,T,O,A,R,M){const v=i.sub(O,i.mul(M,A)),C=i.sub(T,i.mul(R,A)),q=i.sub(i.mul(v,R),i.mul(C,M)),K=i.neg(v),H=C;w.push([q,K,H]);const D=i.sqr(C),P=i.mul(D,C),$=i.mul(D,T),F=i.add(i.sub(P,i.mul($,m0)),i.mul(i.sqr(v),A));return T=i.mul(C,F),O=i.sub(i.mul(i.sub($,F),v),i.mul(P,O)),A=i.mul(A,P),{Rx:T,Ry:O,Rz:A}}const g=h3(c),m=qo(w=>{const T=w,{x:O,y:A}=T.toAffine(),R=O,M=A,v=i.neg(A);let C=R,q=M,K=i.ONE;const H=[];for(const D of g){const P=[];({Rx:C,Ry:q,Rz:K}=d(P,C,q,K)),D&&({Rx:C,Ry:q,Rz:K}=y(P,C,q,K,R,D===-1?v:M)),H.push(P)}if(u){const D=H[H.length-1];u(C,q,K,R,M,y.bind(null,D))}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,C]of w)for(const[q,K,H]of M[R])O=f(q,K,H,O,v,C)}}return a&&(O=s.conjugate(O)),T?s.finalExponentiate(O):O}function S(w,T=!0){const O=[];Sr(t,w.map(({g1:A})=>A)),Sr(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 _(w,T,O=!0){return S([{g1:w,g2:T}],O)}return{Fp12:s,millerLoopBatch:E,pairing:_,pairingBatch:S,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=Ca(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=Ca(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,S=u(d),_=l,w=o([f(m,S),f(E,_)]);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),S=new Map;for(let T=0;T<E.length;T++){const O=E[T],A=m[T];let R=S.get(A);R===void 0&&(R=[],S.set(A,R)),R.push(O)}const _=[],w=t.Point.BASE;try{for(const[T,O]of S){const A=O.reduce((R,M)=>R.add(M));_.push(f(A,T))}return _.push(f(w.negate(),g)),s.eql(o(_),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 p3(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=d3(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),S=e.randomBytes||sg,_=()=>{const x=vw(n.ORDER);return Xx(S(x),n.ORDER)},w={randomSecretKey:_,randomPrivateKey:_,calcPairingPrecomputes:g},{ShortSignature:T}=e.G1,{Signature:O}=e.G2;function A(x,B){return x instanceof c.Point?x:E.hash(on("point",x),B?.DST)}function R(x,B){return x instanceof u.Point?x:m.hash(on("point",x),B?.DST)}function M(x){return m.getPublicKey(x).toBytes(!0)}function v(x){return E.getPublicKey(x).toBytes(!0)}function C(x,B,L){const N=R(x,L),V=m.sign(N,B);return x instanceof u.Point?V:O.toBytes(V)}function q(x,B,L){const N=A(x,L),V=E.sign(N,B);return x instanceof c.Point?V:T.toBytes(V)}function K(x,B,L,N){const V=R(B,N);return m.verify(x,V,L)}function H(x,B,L,N){const V=A(B,N);return E.verify(x,V,L)}function D(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 $(x){const B=E.aggregateSignatures(x);return x[0]instanceof c.Point?B:T.toBytes(B)}function F(x,B,L,N){const V=B.map(G=>R(G,N));return m.verifyBatch(x,V,L)}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:C,signShortSignature:q,verify:K,verifyShortSignature:H,aggregatePublicKeys:D,aggregateSignatures:P,aggregateShortSignatures:$,G1:c,G2:u,Signature:O,ShortSignature:T}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const b0=BigInt(0),Tr=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=Tr;d<r;d++){const g=(f*y-f)/o%c;l.push(e.pow(t,g)),y*=n}a.push(l)}return a}function y3(e,t,n){const r=t.pow(n,(e.ORDER-Tr)/E0),i=t.pow(n,(e.ORDER-Tr)/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-Tr)/E0),c=t.pow(n,(e.ORDER**tn-Tr)/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 g3{constructor(t,n={}){this.MASK=Tr;const r=t.ORDER,i=r*r;this.Fp=t,this.ORDER=i,this.BITS=Lo(i),this.BYTES=Math.ceil(Lo(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 Qi(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)==Tr}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 m3{constructor(t){this.MASK=Tr,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 gw()}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 Qi(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 w3{constructor(t,n){this.MASK=Tr;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){gw()}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 Qi(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),S=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(S,a),tn),S),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),Mx(n,i)&&(r=this.mul(r,t));return r}}function b3(e){const t=pi(e.ORDER),n=new g3(t,e),r=new m3(n),i=new w3(r,e);return{Fp:t,Fp2:n,Fp6:r,Fp12:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Kt=BigInt(0),Ua=BigInt(1),kn=BigInt(2),gu=BigInt(3),Do=BigInt(4),ii=BigInt("0xd201000000010000"),E3=Lo(ii),Gi={p:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),n:BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001"),h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),a:Kt,b:Do,Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1")},_3=pi(Gi.n,{modFromBytes:!0,isLE:!0}),{Fp:Ee,Fp2:Ce,Fp6:S3,Fp12:Le}=b3({ORDER:Gi.p,X_LEN:E3,FP2_NONRESIDUE:[Ua,Ua],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=ii,n=Le.div(Le.frobeniusMap(e,6),e),r=Le.mul(Le.frobeniusMap(n,2),n),i=Le.conjugate(Le._cyclotomicExp(r,t)),s=Le.mul(Le.conjugate(Le._cyclotomicSquare(r)),i),o=Le.conjugate(Le._cyclotomicExp(s,t)),c=Le.conjugate(Le._cyclotomicExp(o,t)),a=Le.mul(Le.conjugate(Le._cyclotomicExp(c,t)),Le._cyclotomicSquare(i)),u=Le.conjugate(Le._cyclotomicExp(a,t)),f=Le.frobeniusMap(Le.mul(i,c),2),l=Le.frobeniusMap(Le.mul(o,r),3),d=Le.frobeniusMap(Le.mul(a,Le.conjugate(r)),1),y=Le.mul(Le.mul(u,Le.conjugate(s)),r);return Le.mul(Le.mul(Le.mul(f,l),d),y)}}),{G2psi:S0,G2psi2:T3}=y3(Ee,Ce,Ce.div(Ce.ONE,Ce.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:Ce.ORDER,n:Gi.n,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),a:Ce.ZERO,b:Ce.fromBigTuple([Do,Do]),Gx:Ce.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:Ce.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")])},mu=mc(Ee.toBytes(Kt),{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 mc(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 x3(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 mc(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 mc(Ut(r,t),{compressed:!0,sort:s})}function A3(e){const{compressed:t,infinity:n,sort:r,value:i}=wu(e),{BYTES:s,ORDER:o}=Ee;if(i.length===48&&t){const c=ir(i),a=Ee.create(c&Ji(Ee.BITS));if(n){if(a!==Kt)throw new Error("invalid G1 point: non-empty, at infinity, with compression");return{x:Kt,y:Kt}}const u=Ee.add(Ee.pow(a,gu),Ee.create(Gi.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=ir(i.subarray(0,s)),a=ir(i.subarray(s));if(n){if(c!==Kt||a!==Kt)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(on("signatureHex",e,48)),i=Ee.ORDER,s=bu.G1.Point,o=ir(r);if(t)return s.ZERO;const c=Ee.create(o&Ji(Ee.BITS)),a=Ee.add(Ee.pow(c,gu),Ee.create(Gi.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 v3(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(Kt,r));const a=!!(c.c1===Kt?c.c0*kn/i:c.c1*kn/i);return $e(mc(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}=Ce.reim(o),{re:f,im:l}=Ce.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(Kt,t));const{x:n,y:r}=e.toAffine(),{re:i,im:s}=Ce.reim(n),{re:o,im:c}=Ce.reim(r),u=!!((c>Kt?c*kn:o*kn)/Ee.ORDER&Ua),f=i;return $e(mc(Ut(s,t),{sort:u,compressed:!0}),Ut(f,t))}function I3(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)=>ir(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:Ce.ZERO,y:Ce.ZERO}}const a=c(o,0,t),u=c(o,t,2*t),f=Ce.create({c0:Ee.create(u),c1:Ee.create(a)}),l=Ce.add(Ce.pow(f,gu),yh.b);let d=Ce.sqrt(l);const y=d.c1===Kt?d.c0*kn/n:d.c1*kn/n?Ua:Kt;return d=s&&y>0?d:Ce.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:Ce.ZERO,y:Ce.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:Ce.fromBigTuple([u,a]),y:Ce.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(on("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=ir(i.slice(0,o)),a=ir(i.slice(o));if(n)return s.ZERO;const u=Ee.create(c&Ji(Ee.BITS)),f=Ee.create(a),l=Ce.create({c0:f,c1:u}),d=Ce.add(Ce.pow(l,gu),yh.b);let y=Ce.sqrt(d);if(!y)throw new Error("Failed to find a square root");const{re:g,im:m}=Ce.reim(y),E=BigInt(r),S=m>Kt&&m*kn/t!==E,_=m===Kt&&g*kn/t!==E;(S||_)&&(y=Ce.neg(y));const w=s.fromAffine({x:l,y});return w.assertValidity(),w}const bu=p3({fields:{Fp:Ee,Fp2:Ce,Fp6:S3,Fp12:Le,Fr:_3},G1:{...Gi,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(ii).negate().multiplyUnsafe(ii).equals(r)},clearCofactor:(e,t)=>t.multiplyUnsafe(ii).add(t),mapToCurve:P3,fromBytes:A3,toBytes:x3,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:Ce,hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...af},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:R3,isTorsionFree:(e,t)=>t.multiplyUnsafe(ii).negate().equals(S0(e,t)),clearCofactor:(e,t)=>{const n=ii;let r=t.multiplyUnsafe(n).negate(),i=S0(e,t),s=t.double();return s=T3(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:I3,toBytes:v3,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:ii,r:Gi.n,xNegative:!0,twistType:"multiplicative"},htfDefaults:af}),O3=Rw(Ce,[[["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=>Ce.fromBigTuple(t.map(BigInt))))),B3=Rw(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)))),N3=Cw(Ee,{A:Ee.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:Ee.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:Ee.create(BigInt(11))}),k3=Cw(Ce,{A:Ce.create({c0:Ee.create(Kt),c1:Ee.create(BigInt(240))}),B:Ce.create({c0:Ee.create(BigInt(1012)),c1:Ee.create(BigInt(1012))}),Z:Ce.create({c0:Ee.create(BigInt(-2)),c1:Ee.create(BigInt(-1))})});function P3(e){const{x:t,y:n}=N3(Ee.create(e[0]));return B3(t,n)}function R3(e){const{x:t,y:n}=k3(Ce.fromBigTuple(e));return O3(t,n)}function C3(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 U3=BigInt(1e6),Uw=e=>Nt(new Ds(e)),gh=e=>{const n=Uw(e)/U3;return new Date(Number(n))},A0=60*1e3,H3=60,F3=24,M3=F3*H3,L3=5,q3=5,V3=30*M3;var Ht;(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"})(Ht||(Ht={}));function D3(e,t){for(let n=0;n<e.length;n++)if(e[n]>t[n])return!0;return!1}class Li{#t=!1;#e=void 0;static async create(t){const n=Li.createUnverified(t);return await n.verify(),n}static createUnverified(t){return new Li(t.certificate,t.rootKey,t.canisterId,t.blsVerify??C3,t.maxAgeInMinutes,t.disableTimeVerification,t.agent)}constructor(t,n,r,i,s=L3,o=!1,c){this._rootKey=n,this._canisterId=r,this._blsVerify=i,this._maxAgeInMinutes=s,this.#t=o,this.cert=tr(t),c&&"getTimeDiffMsecs"in c&&"hasSyncedTime"in c&&"syncTime"in c&&(this.#e=c)}lookup_path(t){return wc(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=j3(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+q3*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 Ro(this._maxAgeInMinutes,y,u,c,"past"));if(m)throw this.#e?.hasSyncedTime()?un.fromCode(new qn("System time has been synced with the IC network, but certificate is still too far in the future.")):An.fromCode(new Ro(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=Li.createUnverified({certificate:t.certificate,rootKey:this._rootKey,canisterId:this._canisterId,blsVerify:this._blsVerify,disableTimeVerification:this.#t,maxAgeInMinutes:V3,agent:this.#e});if(n.cert.delegation)throw yt.fromCode(new Gl);await n.verify();const r=t.subnet_id,i=Ge.fromUint8Array(r);if(!Fw({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=ic("308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100"),$3=96;function j3(e){const t=io.byteLength+$3;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 Ht.Empty:return En(bo("ic-hashtree-empty"));case Ht.Pruned:return e[1];case Ht.Leaf:return En($e(bo("ic-hashtree-leaf"),e[1]));case Ht.Labeled:return En($e(bo("ic-hashtree-labeled"),e[1],await na(e[2])));case Ht.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 Hw(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 wc(e,t){if(e.length===0)switch(t[0]){case Ht.Empty:return{status:vn.Absent};case Ht.Leaf:{if(!t[1])throw un.fromCode(new pc("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 Ht.Pruned:return{status:vn.Unknown};case Ht.Labeled:case Ht.Fork:return{status:vn.Error};default:throw Ss}const n=Hw(e),r=xo(n,t);switch(r.status){case ot.Found:return wc(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=Hw(e),r=xo(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 Ht.Empty:return[];case Ht.Fork:return cl(e[1]).concat(cl(e[2]));default:return[e]}}function xo(e,t){switch(t[0]){case Ht.Labeled:return D3(e,t[1])?{status:ot.Greater}:pu(e,t[1])?{status:ot.Found,value:t[2]}:{status:ot.Less};case Ht.Fork:{const n=xo(e,t[1]);switch(n.status){case ot.Greater:{const r=xo(e,t[2]);return r.status===ot.Less?{status:ot.Absent}:r}case ot.Unknown:{const r=xo(e,t[2]);return r.status===ot.Less?{status:ot.Unknown}:r}default:return n}}case Ht.Pruned:return{status:ot.Unknown};default:return{status:ot.Absent}}}function Fw(e){const{canisterId:t,subnetId:n,tree:r}=e,i=wc(["subnet",n.toUint8Array(),"canister_ranges"],r);if(i.status!==vn.Found)throw yt.fromCode(new Us(`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 tr(i.value).map(a=>[Ge.fromUint8Array(a[0]),Ge.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=Ge.from(e.canisterId),s=[...new Set(n)],o=new Map,c=s.map((a,u)=>{const f=G3(a,i);return(async()=>{try{if(t.rootKey===null)throw an.fromCode(new Ks);const l=t.rootKey,d=await t.readState(i,{paths:[f]}),y=await Li.create({certificate:d.certificate,rootKey:l,canisterId:i,disableTimeVerification:r,agent:t}),g=(S,_)=>{if(_==="subnet"){const w=K3(d.certificate,i,l);return{path:_,data:w}}else return{path:_,data:_n(S.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,W3(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,Uw(E));break}case"cbor":{o.set(m.key,tr(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 br&&(l.hasCode(_s)||l.hasCode(Ro)))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},K3=(e,t,n)=>{if(!t._isPrincipal)throw tt.fromCode(new qn("Invalid canisterId"));const r=tr(e),i=r.tree;let s=r.delegation,o;if(s&&s.subnet_id?o=Ge.fromUint8Array(new Uint8Array(s.subnet_id)):!s&&typeof n<"u"?(o=Ge.selfAuthenticating(new Uint8Array(n)),s={subnet_id:o.toUint8Array(),certificate:new Uint8Array(0)}):(o=Ge.selfAuthenticating(Ge.fromText("tdb26-jop6k-aogll-7ltgs-eruif-6kk7m-qpktf-gdiqx-mxtrf-vb5e6-eqe").toUint8Array()),s={subnet_id:o.toUint8Array(),certificate:new Uint8Array(0)}),!Fw({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 Us("Node not found",a.status));if(a.value instanceof Uint8Array)throw un.fromCode(new pc("Invalid node tree"));const u=cl(a.value),f=new Map;return u.forEach(l=>{const d=Ge.from(l[1]).toText(),y=wc(["public_key"],l[2]);if(y.status!==vn.Found)throw yt.fromCode(new Us("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:Ge.fromUint8Array(new Uint8Array(s.subnet_id)).toText(),nodeKeys:f}},G3=(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 un.fromCode(new qn(`Error while encoding your path for canister status. Please ensure that your path ${e} was formatted correctly.`))},W3=e=>tr(e).map(n=>Ge.fromUint8Array(n));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vr=BigInt(0),Bt=BigInt(1),lf=BigInt(2),X3=BigInt(8);function z3(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 Y3(e,t={}){const n=kw("edwards",e,t,t.FpFnLE),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o}=s;gc(t,{},{uvRatio:"function"});const c=lf<<BigInt(i.BYTES*8)-Bt,a=E=>r.create(E),u=t.uvRatio||((E,S)=>{try{return{isValid:!0,value:r.sqrt(r.div(E,S))}}catch{return{isValid:!1,value:Vr}}});if(!z3(r,s,s.Gx,s.Gy))throw new Error("bad curve params: generator point");function f(E,S,_=!1){const w=_?Bt:Vr;return u0("coordinate "+E,S,w,c),S}function l(E){if(!(E instanceof g))throw new Error("ExtendedPoint expected")}const d=qo((E,S)=>{const{X:_,Y:w,Z:T}=E,O=E.is0();S==null&&(S=O?X3:r.inv(T));const A=a(_*S),R=a(w*S),M=r.mul(T,S);if(O)return{x:Vr,y:Bt};if(M!==Bt)throw new Error("invZ was invalid");return{x:A,y:R}}),y=qo(E=>{const{a:S,d:_}=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),C=a(v*v),q=a(R*S),K=a(v*a(q+M)),H=a(C+a(_*a(R*M)));if(K!==H)throw new Error("bad point: equation left != right (1)");const D=a(w*T),P=a(O*A);if(D!==P)throw new Error("bad point: equation left != right (2)");return!0});class g{constructor(S,_,w,T){this.X=f("x",S),this.Y=f("y",_),this.Z=f("z",w,!0),this.T=f("t",T),Object.freeze(this)}static CURVE(){return s}static fromAffine(S){if(S instanceof g)throw new Error("extended point not allowed");const{x:_,y:w}=S||{};return f("x",_),f("y",w),new g(_,w,Bt,a(_*w))}static fromBytes(S,_=!1){const w=r.BYTES,{a:T,d:O}=s;S=a0(As(S,w,"point")),Fo(_,"zip215");const A=a0(S),R=S[w-1];A[w-1]=R&-129;const M=Mo(A),v=_?c:r.ORDER;u0("point.y",M,Vr,v);const C=a(M*M),q=a(C-Bt),K=a(O*C-T);let{isValid:H,value:D}=u(q,K);if(!H)throw new Error("bad point: invalid y coordinate");const P=(D&Bt)===Bt,$=(R&128)!==0;if(!_&&D===Vr&&$)throw new Error("bad point: x=0 and x_0=1");return $!==P&&(D=a(-D)),g.fromAffine({x:D,y:M})}static fromHex(S,_=!1){return g.fromBytes(on("point",S),_)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(S=8,_=!0){return m.createCache(this,S),_||this.multiply(lf),this}assertValidity(){y(this)}equals(S){l(S);const{X:_,Y:w,Z:T}=this,{X:O,Y:A,Z:R}=S,M=a(_*R),v=a(O*T),C=a(w*R),q=a(A*T);return M===v&&C===q}is0(){return this.equals(g.ZERO)}negate(){return new g(a(-this.X),this.Y,this.Z,a(-this.T))}double(){const{a:S}=s,{X:_,Y:w,Z:T}=this,O=a(_*_),A=a(w*w),R=a(lf*a(T*T)),M=a(S*O),v=_+w,C=a(a(v*v)-O-A),q=M+A,K=q-R,H=M-A,D=a(C*K),P=a(q*H),$=a(C*H),F=a(K*q);return new g(D,P,F,$)}add(S){l(S);const{a:_,d:w}=s,{X:T,Y:O,Z:A,T:R}=this,{X:M,Y:v,Z:C,T:q}=S,K=a(T*M),H=a(O*v),D=a(R*w*q),P=a(A*C),$=a((T+O)*(M+v)-K-H),F=P-D,x=P+D,B=a(H-_*K),L=a($*F),N=a(x*B),V=a($*B),G=a(F*x);return new g(L,N,G,V)}subtract(S){return this.add(S.negate())}multiply(S){if(!i.isValidNot0(S))throw new Error("invalid scalar: expected 1 <= sc < curve.n");const{p:_,f:w}=m.cached(this,S,T=>Sr(g,T));return Sr(g,[_,w])[0]}multiplyUnsafe(S,_=g.ZERO){if(!i.isValid(S))throw new Error("invalid scalar: expected 0 <= sc < curve.n");return S===Vr?g.ZERO:this.is0()||S===Bt?this:m.unsafe(this,S,w=>Sr(g,w),_)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}isTorsionFree(){return m.unsafe(this,s.n).is0()}toAffine(S){return d(this,S)}clearCofactor(){return o===Bt?this:this.multiplyUnsafe(o)}toBytes(){const{x:S,y:_}=this.toAffine(),w=r.toBytes(_);return w[w.length-1]|=S&Bt?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(S){return Sr(g,S)}static msm(S,_){return Nw(g,i,S,_)}_setWindowSize(S){this.precompute(S)}toRawBytes(){return this.toBytes()}}g.BASE=new g(s.Gx,s.Gy,Bt,a(s.Gx*s.Gy)),g.ZERO=new g(Vr,Bt,Bt,Vr),g.Fp=r,g.Fn=i;const m=new Bw(g,i.BITS);return g.BASE.precompute(8),g}function Z3(e,t,n={}){if(typeof t!="function")throw new Error('"hash" function param is required');gc(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||sg,a=n.adjustScalarBytes||(v=>v),u=n.domain||((v,C,q)=>{if(Fo(q,"phflag"),C.length||q)throw new Error("Contexts/pre-hash are not supported");return v});function f(v){return o.create(Mo(v))}function l(v){const C=w.secretKey;v=on("private key",v,C);const q=on("hashed private key",t(v),2*C),K=a(q.slice(0,C)),H=q.slice(C,2*C),D=f(K);return{head:K,prefix:H,scalar:D}}function d(v){const{head:C,prefix:q,scalar:K}=l(v),H=i.multiply(K),D=H.toBytes();return{head:C,prefix:q,scalar:K,point:H,pointBytes:D}}function y(v){return d(v).pointBytes}function g(v=Uint8Array.of(),...C){const q=$e(...C);return f(t(u(q,on("context",v),!!r)))}function m(v,C,q={}){v=on("message",v),r&&(v=r(v));const{prefix:K,scalar:H,pointBytes:D}=d(C),P=g(q.context,K,v),$=i.multiply(P).toBytes(),F=g(q.context,$,D,v),x=o.create(P+F*H);if(!o.isValid(x))throw new Error("sign failed: invalid s");const B=$e($,o.toBytes(x));return As(B,w.signature,"result")}const E={zip215:!0};function S(v,C,q,K=E){const{context:H,zip215:D}=K,P=w.signature;v=on("signature",v,P),C=on("message",C),q=on("publicKey",q,w.publicKey),D!==void 0&&Fo(D,"zip215"),r&&(C=r(C));const $=P/2,F=v.subarray(0,$),x=Mo(v.subarray($,P));let B,L,N;try{B=e.fromBytes(q,D),L=e.fromBytes(F,D),N=i.multiplyUnsafe(x)}catch{return!1}if(!D&&B.isSmallOrder())return!1;const V=g(H,L.toBytes(),B.toBytes(),C);return L.add(B.multiplyUnsafe(V)).subtract(N).clearCofactor().is0()}const _=s.BYTES,w={secretKey:_,publicKey:_,signature:2*_,seed:_};function T(v=c(w.seed)){return As(v,w.seed,"seed")}function O(v){const C=M.randomSecretKey(v);return{secretKey:C,publicKey:y(C)}}function A(v){return rc(v)&&v.length===o.BYTES}function R(v,C){try{return!!e.fromBytes(v,C)}catch{return!1}}const M={getExtendedPublicKey:d,randomSecretKey:T,isValidSecretKey:A,isValidPublicKey:R,toMontgomery(v){const{y:C}=e.fromBytes(v),q=w.publicKey,K=q===32;if(!K&&q!==57)throw new Error("only defined for 25519 and 448");const H=K?s.div(Bt+C,Bt-C):s.div(C-Bt,C+Bt);return s.toBytes(H)},toMontgomerySecret(v){const C=w.secretKey;As(v,C);const q=t(v.subarray(0,C));return a(q).subarray(0,C)},randomPrivateKey:T,precompute(v=8,C=e.BASE){return C.precompute(v,!1)}};return Object.freeze({keygen:O,getPublicKey:y,sign:m,verify:S,utils:M,Point:e,lengths:w})}function J3(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=pi(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 Q3(e,t){const n=t.Point;return Object.assign({},t,{ExtendedPoint:n,CURVE:e,nBitLength:n.Fn.BITS,nByteLength:n.Fn.BYTES})}function e8(e){const{CURVE:t,curveOpts:n,hash:r,eddsaOpts:i}=J3(e),s=Y3(t,n),o=Z3(s,r,i);return Q3(e,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const t8=BigInt(1),I0=BigInt(2);BigInt(3);const n8=BigInt(5),r8=BigInt(8),wh=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Mw={p:wh,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:r8,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function i8(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,t8,s)*e%s,f=Zn(u,n8,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 s8(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}const O0=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");function o8(e,t){const n=wh,r=mt(t*t*t,n),i=mt(r*r*t,n),s=i8(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),Kx(o,n)&&(o=mt(-o,n)),{isValid:f||l,value:o}}const c8=pi(Mw.p,{isLE:!0}),a8={...Mw,Fp:c8,hash:oE,adjustScalarBytes:s8,uvRatio:o8},u8=e8(a8);var B0,N0,Rt,Os;class f8{constructor(t={}){sn(this,Rt);sn(this,Os);this[B0]=this.entries.bind(this),this[N0]="ExpirableMap";const{source:n=[],expirationTime:r=600*1e3}=t,i=Date.now();Yt(this,Rt,new Map([...n].map(([s,o])=>[s,{value:o,timestamp:i}]))),Yt(this,Os,r)}prune(){const t=Date.now();for(const[n,r]of Me(this,Rt).entries())t-r.timestamp>Me(this,Os)&&Me(this,Rt).delete(n);return this}set(t,n){this.prune();const r={value:n,timestamp:Date.now()};return Me(this,Rt).set(t,r),this}get(t){const n=Me(this,Rt).get(t);if(n!==void 0){if(Date.now()-n.timestamp>Me(this,Os)){Me(this,Rt).delete(t);return}return n.value}}clear(){Me(this,Rt).clear()}entries(){const t=Me(this,Rt).entries();return function*(){for(const[r,i]of t)yield[r,i.value]}()}values(){const t=Me(this,Rt).values();return function*(){for(const r of t)yield r.value}()}keys(){return Me(this,Rt).keys()}forEach(t,n){for(const[r,i]of Me(this,Rt).entries())t.call(n,i.value,r,this)}has(t){return Me(this,Rt).has(t)}delete(t){return Me(this,Rt).delete(t)}get size(){return Me(this,Rt).size}}Rt=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 tt.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 tt.fromCode(new hu("Length too long (> 4 bytes)"))},al=(e,t)=>{if(e[t]<128)return 1;if(e[t]===128)throw tt.fromCode(new kr("Invalid length 0"));if(e[t]===129)return 2;if(e[t]===130)return 3;if(e[t]===131)return 4;throw tt.fromCode(new kr("Length too long (> 4 bytes)"))},l8=(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 tt.fromCode(new kr("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 h8(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 d8=(e,t)=>{let n=0;const r=(c,a)=>{if(i[n++]!==c)throw tt.fromCode(new kr(`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 tt.fromCode(new kr("Not the expected OID."));n+=t.byteLength,r(3,"bit string");const s=l8(i,n)-1;n+=al(i,n),r(0,"0 padding");const o=i.slice(n);if(s!==o.length)throw tt.fromCode(new zl(s,o.length));return o};var Ko,Go;const ki=class ki{constructor(t){sn(this,Ko);sn(this,Go);if(t.byteLength!==ki.RAW_KEY_LENGTH)throw tt.fromCode(new kr("An Ed25519 public key must be exactly 32 bytes long"));Yt(this,Ko,t),Yt(this,Go,ki.derEncode(t))}static from(t){return this.fromDer(t.toDer())}static fromRaw(t){return new ki(t)}static fromDer(t){return new ki(this.derDecode(t))}static derEncode(t){return h8(t,R0)}static derDecode(t){const n=d8(t,R0);if(n.length!==this.RAW_KEY_LENGTH)throw tt.fromCode(new kr("An Ed25519 public key must be exactly 32 bytes long"));return n}get rawKey(){return Me(this,Ko)}get derKey(){return Me(this,Go)}toDer(){return this.derKey}toRaw(){return this.rawKey}};Ko=new WeakMap,Go=new WeakMap,ki.RAW_KEY_LENGTH=32;let ul=ki;class p8{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 y8 extends p8{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 C0=.5,U0=1.5,H0=500,F0=6e4,M0=9e5,L0=10;var Fn,Wo,Xo,zo,Yo,Zo,Jo,Qo,Bs;const Va=class Va{constructor(t=Va.default){sn(this,Fn);sn(this,Wo);sn(this,Xo);sn(this,zo);sn(this,Yo);sn(this,Zo);sn(this,Jo);sn(this,Qo);sn(this,Bs,0);const{initialInterval:n=H0,randomizationFactor:r=C0,multiplier:i=U0,maxInterval:s=F0,maxElapsedTime:o=M0,maxIterations:c=L0,date:a=Date}=t;Yt(this,Fn,n),Yt(this,Wo,r),Yt(this,Xo,i),Yt(this,zo,s),Yt(this,Qo,a),Yt(this,Yo,a.now()),Yt(this,Zo,o),Yt(this,Jo,c)}get ellapsedTimeInMsec(){return Me(this,Qo).now()-Me(this,Yo)}get currentInterval(){return Me(this,Fn)}get count(){return Me(this,Bs)}get randomValueFromInterval(){const t=Me(this,Wo)*Me(this,Fn),n=Me(this,Fn)-t,r=Me(this,Fn)+t;return Math.random()*(r-n)+n}incrementCurrentInterval(){return Yt(this,Fn,Math.min(Me(this,Fn)*Me(this,Xo),Me(this,zo))),Mh(this,Bs)._++,Me(this,Fn)}next(){return this.ellapsedTimeInMsec>=Me(this,Zo)||Me(this,Bs)>=Me(this,Jo)?null:(this.incrementCurrentInterval(),this.randomValueFromInterval)}};Fn=new WeakMap,Wo=new WeakMap,Xo=new WeakMap,zo=new WeakMap,Yo=new WeakMap,Zo=new WeakMap,Jo=new WeakMap,Qo=new WeakMap,Bs=new WeakMap,Va.default={initialInterval:H0,randomizationFactor:C0,multiplier:U0,maxInterval:F0,maxElapsedTime:M0,maxIterations:L0,date:Date};let fl=Va;var wr;(function(e){e.Received="received",e.Processing="processing",e.Replied="replied",e.Rejected="rejected",e.Unknown="unknown",e.Done="done"})(wr||(wr={}));const ll=60*1e3,g8=1e6,m8=0,w8="308182301d060d2b0601040182dc7c0503010201060c2b0601040182dc7c05030201036100814c0e6ec71fab583b08bd81373c255c3c371b2e84863c98a4f1e08b74235d14fb5d9c0cd546d9685f913a0c0b2cc5341583bf4b4392e467db96d65b9bb4cb717112f8472e0d5a4d14505ffd7484b01291091c5f87b98883463f98091a0baaae",b8="ic0.app",E8=".ic0.app",_8="icp0.io",S8=".icp0.io",T8="icp-api.io",x8=".icp-api.io",hf=200,A8=202,v8=404;function I8(){let e;if(typeof window<"u")if(window.fetch)e=window.fetch.bind(window);else throw an.fromCode(new To("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 an.fromCode(new To("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 an.fromCode(new To("Fetch implementation was not available. Please provide fetch to the HttpAgent constructor, or ensure it is available in the window or global context."))}function O8(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 xr{#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=m8,this.#g=!1,this.#a=null,this.#w=!1,this._isAgent=!0,this.config={},this.log=new y8,this.#f=[],this.#l=[],this.#h=new f8({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=Ge.fromUint8Array(l).toText();let y;if(o===Cs.Replied){const{reply:_}=i;y=Na({status:o,reply:_,timestamp:BigInt(f),request_id:a})}else if(o===Cs.Rejected){const{reject_code:_,reject_message:w,error_code:T}=i;y=Na({status:o,reject_code:_,reject_message:w,error_code:T,timestamp:BigInt(f),request_id:a})}else throw un.fromCode(new qn(`Unknown status: ${o}`));const g=$e(ox,y),m=s.nodeKeys.get(d);if(!m)throw yt.fromCode(new oh);const E=ul.fromDer(m).rawKey;if(u8.verify(u.signature,g,E))return i;throw An.fromCode(new ch(d))}return i},this.config=t,this.#s=t.fetch||I8()||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=ic(w8);const n=O8(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(E8)?this.host.hostname=b8:this.host.hostname.endsWith(S8)?this.host.hostname=_8:this.host.hostname.endsWith(x8)&&(this.host.hostname=T8),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 tt.fromCode(new ps("The maximum ingress expiry time is 5 minutes.",t.ingressExpiryInMinutes));if(t.ingressExpiryInMinutes&&t.ingressExpiryInMinutes<=0)throw tt.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=xr.createSync(t);return await n.#y(),n}static async from(t){try{return"config"in t?await xr.create(t.config):await xr.create({fetch:t._fetch,fetchOptions:t._fetchOptions,callOptions:t._callOptions,host:t._host.toString(),identity:t._identity??void 0})}catch{throw tt.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 an.fromCode(new Ni);return(await this.#n).getPrincipal()}async call(t,n,r){const i=n.callSync??!0,s=await(r??this.#n);if(!s)throw an.fromCode(new Ni);const o=Ge.from(t),c=n.effectiveCanisterId?Ge.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:Ri.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(S){return Object.assign(S,{__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?tr(T):null;return{requestId:E,response:{...O,body:A},requestDetails:f}}catch(S){let _;if(S instanceof br){if(S.hasCode(Aa))return this.log.warn("v3 api not supported. Fall back to v2"),this.call(t,{...n,callSync:!1},r);if(S.hasCode(ps)&&!this.#g)return await this.syncTime(o),this.call(o,n,r);S.code.requestContext={requestId:E,senderPubKey:l.body.sender_pubkey,senderSignature:l.body.sender_sig,ingressExpiry:l.body.content.ingress_expiry},_=S}else _=un.fromCode(new qn(S));throw this.log.error(`Error while making call: ${_.message}`,_),_}}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 un.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={...tr(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 br?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(g8));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===A8)return{ok:o.ok,status:o.status,statusText:o.statusText,responseBodyBytes:c,headers:a};const u=await o.text();if(o.status===v8&&o.url.includes("api/v3"))throw yt.fromCode(new Aa);if(u.startsWith("Invalid request expiry: "))throw tt.fromCode(new ds(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?Ge.from(n.effectiveCanisterId):Ge.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 cn.fromCode(new Ni);const a=Ge.from(t),u=c.getPrincipal(),f=df(this.#o,this.#i),l={request_type:Ho.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:Ri.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 S=await this.#E(g);return{requestDetails:l,...S}},E=async()=>{const S=this.#h.get(s.toString());if(S)return S;await this.fetchSubnetKeys(s.toString());const _=this.#h.get(s.toString());if(!_)throw An.fromCode(new sh);return _};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.#_(S,w)}}catch(S){let _;throw S instanceof br?(S.code.requestContext={requestId:d,senderPubKey:o.body.sender_pubkey,senderSignature:o.body.sender_sig,ingressExpiry:o.body.content.ingress_expiry},_=S):_=an.fromCode(new qn(S)),this.log.error(`Error while making query: ${_.message}`,_),_}}#_;async createReadStateRequest(t,n){await this.#y();const r=await(n??this.#n);if(!r)throw cn.fromCode(new Ni);const i=r.getPrincipal(),s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#r?{Authorization:"Basic "+btoa(this.#r)}:{}}},endpoint:Ri.ReadState,body:{request_type:Ho.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=Ge.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 cn.fromCode(new Ni);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=tr(f);return this.log.print("Read state response:",l),l}catch(f){let l;throw f instanceof br?(f.code.requestContext={requestId:a,senderPubKey:c.body.sender_pubkey,senderSignature:c.body.sender_sig,ingressExpiry:c.body.content.ingress_expiry},l=f):l=an.fromCode(new qn(f)),this.log.error(`Error while making read state: ${l.message}`,l),l}}parseTimeFromResponse(t){let n;if(t.certificate){const r=tr(t.certificate);if(r&&"tree"in r)n=r.tree;else throw yt.fromCode(new pc("Could not decode time from response"));const i=wc(["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??Ge.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),i=xr.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 br?r:an.fromCode(new qn(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 tr(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 cn.fromCode(new js(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=Ge.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===Ri.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 Ts.fromDeltaInMilliseconds(n,t)}const B8=300*1e3;function Lw(){return C8(k8(N8(),1e3),R8(1e3,1.2),P8(B8))}function N8(){let e=!0;return async()=>e?(e=!1,!0):!1}function k8(e,t){return async(n,r,i)=>{if(await e(n,r,i))return new Promise(s=>setTimeout(s,t))}}function P8(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 R8(e,t){let n=e;return()=>new Promise(r=>setTimeout(()=>{n*=t,r()},n))}function C8(...e){return async(t,n,r)=>{for(const i of e)await i(t,n,r)}}const U8={strategy:Lw(),preSignReadStateRequest:!1};function qw(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function pf(e,t){return e!==null&&typeof e=="object"&&qw(e,t)}function H8(e,t){return qw(e,t)&&typeof e[t]=="function"}function q0(e){return pf(e,"body")&&pf(e.body,"content")&&e.body.content.request_type===Ho.ReadState&&pf(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&H8(e.body.content.ingress_expiry,"toHash")}async function Vw(e,t,n,r={}){const i=[dt("request_status"),n];let s,o;if(r.preSignReadStateRequest??!1?(o=await F8({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 cn.fromCode(new js);const a=await Li.create({certificate:s.certificate,rootKey:e.rootKey,canisterId:t,blsVerify:r.blsVerify,agent:e}),u=En(a.lookup_path([...i,dt("status")]));let f;switch(typeof u>"u"?f=wr.Unknown:f=new TextDecoder().decode(u),f){case wr.Replied:return{reply:En(a.lookup_path([...i,"reply"])),certificate:a};case wr.Received:case wr.Unknown:case wr.Processing:return await(r.strategy??Lw())(t,n,f),Vw(e,t,n,{...r,request:o});case wr.Rejected:{const l=new Uint8Array(En(a.lookup_path([...i,"reject_code"])))[0],d=new TextDecoder().decode(En(a.lookup_path([...i,"reject_message"]))),y=En(a.lookup_path([...i,"error_code"])),g=y?new TextDecoder().decode(y):void 0;throw bs.fromCode(new du(n,l,d,g))}case wr.Done:throw an.fromCode(new th(n))}throw _s}async function F8(e){const{paths:t,agent:n,pollingOptions:r}=e;if(r.request&&q0(r.request))return r.request;const i=await n.createReadStateRequest?.({paths:t},void 0);if(!q0(i))throw tt.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 Ge.from(t[xn].config.canisterId)}static createActorClass(t,n){const r=t({IDL:vS});class i extends Ha{constructor(o){if(!o.canisterId)throw tt.fromCode(new Ia(o.canisterId));const c=typeof o.canisterId=="string"?Ge.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($w),this[a]=M8(this,a,u,o.blsVerify)}}return i}static createActor(t,n){if(!n.canisterId)throw tt.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 ss(e,t){const n=sm(e,t);switch(n.length){case 0:return;case 1:return n[0];default:return n}}const Dw={pollingOptions:U8},hl="http-details",$w="certificate";function M8(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 xr,u=Ge.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 Rs.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},bs.fromCode(y)}case Rs.Replied:return n.annotations.includes(hl)?{httpDetails:d,result:ss(n.retTypes,l.reply.arg)}:ss(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||xr.createSync(),{canisterId:u,effectiveCanisterId:f,pollingOptions:l}={...Dw,...e[xn].config,...o},d=Ge.from(u),y=f!==void 0?Ge.from(f):d,g=Xf(n.argTypes,c),{requestId:m,response:E,requestDetails:S}=await a.call(d,{methodName:t,arg:g,effectiveCanisterId:y,nonce:o.nonce});let _,w;if(sx(E.body)){if(a.rootKey==null)throw cn.fromCode(new js);const R=E.body.certificate;w=await Li.create({certificate:R,rootKey:a.rootKey,canisterId:y,blsVerify:r,agent:a});const M=[dt("request_status"),m];switch(new TextDecoder().decode(En(w.lookup_path([...M,"status"])))){case"replied":_=En(w.lookup_path([...M,"reply"]));break;case"rejected":{const C=new Uint8Array(En(w.lookup_path([...M,"reject_code"])))[0],q=new TextDecoder().decode(En(w.lookup_path([...M,"reject_message"]))),K=En(w.lookup_path([...M,"error_code"])),H=K?new TextDecoder().decode(K):void 0,D=new du(m,C,q,H);throw D.callContext={canisterId:d,methodName:t,httpDetails:E},bs.fromCode(D)}}}else if(ix(E.body)){const{reject_code:R,reject_message:M,error_code:v}=E.body,C=new eh(m,R,M,v);throw C.callContext={canisterId:d,methodName:t,httpDetails:E},bs.fromCode(C)}if(E.status===202){const R={...l,blsVerify:r},M=await Vw(a,y,m,R);w=M.certificate,_=M.reply}const T=n.annotations.includes(hl),O=n.annotations.includes($w),A={...E,requestDetails:S};if(_!==void 0)return T&&O?{httpDetails:A,certificate:w,result:ss(n.retTypes,_)}:O?{certificate:w,result:ss(n.retTypes,_)}:T?{httpDetails:A,result:ss(n.retTypes,_)}:ss(n.retTypes,_);{const R=new qn(`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},an.fromCode(R)}};const s=(...o)=>i({},...o);return s.withOptions=o=>(...c)=>i(o,...c),s}var bi={},ze={},yf={},Zt={},ur={},V0;function Wn(){return V0||(V0=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.testnet=ur.regtest=ur.bitcoin=void 0,ur.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===A8)return{ok:o.ok,status:o.status,statusText:o.statusText,responseBodyBytes:c,headers:a};const u=await o.text();if(o.status===v8&&o.url.includes("api/v3"))throw yt.fromCode(new Aa);if(u.startsWith("Invalid request expiry: "))throw tt.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?Ge.from(n.effectiveCanisterId):Ge.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 an.fromCode(new Ni);const a=Ge.from(t),u=c.getPrincipal(),f=df(this.#o,this.#i),l={request_type:Ho.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:Ri.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 S=await this.#E(g);return{requestDetails:l,...S}},E=async()=>{const S=this.#h.get(s.toString());if(S)return S;await this.fetchSubnetKeys(s.toString());const _=this.#h.get(s.toString());if(!_)throw An.fromCode(new sh);return _};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.#_(S,w)}}catch(S){let _;throw S instanceof br?(S.code.requestContext={requestId:d,senderPubKey:o.body.sender_pubkey,senderSignature:o.body.sender_sig,ingressExpiry:o.body.content.ingress_expiry},_=S):_=un.fromCode(new qn(S)),this.log.error(`Error while making query: ${_.message}`,_),_}}#_;async createReadStateRequest(t,n){await this.#y();const r=await(n??this.#n);if(!r)throw an.fromCode(new Ni);const i=r.getPrincipal(),s=await this._transform({request:{method:"POST",headers:{"Content-Type":"application/cbor",...this.#r?{Authorization:"Basic "+btoa(this.#r)}:{}}},endpoint:Ri.ReadState,body:{request_type:Ho.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=Ge.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 an.fromCode(new Ni);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=tr(f);return this.log.print("Read state response:",l),l}catch(f){let l;throw f instanceof br?(f.code.requestContext={requestId:a,senderPubKey:c.body.sender_pubkey,senderSignature:c.body.sender_sig,ingressExpiry:c.body.content.ingress_expiry},l=f):l=un.fromCode(new qn(f)),this.log.error(`Error while making read state: ${l.message}`,l),l}}parseTimeFromResponse(t){let n;if(t.certificate){const r=tr(t.certificate);if(r&&"tree"in r)n=r.tree;else throw yt.fromCode(new pc("Could not decode time from response"));const i=wc(["time"],n);if(i.status!==vn.Found)throw yt.fromCode(new Us("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??Ge.from("ryjl3-tyaaa-aaaaa-aaaba-cai"),i=xr.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 br?r:un.fromCode(new qn(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 tr(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 an.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=Ge.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===Ri.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 B8=300*1e3;function Lw(){return C8(k8(N8(),1e3),R8(1e3,1.2),P8(B8))}function N8(){let e=!0;return async()=>e?(e=!1,!0):!1}function k8(e,t){return async(n,r,i)=>{if(await e(n,r,i))return new Promise(s=>setTimeout(s,t))}}function P8(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 R8(e,t){let n=e;return()=>new Promise(r=>setTimeout(()=>{n*=t,r()},n))}function C8(...e){return async(t,n,r)=>{for(const i of e)await i(t,n,r)}}const U8={strategy:Lw(),preSignReadStateRequest:!1};function qw(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function pf(e,t){return e!==null&&typeof e=="object"&&qw(e,t)}function H8(e,t){return qw(e,t)&&typeof e[t]=="function"}function q0(e){return pf(e,"body")&&pf(e.body,"content")&&e.body.content.request_type===Ho.ReadState&&pf(e.body.content,"ingress_expiry")&&typeof e.body.content.ingress_expiry=="object"&&e.body.content.ingress_expiry!==null&&H8(e.body.content.ingress_expiry,"toHash")}async function Vw(e,t,n,r={}){const i=[dt("request_status"),n];let s,o;if(r.preSignReadStateRequest??!1?(o=await F8({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 an.fromCode(new Ks);const a=await Li.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=wr.Unknown:f=new TextDecoder().decode(u),f){case wr.Replied:return{reply:_n(a.lookup_path([...i,"reply"])),certificate:a};case wr.Received:case wr.Unknown:case wr.Processing:return await(r.strategy??Lw())(t,n,f),Vw(e,t,n,{...r,request:o});case wr.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 wr.Done:throw un.fromCode(new th(n))}throw Ss}async function F8(e){const{paths:t,agent:n,pollingOptions:r}=e;if(r.request&&q0(r.request))return r.request;const i=await n.createReadStateRequest?.({paths:t},void 0);if(!q0(i))throw tt.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 Ge.from(t[xn].config.canisterId)}static createActorClass(t,n){const r=t({IDL:vS});class i extends Ha{constructor(o){if(!o.canisterId)throw tt.fromCode(new Ia(o.canisterId));const c=typeof o.canisterId=="string"?Ge.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($w),this[a]=M8(this,a,u,o.blsVerify)}}return i}static createActor(t,n){if(!n.canisterId)throw tt.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 ss(e,t){const n=sm(e,t);switch(n.length){case 0:return;case 1:return n[0];default:return n}}const Dw={pollingOptions:U8},hl="http-details",$w="certificate";function M8(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 xr,u=Ge.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 Cs.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 Cs.Replied:return n.annotations.includes(hl)?{httpDetails:d,result:ss(n.retTypes,l.reply.arg)}:ss(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||xr.createSync(),{canisterId:u,effectiveCanisterId:f,pollingOptions:l}={...Dw,...e[xn].config,...o},d=Ge.from(u),y=f!==void 0?Ge.from(f):d,g=Xf(n.argTypes,c),{requestId:m,response:E,requestDetails:S}=await a.call(d,{methodName:t,arg:g,effectiveCanisterId:y,nonce:o.nonce});let _,w;if(sx(E.body)){if(a.rootKey==null)throw an.fromCode(new Ks);const R=E.body.certificate;w=await Li.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":_=_n(w.lookup_path([...M,"reply"]));break;case"rejected":{const C=new Uint8Array(_n(w.lookup_path([...M,"reject_code"])))[0],q=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,D=new du(m,C,q,H);throw D.callContext={canisterId:d,methodName:t,httpDetails:E},Es.fromCode(D)}}}else if(ix(E.body)){const{reject_code:R,reject_message:M,error_code:v}=E.body,C=new eh(m,R,M,v);throw C.callContext={canisterId:d,methodName:t,httpDetails:E},Es.fromCode(C)}if(E.status===202){const R={...l,blsVerify:r},M=await Vw(a,y,m,R);w=M.certificate,_=M.reply}const T=n.annotations.includes(hl),O=n.annotations.includes($w),A={...E,requestDetails:S};if(_!==void 0)return T&&O?{httpDetails:A,certificate:w,result:ss(n.retTypes,_)}:O?{certificate:w,result:ss(n.retTypes,_)}:T?{httpDetails:A,result:ss(n.retTypes,_)}:ss(n.retTypes,_);{const R=new qn(`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},un.fromCode(R)}};const s=(...o)=>i({},...o);return s.withOptions=o=>(...c)=>i(o,...c),s}const mn={P2PKH:{P2PKH:null},P2SH_P2WPKH:{P2SH_P2WPKH:null},P2WPKH:{P2WPKH:null},P2WSH:{P2WSH:null},P2SH:{P2SH:null},P2TR:{P2TR:null},UNKNOWN:{UNKNOWN:null}};var bi={},ze={},yf={},Zt={},ur={},V0;function Wn(){return V0||(V0=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.testnet=ur.regtest=ur.bitcoin=void 0,ur.bitcoin={messagePrefix:`Bitcoin Signed Message:
71
71
  `,bech32:"bc",bip32:{public:76067358,private:76066276},pubKeyHash:0,scriptHash:5,wif:128},ur.regtest={messagePrefix:`Bitcoin Signed Message:
72
72
  `,bech32:"bcrt",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239},ur.testnet={messagePrefix:`Bitcoin Signed Message:
73
- `,bech32:"tb",bip32:{public:70617039,private:70615956},pubKeyHash:111,scriptHash:196,wif:239}),ur}var gf={},io={},mf={},fr={},D0;function jw(){if(D0)return fr;D0=1,Object.defineProperty(fr,"__esModule",{value:!0}),fr.encode=fr.decode=fr.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))}fr.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)}}fr.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 fr.encode=n,fr}var Ei={},$0;function bh(){if($0)return Ei;$0=1,Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.REVERSE_OPS=Ei.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};Ei.OPS=e;const t={};Ei.REVERSE_OPS=t;for(const n of Object.keys(e)){const r=e[n];t[r]=n}return Ei}var lr={},j0;function L8(){if(j0)return lr;j0=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.decode=lr.encode=lr.encodingLength=void 0;const e=bh();function t(i){return i<e.OPS.OP_PUSHDATA1?1:i<=255?2:i<=65535?3:5}lr.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}lr.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 lr.decode=r,lr}var _i={},K0;function q8(){if(K0)return _i;K0=1,Object.defineProperty(_i,"__esModule",{value:!0}),_i.encode=_i.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}_i.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 _i.encode=n,_i}var Si={},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 Kw(){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 S='" of type ';return y==="key"&&(S='" with key type '),o('property "'+s(g)+S+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 V8(){if(X0)return _f;X0=1;var e=Eh(),t=Kw();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(C){if(!A(C))return!1;if(C.length===R)return!0;throw t.tfCustomError(M+"(Length: "+R+")",M+"(Length: "+C.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(C,q){return M(C,q)&&C>A&&C<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 S(A){return(A&65535)===A}function _(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:S,UInt32:_,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 D8(){if(z0)return Sf;z0=1;var e=Kw(),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,S){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(_,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,S){if(!t.Object(E)||t.Nil(E))return!1;for(var _ in E){try{g&&u(g,_,S)}catch(T){throw s(T,_,"key")}try{var w=E[_];u(y,w,S)}catch(T){throw s(T,_)}}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(S)||t.Nil(S))return!1;var w;try{for(w in g){var T=g[w],O=S[w];u(T,O,_)}}catch(A){throw s(A,w)}if(_){for(w in S)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(S){try{return u(S,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(S){try{return u(S,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(S,m[_],E)}catch(w){throw s(w,_)}})}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=V8();for(f in l)u[f]=l[f];return u.compile=a,u.TfTypeError=r,u.TfPropertyTypeError=i,Sf=u,Sf}var Y0;function zt(){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=ec();e.typeforce=D8();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 $8(){if(Z0)return Si;Z0=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.encode=Si.decode=void 0;const e=jw(),t=nn(),n=zt(),{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}}Si.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 Si.encode=a,Si}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=jw(),n=bh();Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return n.OPS}});const r=L8(),i=q8(),s=$8(),o=zt(),{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 S(v){if(g(v))return v;c(o.Array,v);const C=v.reduce((H,D)=>E(D)?D.length===1&&y(D)!==void 0?H+1:H+r.encodingLength(D.length)+D.length:H+1,0),q=Buffer.allocUnsafe(C);let K=0;if(v.forEach(H=>{if(E(H)){const D=y(H);if(D!==void 0){q.writeUInt8(D,K),K+=1;return}K+=r.encode(q,H.length,K),H.copy(q,K),K+=H.length}else q.writeUInt8(H,K),K+=1}),K!==q.length)throw new Error("Could not decode chunks");return q}e.compile=S;function _(v){if(m(v))return v;c(o.Buffer,v);const C=[];let q=0;for(;q<v.length;){const K=v[q];if(K>n.OPS.OP_0&&K<=n.OPS.OP_PUSHDATA4){const H=r.decode(v,q);if(H===null||(q+=H.size,q+H.number>v.length))return null;const D=v.slice(q,q+H.number);q+=H.number;const P=y(D);P!==void 0?C.push(P):C.push(D)}else C.push(K),q+=1}return C}e.decompile=_;function w(v){if(g(v)&&(v=_(v)),!v)throw new Error("Could not convert invalid chunks to ASM");return v.map(C=>{if(E(C)){const q=y(C);if(q===void 0)return C.toString("hex");C=q}return n.REVERSE_OPS[C]}).join(" ")}e.toASM=w;function T(v){return c(o.String,v),S(v.split(" ").map(C=>n.OPS[C]!==void 0?n.OPS[C]:(c(o.Hex,C),Buffer.from(C,"hex"))))}e.fromASM=T;function O(v){return v=_(v),c(l,v),v.map(C=>E(C)?C:C===n.OPS.OP_0?Buffer.allocUnsafe(0):i.encode(C-a))}e.toStack=O;function A(v){return o.isPoint(v)}e.isCanonicalPubKey=A;function R(v){const C=v&-129;return C>0&&C<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 Ti={},Q0;function yi(){if(Q0)return Ti;Q0=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.value=Ti.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})}})}Ti.prop=e;function t(n){let r;return()=>(r!==void 0||(r=n()),r)}return Ti.value=t,Ti}var ep;function j8(){if(ep)return io;ep=1,Object.defineProperty(io,"__esModule",{value:!0}),io.p2data=void 0;const e=Wn(),t=nn(),n=zt(),r=yi(),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 io.p2data=s,io}var so={},tp;function K8(){if(tp)return so;tp=1,Object.defineProperty(so,"__esModule",{value:!0}),so.p2ms=void 0;const e=Wn(),t=nn(),n=zt(),r=yi(),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 so.p2ms=o,so}var oo={},np;function G8(){if(np)return oo;np=1,Object.defineProperty(oo,"__esModule",{value:!0}),oo.p2pk=void 0;const e=Wn(),t=nn(),n=zt(),r=yi(),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 oo.p2pk=s,oo}var co={},Tf={},xi={},Jt={},rp;function Gw(){if(rp)return Jt;rp=1,Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.ripemd160=Jt.RIPEMD160=Jt.md5=Jt.MD5=Jt.sha1=Jt.SHA1=void 0;const e=ky(),t=ai(),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:C,C:q,D:K,E:H}=this;return[v,C,q,K,H]}set(v,C,q,K,H){this.A=v|0,this.B=C|0,this.C=q|0,this.D=K|0,this.E=H|0}process(v,C){for(let $=0;$<16;$++,C+=4)r[$]=v.getUint32(C,!1);for(let $=16;$<80;$++)r[$]=(0,t.rotl)(r[$-3]^r[$-8]^r[$-14]^r[$-16],1);let{A:q,B:K,C:H,D,E:P}=this;for(let $=0;$<80;$++){let F,x;$<20?(F=(0,e.Chi)(K,H,D),x=1518500249):$<40?(F=K^H^D,x=1859775393):$<60?(F=(0,e.Maj)(K,H,D),x=2400959708):(F=K^H^D,x=3395469782);const B=(0,t.rotl)(q,5)+F+P+x+r[$]|0;P=D,D=H,H=(0,t.rotl)(K,30),K=q,q=B}q=q+this.A|0,K=K+this.B|0,H=H+this.C|0,D=D+this.D|0,P=P+this.E|0,this.set(q,K,H,D,P)}roundClean(){(0,t.clean)(r)}destroy(){this.set(0,0,0,0,0),(0,t.clean)(this.buffer)}}Jt.SHA1=i,Jt.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:C,C:q,D:K}=this;return[v,C,q,K]}set(v,C,q,K){this.A=v|0,this.B=C|0,this.C=q|0,this.D=K|0}process(v,C){for(let P=0;P<16;P++,C+=4)a[P]=v.getUint32(C,!0);let{A:q,B:K,C:H,D}=this;for(let P=0;P<64;P++){let $,F,x;P<16?($=(0,e.Chi)(K,H,D),F=P,x=[7,12,17,22]):P<32?($=(0,e.Chi)(D,K,H),F=(5*P+1)%16,x=[5,9,14,20]):P<48?($=K^H^D,F=(3*P+5)%16,x=[4,11,16,23]):($=H^(K|~D),F=7*P%16,x=[6,10,15,21]),$=$+q+o[P]+a[F],q=D,D=H,H=K,K=K+(0,t.rotl)($,x[P%4])}q=q+this.A|0,K=K+this.B|0,H=H+this.C|0,D=D+this.D|0,this.set(q,K,H,D)}roundClean(){(0,t.clean)(a)}destroy(){this.set(0,0,0,0),(0,t.clean)(this.buffer)}}Jt.MD5=u,Jt.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 C=[[l],[d]];for(let q=0;q<4;q++)for(let K of C)K.push(K[q].map(H=>f[H]));return C})(),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)),S=g.map((M,v)=>M.map(C=>E[v][C])),_=m.map((M,v)=>M.map(C=>E[v][C])),w=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),T=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function O(M,v,C,q){return M===0?v^C^q:M===1?v&C|~v&q:M===2?(v|~C)^q:M===3?v&q|C&~q:v^(C|~q)}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:C,h2:q,h3:K,h4:H}=this;return[v,C,q,K,H]}set(v,C,q,K,H){this.h0=v|0,this.h1=C|0,this.h2=q|0,this.h3=K|0,this.h4=H|0}process(v,C){for(let N=0;N<16;N++,C+=4)A[N]=v.getUint32(C,!0);let q=this.h0|0,K=q,H=this.h1|0,D=H,P=this.h2|0,$=P,F=this.h3|0,x=F,B=this.h4|0,L=B;for(let N=0;N<5;N++){const V=4-N,G=w[N],X=T[N],Y=g[N],ce=m[N],ue=S[N],te=_[N];for(let Z=0;Z<16;Z++){const ae=(0,t.rotl)(q+O(N,H,P,F)+A[Y[Z]]+G,ue[Z])+B|0;q=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(V,D,$,x)+A[ce[Z]]+X,te[Z])+L|0;K=L,L=x,x=(0,t.rotl)($,10)|0,$=D,D=ae}}this.set(this.h1+P+x|0,this.h2+F+L|0,this.h3+B+K|0,this.h4+q+D|0,this.h0+H+$|0)}roundClean(){(0,t.clean)(A)}destroy(){this.destroyed=!0,(0,t.clean)(this.buffer),this.set(0,0,0,0,0)}}return Jt.RIPEMD160=R,Jt.ripemd160=(0,t.createHasher)(()=>new R),Jt}var ip;function W8(){if(ip)return xi;ip=1,Object.defineProperty(xi,"__esModule",{value:!0}),xi.ripemd160=xi.RIPEMD160=void 0;const e=Gw();return xi.RIPEMD160=e.RIPEMD160,xi.ripemd160=e.ripemd160,xi}var Ai={},sp;function X8(){if(sp)return Ai;sp=1,Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.sha1=Ai.SHA1=void 0;const e=Gw();return Ai.SHA1=e.SHA1,Ai.sha1=e.sha1,Ai}var Cn={},op;function Ww(){if(op)return Cn;op=1,Object.defineProperty(Cn,"__esModule",{value:!0}),Cn.sha224=Cn.SHA224=Cn.sha256=Cn.SHA256=void 0;const e=Py();return Cn.SHA256=e.SHA256,Cn.sha256=e.sha256,Cn.SHA224=e.SHA224,Cn.sha224=e.sha224,Cn}var cp;function Rr(){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=W8(),n=X8(),r=Ww();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 z8(){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,S=0,_=g.length;S!==_&&g[S]===0;)S++,m++;for(var w=(_-S)*f+1>>>0,T=new Uint8Array(w);S!==_;){for(var O=g[S],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,S++}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,S=0;g[m]===a;)E++,m++;for(var _=(g.length-m)*u+1>>>0,w=new Uint8Array(_);g[m];){var T=g.charCodeAt(m);if(T>255)return;var O=n[T];if(O===255)return;for(var A=0,R=_-1;(O!==0||A<S)&&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");S=A,m++}for(var M=_-S;M!==_&&w[M]===0;)M++;for(var v=new Uint8Array(E+(_-M)),C=E;M!==_;)v[C++]=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 Y8(){return up||(up=1,Af=z8()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),Af}var vf,fp;function Z8(){if(fp)return vf;fp=1;var e=Y8();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}=Ww(),t=Z8();function n(r){return e(e(r))}return If=t(n),If}var hp;function J8(){if(hp)return co;hp=1,Object.defineProperty(co,"__esModule",{value:!0}),co.p2pkh=void 0;const e=Rr(),t=Wn(),n=nn(),r=zt(),i=yi(),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 co.p2pkh=c,co}var ao={},dp;function Q8(){if(dp)return ao;dp=1,Object.defineProperty(ao,"__esModule",{value:!0}),ao.p2sh=void 0;const e=Rr(),t=Wn(),n=nn(),r=zt(),i=yi(),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),S=m.slice(1);return{version:E,hash:S}}),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 S=a.output.slice(2,22);if(m.length>0&&!m.equals(S))throw new TypeError("Hash mismatch");m=S}const E=S=>{if(S.output){const _=n.decompile(S.output);if(!_||_.length<1)throw new TypeError("Redeem.output too short");if(S.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(n.countNonPushOnlyOPs(_)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const w=e.hash160(S.output);if(m.length>0&&!m.equals(w))throw new TypeError("Hash mismatch");m=w}if(S.input){const _=S.input.length>0,w=S.witness&&S.witness.length>0;if(!_&&!w)throw new TypeError("Empty input");if(_&&w)throw new TypeError("Input and witness provided");if(_){const T=n.decompile(S.input);if(!n.isPushOnly(T))throw new TypeError("Non push-only scriptSig")}}};if(a.input){const S=y();if(!S||S.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 S=g();if(a.redeem.output&&!a.redeem.output.equals(S.output))throw new TypeError("Redeem.output mismatch");if(a.redeem.input&&!a.redeem.input.equals(S.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 ao.p2sh=c,ao}var uo={},pp;function eA(){if(pp)return uo;pp=1,Object.defineProperty(uo,"__esModule",{value:!0}),uo.p2wpkh=void 0;const e=Rr(),t=Wn(),n=nn(),r=zt(),i=yi(),s=cc(),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 uo.p2wpkh=a,uo}var fo={},yp;function tA(){if(yp)return fo;yp=1,Object.defineProperty(fo,"__esModule",{value:!0}),fo.p2wsh=void 0;const e=Rr(),t=Wn(),n=nn(),r=zt(),i=yi(),s=cc(),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),S=E.words.shift(),_=s.bech32.fromWords(E.words);return{version:S,prefix:E.prefix,data:Buffer.from(_)}}),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 S=f.output.slice(2);if(E.length>0&&!E.equals(S))throw new TypeError("Hash mismatch");E=S}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 S=n.decompile(f.redeem.output);if(!S||S.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(S)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const _=e.sha256(f.redeem.output);if(E.length>0&&!E.equals(_))throw new TypeError("Hash mismatch");E=_}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 S=f.witness[f.witness.length-1];if(f.redeem&&f.redeem.output&&!f.redeem.output.equals(S))throw new TypeError("Witness and redeem.output mismatch");if(f.witness.some(a)||(n.decompile(S)||[]).some(a))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(m,f)}return fo.p2wsh=u,fo}var lo={},vi={},gp;function Sh(){if(gp)return vi;gp=1,Object.defineProperty(vi,"__esModule",{value:!0}),vi.getEccLib=vi.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}vi.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}vi.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 vi}var Of={},Pt={},Hc={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var mp;function nA(){return mp||(mp=1,(function(e,t){var n=ec(),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)}})(Hc,Hc.exports)),Hc.exports}var Bf,wp;function rA(){if(wp)return Bf;wp=1;var e=nA().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 Pt;bp=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.BufferReader=Pt.BufferWriter=Pt.cloneBuffer=Pt.reverseBuffer=Pt.writeUInt64LE=Pt.readUInt64LE=Pt.varuint=void 0;const e=zt(),{typeforce:t}=e,n=rA();Pt.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}Pt.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}Pt.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}Pt.reverseBuffer=o;function c(f){const l=Buffer.allocUnsafe(f.length);return f.copy(l),l}Pt.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}`)}}Pt.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 Pt.BufferReader=u,Pt}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=ec(),n=Sh(),r=Rr(),i=Eu(),s=zt();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 S=(m.length-33)/32;let _=E;for(let w=0;w<S;w++){const T=m.slice(33+32*w,65+32*w);_.compare(T)<0?_=y(_,T):_=y(T,_)}return _}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(S.hash,_.hash),left:S,right:_}}e.toHashTree=a;function u(m,E){if(o(m)){const S=u(m.left,E);if(S!==void 0)return[...S,m.right.hash];const _=u(m.right,E);if(_!==void 0)return[..._,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 S=l(m,E),_=(0,n.getEccLib)().xOnlyPointAddTweak(m,S);return!_||_.xOnlyPubkey===null?null:{parity:_.parity,x:t.Buffer.from(_.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),S=t.Buffer.allocUnsafe(E);return i.varuint.encode(m.length,S),t.Buffer.concat([S,m])}})(Of)),Of}var _p;function iA(){if(_p)return lo;_p=1,Object.defineProperty(lo,"__esModule",{value:!0}),lo.p2tr=void 0;const e=ec(),t=Wn(),n=nn(),r=zt(),i=Sh(),s=Th(),o=yi(),c=cc(),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()}),S=o.value(()=>{if(y.scriptTree)return(0,s.toHashTree)(y.scriptTree);if(y.hash)return{hash:y.hash}}),_=y.network||t.bitcoin,w={name:"p2tr",network:_};if(o.prop(w,"address",()=>{if(!w.pubkey)return;const T=c.bech32m.toWords(w.pubkey);return T.unshift(f),c.bech32m.encode(_.bech32,T)}),o.prop(w,"hash",()=>{const T=S();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=S();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(_&&_.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=S();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 C=R[0]&r.TAPLEAF_VERSION_MASK,q=A[A.length-2],K=(0,s.tapleafHash)({output:q,version:C}),H=(0,s.rootHashFromPath)(R,K),D=(0,s.tweakKey)(v,H);if(!D)throw new TypeError("Invalid outputKey for p2tr witness");if(T.length&&!T.equals(D.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(D.parity!==(R[0]&1))throw new Error("Incorrect parity")}}return Object.assign(w,y)}return lo.p2tr=d,lo}var Sp;function bc(){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=j8();Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const n=K8();Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return n.p2ms}});const r=G8();Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return r.p2pk}});const i=J8();Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const s=Q8();Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return s.p2sh}});const o=eA();Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const c=tA();Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return c.p2wsh}});const a=iA();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return a.p2tr}})})(gf)),gf}var Tp;function xh(){if(Tp)return Zt;Tp=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.toOutputScript=Zt.fromOutputScript=Zt.toBech32=Zt.toBase58Check=Zt.fromBech32=Zt.fromBase58Check=void 0;const e=Wn(),t=bc(),n=nn(),r=zt(),i=cc(),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}}Zt.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)}}Zt.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)}Zt.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)}Zt.toBech32=E;function S(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")}Zt.fromOutputScript=S;function _(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 Zt.toOutputScript=_,Zt}var ho={},po={},xp;function sA(){if(xp)return po;xp=1,Object.defineProperty(po,"__esModule",{value:!0}),po.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 po.fastMerkleRoot=e,po}var yo={},Ap;function Ec(){if(Ap)return yo;Ap=1,Object.defineProperty(yo,"__esModule",{value:!0}),yo.Transaction=void 0;const e=Eu(),t=Rr(),n=nn(),r=nn(),i=zt(),{typeforce:s}=i;function o(E){const S=E.length;return e.varuint.encodingLength(S)+S}function c(E){const S=E.length;return e.varuint.encodingLength(S)+E.reduce((_,w)=>_+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(S),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 C=0;C<M;++C)T.ins.push({hash:w.readSlice(32),index:w.readUInt32(),script:w.readVarSlice(),sequence:w.readUInt32(),witness:u});const v=w.readVarInt();for(let C=0;C<v;++C)T.outs.push({value:w.readUInt64(),script:w.readVarSlice()});if(R){for(let C=0;C<M;++C)T.ins[C].witness=w.readVector();if(!T.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(T.locktime=w.readUInt32(),_)return T;if(w.offset!==S.length)throw new Error("Transaction has unexpected data");return T}static fromHex(S){return m.fromBuffer(Buffer.from(S,"hex"),!1)}static isCoinbaseHash(S){s(i.Hash256bit,S);for(let _=0;_<32;++_)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:S,index:_,script:T||a,sequence:w,witness:u})-1}addOutput(S,_){return s(i.tuple(i.Buffer,i.Satoshi),arguments),this.outs.push({script:S,value:_})-1}hasWitnesses(){return this.ins.some(S=>S.witness.length!==0)}stripWitnesses(){this.ins.forEach(S=>{S.witness=u})}weight(){const S=this.byteLength(!1),_=this.byteLength(!0);return S*3+_}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(S=!0){const _=S&&this.hasWitnesses();return(_?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)+(_?this.ins.reduce((w,T)=>w+c(T.witness),0):0)}clone(){const S=new m;return S.version=this.version,S.locktime=this.locktime,S.ins=this.ins.map(_=>({hash:_.hash,index:_.index,script:_.script,sequence:_.sequence,witness:_.witness})),S.outs=this.outs.map(_=>({script:_.script,value:_.value})),S}hashForSignature(S,_,w){if(s(i.tuple(i.UInt32,i.Buffer,i.Number),arguments),S>=this.ins.length)return l;const T=n.compile(n.decompile(_).filter(R=>R!==r.OPS.OP_CODESEPARATOR)),O=this.clone();if((w&31)===m.SIGHASH_NONE)O.outs=[],O.ins.forEach((R,M)=>{M!==S&&(R.sequence=0)});else if((w&31)===m.SIGHASH_SINGLE){if(S>=this.outs.length)return l;O.outs.length=S+1;for(let R=0;R<S;R++)O.outs[R]=y;O.ins.forEach((R,M)=>{M!==S&&(R.sequence=0)})}w&m.SIGHASH_ANYONECANPAY?(O.ins=[O.ins[S]],O.ins[0].script=T):(O.ins.forEach(R=>{R.script=a}),O.ins[S].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||_.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,C=R===m.SIGHASH_NONE,q=R===m.SIGHASH_SINGLE;let K=a,H=a,D=a,P=a,$=a;if(!v){let L=e.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(N=>{L.writeSlice(N.hash),L.writeUInt32(N.index)}),K=t.sha256(L.end()),L=e.BufferWriter.withCapacity(8*this.ins.length),w.forEach(N=>L.writeUInt64(N)),H=t.sha256(L.end()),L=e.BufferWriter.withCapacity(_.map(o).reduce((N,V)=>N+V)),_.forEach(N=>L.writeVarSlice(N)),D=t.sha256(L.end()),L=e.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(N=>L.writeUInt32(N.sequence)),P=t.sha256(L.end())}if(C||q){if(q&&S<this.outs.length){const L=this.outs[S],N=e.BufferWriter.withCapacity(8+o(L.script));N.writeUInt64(L.value),N.writeVarSlice(L.script),$=t.sha256(N.end())}}else{const L=this.outs.map(V=>8+o(V.script)).reduce((V,G)=>V+G),N=e.BufferWriter.withCapacity(L);this.outs.forEach(V=>{N.writeUInt64(V.value),N.writeVarSlice(V.script)}),$=t.sha256(N.end())}const F=(O?2:0)+(A?1:0),x=174-(v?49:0)-(C?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(D),B.writeSlice(P),C||q||B.writeSlice($),B.writeUInt8(F),v){const L=this.ins[S];B.writeSlice(L.hash),B.writeUInt32(L.index),B.writeUInt64(w[S]),B.writeVarSlice(_[S]),B.writeUInt32(L.sequence)}else B.writeUInt32(S);if(A){const L=e.BufferWriter.withCapacity(o(A));L.writeVarSlice(A),B.writeSlice(t.sha256(L.end()))}return q&&B.writeSlice($),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(q=>{A.writeSlice(q.hash),A.writeUInt32(q.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(q=>{A.writeUInt32(q.sequence)}),v=t.hash256(O)),(T&31)!==m.SIGHASH_SINGLE&&(T&31)!==m.SIGHASH_NONE){const q=this.outs.reduce((K,H)=>K+8+o(H.script),0);O=Buffer.allocUnsafe(q),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&&S<this.outs.length){const q=this.outs[S];O=Buffer.allocUnsafe(8+o(q.script)),A=new e.BufferWriter(O,0),A.writeUInt64(q.value),A.writeVarSlice(q.script),R=t.hash256(O)}O=Buffer.allocUnsafe(156+o(_)),A=new e.BufferWriter(O,0);const C=this.ins[S];return A.writeInt32(this.version),A.writeSlice(M),A.writeSlice(v),A.writeSlice(C.hash),A.writeUInt32(C.index),A.writeVarSlice(_),A.writeUInt64(w),A.writeUInt32(C.sequence),A.writeSlice(R),A.writeUInt32(this.locktime),A.writeUInt32(T),t.hash256(O)}getHash(S){return S&&this.isCoinbase()?Buffer.alloc(32,0):t.hash256(this.__toBuffer(void 0,void 0,S))}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[S].script=_}setWitness(S,_){s(i.tuple(i.Number,[i.Buffer]),arguments),this.ins[S].witness=_}__toBuffer(S,_,w=!1){S||(S=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),_!==void 0?S.slice(_,T.offset):S}}return yo.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,yo}var vp;function oA(){if(vp)return ho;vp=1,Object.defineProperty(ho,"__esModule",{value:!0}),ho.Block=void 0;const e=Eu(),t=Rr(),n=sA(),r=Ec(),i=zt(),{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 _=r.Transaction.fromBuffer(y.buffer.slice(y.offset),!0);return y.offset+=_.byteLength(),_},E=y.readVarInt();g.transactions=[];for(let _=0;_<E;++_){const w=m();g.transactions.push(w)}const S=g.getWitnessCommit();return S&&(g.witnessCommit=S),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}}ho.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 ho}var go={},Fc={},Mc={},Nf={},os={},cs={},kf={},Ip;function Lt(){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 Dr={},Op;function cA(){if(Op)return Dr;Op=1,Object.defineProperty(Dr,"__esModule",{value:!0});const e=Lt(),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}Dr.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}}Dr.encode=r,Dr.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+'?)*$/)}Dr.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 Dr.canAddToArray=s,Dr}var Lc={},Bp;function aA(){if(Bp)return Lc;Bp=1,Object.defineProperty(Lc,"__esModule",{value:!0});const e=Lt();function t(n){return{key:Buffer.from([e.GlobalTypes.UNSIGNED_TX]),value:n.toBuffer()}}return Lc.encode=t,Lc}var $r={},Np;function uA(){if(Np)return $r;Np=1,Object.defineProperty($r,"__esModule",{value:!0});const e=Lt();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}$r.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.FINAL_SCRIPTSIG]),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.finalScriptSig===void 0}return $r.canAdd=i,$r}var jr={},kp;function fA(){if(kp)return jr;kp=1,Object.defineProperty(jr,"__esModule",{value:!0});const e=Lt();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}jr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.FINAL_SCRIPTWITNESS]),value:s}}jr.encode=n,jr.expected="Buffer";function r(s){return Buffer.isBuffer(s)}jr.check=r;function i(s,o){return!!s&&!!o&&s.finalScriptWitness===void 0}return jr.canAdd=i,jr}var Kr={},Pp;function lA(){if(Pp)return Kr;Pp=1,Object.defineProperty(Kr,"__esModule",{value:!0});const e=Lt();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}Kr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.NON_WITNESS_UTXO]),value:s}}Kr.encode=n,Kr.expected="Buffer";function r(s){return Buffer.isBuffer(s)}Kr.check=r;function i(s,o){return!!s&&!!o&&s.nonWitnessUtxo===void 0}return Kr.canAdd=i,Kr}var Gr={},Rp;function hA(){if(Rp)return Gr;Rp=1,Object.defineProperty(Gr,"__esModule",{value:!0});const e=Lt();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}}Gr.decode=t;function n(o){const c=Buffer.from([e.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([c,o.pubkey]),value:o.signature}}Gr.encode=n,Gr.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)}Gr.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 Gr.canAddToArray=s,Gr}var Wr={},Cp;function dA(){if(Cp)return Wr;Cp=1,Object.defineProperty(Wr,"__esModule",{value:!0});const e=Lt();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")}Wr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.POR_COMMITMENT]),value:Buffer.from(s,"utf8")}}Wr.encode=n,Wr.expected="string";function r(s){return typeof s=="string"}Wr.check=r;function i(s,o){return!!s&&!!o&&s.porCommitment===void 0}return Wr.canAdd=i,Wr}var Xr={},Up;function pA(){if(Up)return Xr;Up=1,Object.defineProperty(Xr,"__esModule",{value:!0});const e=Lt();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)}Xr.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}}Xr.encode=n,Xr.expected="number";function r(s){return typeof s=="number"}Xr.check=r;function i(s,o){return!!s&&!!o&&s.sighashType===void 0}return Xr.canAdd=i,Xr}var zr={},Hp;function yA(){if(Hp)return zr;Hp=1,Object.defineProperty(zr,"__esModule",{value:!0});const e=Lt();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}zr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.TAP_KEY_SIG]),value:s}}zr.encode=n,zr.expected="Buffer";function r(s){return Buffer.isBuffer(s)&&(s.length===64||s.length===65)}zr.check=r;function i(s,o){return!!s&&!!o&&s.tapKeySig===void 0}return zr.canAdd=i,zr}var Yr={},Fp;function gA(){if(Fp)return Yr;Fp=1,Object.defineProperty(Yr,"__esModule",{value:!0});const e=Lt();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}}Yr.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])}}Yr.encode=n,Yr.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)}Yr.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 Yr.canAddToArray=i,Yr}var Zr={},Mp;function mA(){if(Mp)return Zr;Mp=1,Object.defineProperty(Zr,"__esModule",{value:!0});const e=Lt();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 Jr={},Lp;function wA(){if(Lp)return Jr;Lp=1,Object.defineProperty(Jr,"__esModule",{value:!0});const e=Lt();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}}Jr.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}}Jr.encode=n,Jr.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)}Jr.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 Jr.canAddToArray=i,Jr}var Qr={},hr={},as={},qp;function es(){if(qp)return as;qp=1,Object.defineProperty(as,"__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}as.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}}as.decode=r;function i(s){return t(s),s<253?1:s<=65535?3:s<=4294967295?5:9}return as.encodingLength=i,as}var Vp;function Ah(){if(Vp)return hr;Vp=1,Object.defineProperty(hr,"__esModule",{value:!0});const e=es();hr.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}hr.reverseBuffer=t;function n(c){const a=c.map(r);return a.push(Buffer.from([0])),Buffer.concat(a)}hr.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}hr.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}hr.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 hr.writeUInt64LE=o,hr}var Dp;function bA(){if(Dp)return Qr;Dp=1,Object.defineProperty(Qr,"__esModule",{value:!0});const e=Lt(),t=Ah(),n=es();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}}Qr.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}}Qr.encode=i,Qr.expected="{ script: Buffer; value: number; }";function s(c){return Buffer.isBuffer(c.script)&&typeof c.value=="number"}Qr.check=s;function o(c,a){return!!c&&!!a&&c.witnessUtxo===void 0}return Qr.canAdd=o,Qr}var ei={},$p;function EA(){if($p)return ei;$p=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=Lt(),t=es();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}}ei.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)}}ei.encode=r,ei.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))}ei.check=i;function s(o,c){return!!o&&!!c&&o.tapTree===void 0}return ei.canAdd=s,ei}var qc={},jp;function Xw(){if(jp)return qc;jp=1,Object.defineProperty(qc,"__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 S=E.slice(-1)==="'";let _=2147483647&parseInt(S?E.slice(0,-1):E,10);S&&(_+=2147483648),g.writeUInt32LE(_,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 qc.makeConverter=n,qc}var Vc={},Kp;function _A(){if(Kp)return Vc;Kp=1,Object.defineProperty(Vc,"__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 Vc.makeChecker=e,Vc}var Dc={},Gp;function SA(){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 $c={},Wp;function TA(){if(Wp)return $c;Wp=1,Object.defineProperty($c,"__esModule",{value:!0});const e=es(),t=Xw(),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 $c.makeConverter=r,$c}var jc={},Xp;function xA(){if(Xp)return jc;Xp=1,Object.defineProperty(jc,"__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 jc.makeConverter=e,jc}var Kc={},zp;function AA(){if(zp)return Kc;zp=1,Object.defineProperty(Kc,"__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 Kc.makeConverter=e,Kc}var Yp;function vh(){if(Yp)return cs;Yp=1,Object.defineProperty(cs,"__esModule",{value:!0});const e=Lt(),t=cA(),n=aA(),r=uA(),i=fA(),s=lA(),o=hA(),c=dA(),a=pA(),u=yA(),f=gA(),l=mA(),d=wA(),y=bA(),g=EA(),m=Xw(),E=_A(),S=SA(),_=TA(),w=xA(),T=AA(),O={unsignedTx:n,globalXpub:t,checkPubkey:E.makeChecker([])};cs.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:S.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:_.makeConverter(e.InputTypes.TAP_BIP32_DERIVATION),tapInternalKey:w.makeConverter(e.InputTypes.TAP_INTERNAL_KEY),tapMerkleRoot:l};cs.inputs=A;const R={bip32Derivation:m.makeConverter(e.OutputTypes.BIP32_DERIVATION),redeemScript:S.makeConverter(e.OutputTypes.REDEEM_SCRIPT),witnessScript:T.makeConverter(e.OutputTypes.WITNESS_SCRIPT),checkPubkey:E.makeChecker([e.OutputTypes.BIP32_DERIVATION]),tapBip32Derivation:_.makeConverter(e.OutputTypes.TAP_BIP32_DERIVATION),tapTree:g,tapInternalKey:w.makeConverter(e.OutputTypes.TAP_INTERNAL_KEY)};return cs.outputs=R,cs}var Zp;function vA(){if(Zp)return os;Zp=1,Object.defineProperty(os,"__esModule",{value:!0});const e=vh(),t=Ah(),n=es(),r=Lt();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 S=m.filter(R=>R.key[0]===r.GlobalTypes.UNSIGNED_TX);if(S.length!==1)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const _=a(S[0].value),{inputCount:w,outputCount:T}=_.getInputOutputCounts(),O=[],A=[];for(const R of t.range(w)){const M={},v=[];for(;!g();){const C=y(),q=C.key.toString("hex");if(M[q])throw new Error("Format Error: Keys must be unique for each input: input index "+R+" key "+q);M[q]=1,v.push(C)}O.push(v)}for(const R of t.range(T)){const M={},v=[];for(;!g();){const C=y(),q=C.key.toString("hex");if(M[q])throw new Error("Format Error: Keys must be unique for each output: output index "+R+" key "+q);M[q]=1,v.push(C)}A.push(v)}return o(_,{globalMapKeyVals:m,inputKeyVals:O,outputKeyVals:A})}os.psbtFromBuffer=i;function s(c,a,u){if(!a.equals(Buffer.from([u])))throw new Error(`Format Error: Invalid ${c} key: ${a.toString("hex")}`)}os.checkKeyBuffer=s;function o(c,{globalMapKeyVals:a,inputKeyVals:u,outputKeyVals:f}){const l={unsignedTx:c};let d=0;for(const S of a)switch(S.key[0]){case r.GlobalTypes.UNSIGNED_TX:if(s("global",S.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(S));break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(S)}const y=u.length,g=f.length,m=[],E=[];for(const S of t.range(y)){const _={};for(const w of u[S])switch(e.inputs.checkPubkey(w),w.key[0]){case r.InputTypes.NON_WITNESS_UTXO:if(s("input",w.key,r.InputTypes.NON_WITNESS_UTXO),_.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");_.nonWitnessUtxo=e.inputs.nonWitnessUtxo.decode(w);break;case r.InputTypes.WITNESS_UTXO:if(s("input",w.key,r.InputTypes.WITNESS_UTXO),_.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");_.witnessUtxo=e.inputs.witnessUtxo.decode(w);break;case r.InputTypes.PARTIAL_SIG:_.partialSig===void 0&&(_.partialSig=[]),_.partialSig.push(e.inputs.partialSig.decode(w));break;case r.InputTypes.SIGHASH_TYPE:if(s("input",w.key,r.InputTypes.SIGHASH_TYPE),_.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");_.sighashType=e.inputs.sighashType.decode(w);break;case r.InputTypes.REDEEM_SCRIPT:if(s("input",w.key,r.InputTypes.REDEEM_SCRIPT),_.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");_.redeemScript=e.inputs.redeemScript.decode(w);break;case r.InputTypes.WITNESS_SCRIPT:if(s("input",w.key,r.InputTypes.WITNESS_SCRIPT),_.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");_.witnessScript=e.inputs.witnessScript.decode(w);break;case r.InputTypes.BIP32_DERIVATION:_.bip32Derivation===void 0&&(_.bip32Derivation=[]),_.bip32Derivation.push(e.inputs.bip32Derivation.decode(w));break;case r.InputTypes.FINAL_SCRIPTSIG:s("input",w.key,r.InputTypes.FINAL_SCRIPTSIG),_.finalScriptSig=e.inputs.finalScriptSig.decode(w);break;case r.InputTypes.FINAL_SCRIPTWITNESS:s("input",w.key,r.InputTypes.FINAL_SCRIPTWITNESS),_.finalScriptWitness=e.inputs.finalScriptWitness.decode(w);break;case r.InputTypes.POR_COMMITMENT:s("input",w.key,r.InputTypes.POR_COMMITMENT),_.porCommitment=e.inputs.porCommitment.decode(w);break;case r.InputTypes.TAP_KEY_SIG:s("input",w.key,r.InputTypes.TAP_KEY_SIG),_.tapKeySig=e.inputs.tapKeySig.decode(w);break;case r.InputTypes.TAP_SCRIPT_SIG:_.tapScriptSig===void 0&&(_.tapScriptSig=[]),_.tapScriptSig.push(e.inputs.tapScriptSig.decode(w));break;case r.InputTypes.TAP_LEAF_SCRIPT:_.tapLeafScript===void 0&&(_.tapLeafScript=[]),_.tapLeafScript.push(e.inputs.tapLeafScript.decode(w));break;case r.InputTypes.TAP_BIP32_DERIVATION:_.tapBip32Derivation===void 0&&(_.tapBip32Derivation=[]),_.tapBip32Derivation.push(e.inputs.tapBip32Derivation.decode(w));break;case r.InputTypes.TAP_INTERNAL_KEY:s("input",w.key,r.InputTypes.TAP_INTERNAL_KEY),_.tapInternalKey=e.inputs.tapInternalKey.decode(w);break;case r.InputTypes.TAP_MERKLE_ROOT:s("input",w.key,r.InputTypes.TAP_MERKLE_ROOT),_.tapMerkleRoot=e.inputs.tapMerkleRoot.decode(w);break;default:_.unknownKeyVals||(_.unknownKeyVals=[]),_.unknownKeyVals.push(w)}m.push(_)}for(const S of t.range(g)){const _={};for(const w of f[S])switch(e.outputs.checkPubkey(w),w.key[0]){case r.OutputTypes.REDEEM_SCRIPT:if(s("output",w.key,r.OutputTypes.REDEEM_SCRIPT),_.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");_.redeemScript=e.outputs.redeemScript.decode(w);break;case r.OutputTypes.WITNESS_SCRIPT:if(s("output",w.key,r.OutputTypes.WITNESS_SCRIPT),_.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");_.witnessScript=e.outputs.witnessScript.decode(w);break;case r.OutputTypes.BIP32_DERIVATION:_.bip32Derivation===void 0&&(_.bip32Derivation=[]),_.bip32Derivation.push(e.outputs.bip32Derivation.decode(w));break;case r.OutputTypes.TAP_INTERNAL_KEY:s("output",w.key,r.OutputTypes.TAP_INTERNAL_KEY),_.tapInternalKey=e.outputs.tapInternalKey.decode(w);break;case r.OutputTypes.TAP_TREE:s("output",w.key,r.OutputTypes.TAP_TREE),_.tapTree=e.outputs.tapTree.decode(w);break;case r.OutputTypes.TAP_BIP32_DERIVATION:_.tapBip32Derivation===void 0&&(_.tapBip32Derivation=[]),_.tapBip32Derivation.push(e.outputs.tapBip32Derivation.decode(w));break;default:_.unknownKeyVals||(_.unknownKeyVals=[]),_.unknownKeyVals.push(w)}E.push(_)}return{globalMap:l,inputs:m,outputs:E}}return os.psbtFromKeyVals=o,os}var mo={},Jp;function IA(){if(Jp)return mo;Jp=1,Object.defineProperty(mo,"__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=S=>S.length===0?[Buffer.from([0])]:S.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))}mo.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(S=>S.key.toString("hex")).forEach(S=>{if(a.has(S))throw new Error("Serialize Error: Duplicate key: "+S);a.add(S)}),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 mo.psbtToKeyVals=s,mo}var Qp;function zw(){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(vA()),t(IA())})(Nf)),Nf}var ey;function OA(){if(ey)return Mc;ey=1,Object.defineProperty(Mc,"__esModule",{value:!0});const e=zw();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})}Mc.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 Mc}var Pf={},ty;function Yw(){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,S=!!g.witnessScript,_=!E||!!g.finalScriptSig,w=!S||!!g.finalScriptWitness,T=!!g.finalScriptSig||!!g.finalScriptWitness;m=_&&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 S=g[E],{canAdd:_,canAddToArray:w,check:T,expected:O}=t[y+"s"][E]||{},A=!!w;if(T)if(A){if(!Array.isArray(S)||m[E]&&!Array.isArray(m[E]))throw new Error(`Key type ${E} must be an array`);S.every(T)||c(y,E,O,S);const R=m[E]||[],M=new Set;if(!S.every(v=>w(R,v,M)))throw new Error("Can not add duplicate data to array");m[E]=R.concat(S)}else{if(T(S)||c(y,E,O,S),!_(m,S))throw new Error(`Can not add duplicate data to ${y}`);m[E]=S}}}}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 BA(){if(ny)return Fc;ny=1,Object.defineProperty(Fc,"__esModule",{value:!0});const e=OA(),t=zw(),n=Lt(),r=Yw();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 Fc.Psbt=i,Fc}var et={},Ye={},ry;function dl(){if(ry)return Ye;ry=1,Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.signatureBlocksAction=Ye.checkInputForSig=Ye.pubkeyInScript=Ye.pubkeyPositionInScript=Ye.witnessStackToScriptWitness=Ye.isP2TR=Ye.isP2SHScript=Ye.isP2WSHScript=Ye.isP2WPKH=Ye.isP2PKH=Ye.isP2PK=Ye.isP2MS=void 0;const e=es(),t=nn(),n=Ec(),r=Rr(),i=bc();function s(y){return g=>{try{return y({output:g}),!0}catch{return!1}}}Ye.isP2MS=s(i.p2ms),Ye.isP2PK=s(i.p2pk),Ye.isP2PKH=s(i.p2pkh),Ye.isP2WPKH=s(i.p2wpkh),Ye.isP2WSHScript=s(i.p2wsh),Ye.isP2SHScript=s(i.p2sh),Ye.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 S(w){E(w.length),m(w)}function _(w){E(w.length),w.forEach(S)}return _(y),g}Ye.witnessStackToScriptWitness=o;function c(y,g){const m=(0,r.hash160)(y),E=y.slice(1,33),S=t.decompile(g);if(S===null)throw new Error("Unknown script error");return S.findIndex(_=>typeof _=="number"?!1:_.equals(y)||_.equals(m)||_.equals(E))}Ye.pubkeyPositionInScript=c;function a(y,g){return c(y,g)!==-1}Ye.pubkeyInScript=a;function u(y,g){return l(y).some(E=>f(E,t.signature.decode,g))}Ye.checkInputForSig=u;function f(y,g,m){const{hashType:E}=g(y),S=[];switch(E&n.Transaction.SIGHASH_ANYONECANPAY&&S.push("addInput"),E&31){case n.Transaction.SIGHASH_ALL:break;case n.Transaction.SIGHASH_SINGLE:case n.Transaction.SIGHASH_NONE:S.push("addOutput"),S.push("setInputSequence");break}return S.indexOf(m)===-1}Ye.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 Ye}var iy;function NA(){if(iy)return et;iy=1,Object.defineProperty(et,"__esModule",{value:!0}),et.checkTaprootInputForSigs=et.tapTreeFromList=et.tapTreeToList=et.tweakInternalPubKey=et.checkTaprootOutputFields=et.checkTaprootInputFields=et.isTaprootOutput=et.isTaprootInput=et.serializeTaprootSignature=et.tapScriptFinalizer=et.toXOnly=void 0;const e=zt(),t=Ec(),n=dl(),r=Th(),i=bc(),s=dl(),o=x=>x.length===32?x:x.slice(1,33);et.toXOnly=o;function c(x,B,L){const N=P(B,x,L);try{const G=H(B,N).concat(N.script).concat(N.controlBlock);return{finalScriptWitness:(0,n.witnessStackToScriptWitness)(G)}}catch(V){throw new Error(`Can not finalize taproot input #${x}: ${V}`)}}et.tapScriptFinalizer=c;function a(x,B){const L=B?Buffer.from([B]):Buffer.from([]);return Buffer.concat([x,L])}et.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))}et.isTaprootInput=u;function f(x,B){return x&&!!(x.tapInternalKey||x.tapTree||x.tapBip32Derivation&&x.tapBip32Derivation.length||B&&(0,n.isP2TR)(B))}et.isTaprootOutput=f;function l(x,B,L){v(x,B,L),q(x,B,L)}et.checkTaprootInputFields=l;function d(x,B,L){C(x,B,L),y(x,B)}et.checkTaprootOutputFields=d;function y(x,B){if(!B.tapTree&&!B.tapInternalKey)return;const L=B.tapInternalKey||x.tapInternalKey,N=B.tapTree||x.tapTree;if(L){const{script:V}=x,G=g(L,N);if(V&&!V.equals(G))throw new Error("Error adding output. Script or address missmatch.")}}function g(x,B){const L=B&&S(B.leaves),{output:N}=(0,i.p2tr)({internalPubkey:x,scriptTree:L});return N}function m(x,B){const L=B.tapInternalKey,N=L&&(0,r.tweakKey)(L,B.tapMerkleRoot);if(!N)throw new Error(`Cannot tweak tap internal key for input #${x}. Public key: ${L&&L.toString("hex")}`);return N.x}et.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)}et.tapTreeToList=E;function S(x=[]){return x.length===1&&x[0].depth===0?{output:x[0].script,version:x[0].leafVersion}:R(x)}et.tapTreeFromList=S;function _(x,B){return T(x).some(N=>(0,s.signatureBlocksAction)(N,w,B))}et.checkTaprootInputForSigs=_;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(L=>L.signature)),!B.length){const L=O(x.finalScriptWitness);L&&B.push(L)}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=[],L=0){if(L>r.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return x?(0,e.isTapleaf)(x)?(B.push({depth:L,leafVersion:x.version||r.LEAF_VERSION_TAPSCRIPT,script:x.output}),B):(x[0]&&A(x[0],B,L+1),x[1]&&A(x[1],B,L+1),B):[]}function R(x){let B;for(const L of x)if(B=M(L,B),!B)throw new Error("No room left to insert tapleaf in tree");return B}function M(x,B,L=0){if(L>r.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(x.depth===L)return B?void 0:{output:x.script,version:x.leafVersion};if((0,e.isTapleaf)(B))return;const N=M(x,B&&B[0],L+1);if(N)return[N,B&&B[1]];const V=M(x,B&&B[1],L+1);if(V)return[B&&B[0],V]}function v(x,B,L){const N=u(x)&&F(B),V=F(x)&&u(B),G=x===B&&u(B)&&F(B);if(N||V||G)throw new Error(`Invalid arguments for Psbt.${L}. Cannot use both taproot and non-taproot fields.`)}function C(x,B,L){const N=f(x)&&F(B),V=F(x)&&f(B),G=x===B&&f(B)&&F(B);if(N||V||G)throw new Error(`Invalid arguments for Psbt.${L}. Cannot use both taproot and non-taproot fields.`)}function q(x,B,L){if(B.tapMerkleRoot){const N=(B.tapLeafScript||[]).every(G=>K(G,B.tapMerkleRoot)),V=(x.tapLeafScript||[]).every(G=>K(G,B.tapMerkleRoot));if(!N||!V)throw new Error(`Invalid arguments for Psbt.${L}. Tapleaf not part of taptree.`)}else if(x.tapMerkleRoot&&!(B.tapLeafScript||[]).every(V=>K(V,x.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${L}. Tapleaf not part of taptree.`)}function K(x,B){if(!B)return!0;const L=(0,r.tapleafHash)({output:x.script,version:x.leafVersion});return(0,r.rootHashFromPath)(x.controlBlock,L).equals(B)}function H(x,B){const L=(0,r.tapleafHash)({output:B.script,version:B.leafVersion});return(x.tapScriptSig||[]).filter(N=>N.leafHash.equals(L)).map(N=>D(B.script,N)).sort((N,V)=>V.positionInScript-N.positionInScript).map(N=>N.signature)}function D(x,B){return Object.assign({positionInScript:(0,n.pubkeyPositionInScript)(B.pubkey,x)},B)}function P(x,B,L){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((V,G)=>V.controlBlock.length-G.controlBlock.length).find(V=>$(V,x.tapScriptSig,L));if(!N)throw new Error(`Can not finalize taproot input #${B}. Signature for tapleaf script not found.`);return N}function $(x,B,L){const N=(0,r.tapleafHash)({output:x.script,version:x.leafVersion});return(!L||L.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 et}var sy;function kA(){if(sy)return go;sy=1,Object.defineProperty(go,"__esModule",{value:!0}),go.Psbt=void 0;const e=BA(),t=es(),n=Yw(),r=xh(),i=Eu(),s=Wn(),o=bc(),c=Th(),a=nn(),u=Ec(),f=NA(),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),U=new y(b,I);return q(U.__CACHE.__TX,U.__CACHE),U}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=(U,j,W,ie)=>Object.defineProperty(U,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 U=this.data.inputs.length-1,j=this.data.inputs[U];return j.nonWitnessUtxo&&ge(this.__CACHE,j,U),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:U}=this.opts,j=(0,r.toOutputScript)(b,U);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 $("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return $("__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 U=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(U))return this._finalizeTaprootInput(h,U,b,I);throw new Error(`Cannot finalize input #${h}. Not Taproot.`)}_finalizeInput(h,b,I=F){const{script:U,isP2SH:j,isP2WSH:W,isSegwit:ie}=ue(h,b,this.__CACHE);if(!U)throw new Error(`No script found for input #${h}`);M(b);const{finalScriptSig:Q,finalScriptWitness:fe}=I(h,b,U,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,U=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}=U(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=Oe(h,b,this.__CACHE),U=oe(I,h,"input",b.redeemScript||Ot(b.finalScriptSig),b.witnessScript||Be(b.finalScriptWitness)),j=U.type==="raw"?"":U.type+"-",W=re(U.meaningfulScript);return j+W}inputHasPubkey(h,b){const I=(0,n.checkForInput)(this.data.inputs,h);return ut(b,I,h,this.__CACHE)}inputHasHDKey(h,b){const I=(0,n.checkForInput)(this.data.inputs,h),U=T(b);return!!I.bip32Derivation&&I.bip32Derivation.some(U)}outputHasPubkey(h,b){const I=(0,n.checkForOutput)(this.data.outputs,h);return bt(b,I,h,this.__CACHE)}outputHasHDKey(h,b){const I=(0,n.checkForOutput)(this.data.outputs,h),U=T(b);return!!I.bip32Derivation&&I.bip32Derivation.some(U)}validateSignaturesOfAllInputs(h){return(0,n.checkForInput)(this.data.inputs,0),k(this.data.inputs.length).map(I=>this.validateSignaturesOfInput(I,h)).reduce((I,U)=>U===!0&&I,!0)}validateSignaturesOfInput(h,b,I){const U=this.data.inputs[h];return(0,f.isTaprootInput)(U)?this.validateSignaturesOfTaprootInput(h,b,I):this._validateSignaturesOfInput(h,b,I)}_validateSignaturesOfInput(h,b,I){const U=this.data.inputs[h],j=(U||{}).partialSig;if(!U||!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(ke=>ke.pubkey.equals(I)):j;if(W.length<1)throw new Error("No signatures for this pubkey");const ie=[];let Q,fe,le;for(const ke of W){const Re=a.signature.decode(ke.signature),{hash:nt,script:Ke}=le!==Re.hashType?L(h,Object.assign({},U,{sighashType:Re.hashType}),this.__CACHE,!0):{hash:Q,script:fe};le=Re.hashType,Q=nt,fe=Ke,v(ke.pubkey,Ke,"verify"),ie.push(b(ke.pubkey,nt,Re.signature))}return ie.every(ke=>ke===!0)}validateSignaturesOfTaprootInput(h,b,I){const U=this.data.inputs[h],j=(U||{}).tapKeySig,W=(U||{}).tapScriptSig;if(!U&&!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,U,this.data.inputs,I,this.__CACHE):N(h,U,this.data.inputs,this.__CACHE);if(!ie.length)throw new Error("No signatures for this pubkey");const Q=ie.find(le=>!le.leafHash);let fe=0;if(j&&Q){if(!b(Q.pubkey,Q.hash,G(j)))return!1;fe++}if(W)for(const le of W){const ke=ie.find(Re=>le.pubkey.equals(Re.pubkey));if(ke){if(!b(le.pubkey,ke.hash,G(le.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 U of k(this.data.inputs.length))try{this.signInputHD(U,h,b),I.push(!0)}catch{I.push(!1)}if(I.every(U=>U===!1))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(h,b=[u.Transaction.SIGHASH_ALL]){return new Promise((I,U)=>{if(!h||!h.publicKey||!h.fingerprint)return U(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 U(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((U,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(()=>{U()}).catch(j)})}signAllInputs(h,b){if(!h||!h.publicKey)throw new Error("Need Signer to sign input");const I=[];for(const U of k(this.data.inputs.length))try{this.signInput(U,h,b),I.push(!0)}catch{I.push(!1)}if(I.every(U=>U===!1))throw new Error("No inputs were signed");return this}signAllInputsAsync(h,b){return new Promise((I,U)=>{if(!h||!h.publicKey)return U(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 U(new Error("No inputs were signed"));I()})})}signInput(h,b,I){if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const U=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(U)?this._signTaprootInput(h,U,b,void 0,I):this._signInput(h,b,I)}signTaprootInput(h,b,I,U){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,U);throw new Error(`Input #${h} is not of type Taproot.`)}_signInput(h,b,I=[u.Transaction.SIGHASH_ALL]){const{hash:U,sighashType:j}=B(this.data.inputs,h,b.publicKey,this.__CACHE,I),W=[{pubkey:b.publicKey,signature:a.signature.encode(b.sign(U),j)}];return this.data.updateInput(h,{partialSig:W}),this}_signTaprootInput(h,b,I,U,j=[u.Transaction.SIGHASH_DEFAULT]){const W=this.checkTaprootHashesForSig(h,b,I,U,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 U=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(U)?this._signTaprootInputAsync(h,U,b,void 0,I):this._signInputAsync(h,b,I)})}signTaprootInputAsync(h,b,I,U){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,U);throw new Error(`Input #${h} is not of type Taproot.`)})}_signInputAsync(h,b,I=[u.Transaction.SIGHASH_ALL]){const{hash:U,sighashType:j}=B(this.data.inputs,h,b.publicKey,this.__CACHE,I);return Promise.resolve(b.sign(U)).then(W=>{const ie=[{pubkey:b.publicKey,signature:a.signature.encode(W,j)}];this.data.updateInput(h,{partialSig:ie})})}async _signTaprootInputAsync(h,b,I,U,j=[u.Transaction.SIGHASH_DEFAULT]){const W=this.checkTaprootHashesForSig(h,b,I,U,j),ie=[],Q=W.filter(le=>!le.leafHash)[0];if(Q){const le=Promise.resolve(I.signSchnorr(Q.hash)).then(ke=>({tapKeySig:(0,f.serializeTaprootSignature)(ke,b.sighashType)}));ie.push(le)}const fe=W.filter(le=>!!le.leafHash);if(fe.length){const le=fe.map(ke=>Promise.resolve(I.signSchnorr(ke.hash)).then(Re=>({tapScriptSig:[{pubkey:(0,f.toXOnly)(I.publicKey),signature:(0,f.serializeTaprootSignature)(Re,b.sighashType),leafHash:ke.leafHash}]})));ie.push(...le)}return Promise.all(ie).then(le=>{le.forEach(ke=>this.data.updateInput(h,ke))})}checkTaprootHashesForSig(h,b,I,U,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,U,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 S(this.__CACHE),this.data.toBuffer()}toHex(){return S(this.__CACHE),this.data.toHex()}toBase64(){return S(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&&ge(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}}go.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),C(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 _(1,p.partialSig);case"multisig":const I=o.p2ms({output:h});return _(I.m,p.partialSig,I.pubkeys);default:return!1}}function S(p){if(p.__UNSAFE_SIGN_NONSEGWIT!==!1)throw new Error("Not BIP174 compliant, can not export")}function _(p,h,b){if(!h)return!1;let I;if(b?I=b.map(U=>{const j=gn(U);return h.find(W=>W.pubkey.equals(j))}).filter(U=>!!U):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(),U=h.__EXTRACTED_TX.virtualSize(),j=I*U;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 ${U} 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:U}=a.signature.decode(I.signature);if(b!==U)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 C(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 q(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,U,j)=>{const W=p({redeem:{output:U}}).output;if(!I.equals(W))throw new Error(`${h} for ${j} #${b} doesn't match the scriptPubKey in the prevout`)}}const D=H(o.p2sh,"Redeem script"),P=H(o.p2wsh,"Witness script");function $(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 U,j=!0;if(I.__EXTRACTED_TX?(U=I.__EXTRACTED_TX,j=!1):U=I.__TX.clone(),J(b,U,I,j),p==="__FEE_RATE")return I.__FEE_RATE;if(p==="__FEE")return I.__FEE}function F(p,h,b,I,U,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,U,j)}function x(p,h,b,I,U,j){let W,ie;const Q=ce(p,h,b),fe=j?o.p2wsh({redeem:Q}):null,le=U?o.p2sh({redeem:fe||Q}):null;return I?(fe?ie=(0,l.witnessStackToScriptWitness)(fe.witness):ie=(0,l.witnessStackToScriptWitness)(Q.witness),le&&(W=le.input)):le?W=le.input:W=Q.input,{finalScriptSig:W,finalScriptWitness:ie}}function B(p,h,b,I,U){const j=(0,n.checkForInput)(p,h),{hash:W,sighashType:ie,script:Q}=L(h,j,I,!1,U);return v(b,Q,"sign"),{hash:W,sighashType:ie}}function L(p,h,b,I,U){const j=b.__TX,W=h.sighashType||u.Transaction.SIGHASH_ALL;Y(W,U);let ie,Q;if(h.nonWitnessUtxo){const ke=he(b,h,p),Re=j.ins[p].hash,nt=ke.getHash();if(!Re.equals(nt))throw new Error(`Non-witness UTXO hash for input #${p} doesn't match the hash specified in the prevout`);const Ke=j.ins[p].index;Q=ke.outs[Ke]}else if(h.witnessUtxo)Q=h.witnessUtxo;else throw new Error("Need a Utxo input item for signing");const{meaningfulScript:fe,type:le}=oe(Q.script,p,"input",h.redeemScript,h.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(le)>=0)ie=j.hashForWitnessV0(p,fe,Q.value,W);else if((0,l.isP2WPKH)(fe)){const ke=o.p2pkh({hash:fe.slice(2)}).output;ie=j.hashForWitnessV0(p,ke,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}),ur}var gf={},so={},mf={},fr={},D0;function jw(){if(D0)return fr;D0=1,Object.defineProperty(fr,"__esModule",{value:!0}),fr.encode=fr.decode=fr.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))}fr.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)}}fr.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 fr.encode=n,fr}var Ei={},$0;function bh(){if($0)return Ei;$0=1,Object.defineProperty(Ei,"__esModule",{value:!0}),Ei.REVERSE_OPS=Ei.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};Ei.OPS=e;const t={};Ei.REVERSE_OPS=t;for(const n of Object.keys(e)){const r=e[n];t[r]=n}return Ei}var lr={},j0;function L8(){if(j0)return lr;j0=1,Object.defineProperty(lr,"__esModule",{value:!0}),lr.decode=lr.encode=lr.encodingLength=void 0;const e=bh();function t(i){return i<e.OPS.OP_PUSHDATA1?1:i<=255?2:i<=65535?3:5}lr.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}lr.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 lr.decode=r,lr}var _i={},K0;function q8(){if(K0)return _i;K0=1,Object.defineProperty(_i,"__esModule",{value:!0}),_i.encode=_i.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}_i.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 _i.encode=n,_i}var Si={},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 Kw(){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 S='" of type ';return y==="key"&&(S='" with key type '),o('property "'+s(g)+S+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 V8(){if(X0)return _f;X0=1;var e=Eh(),t=Kw();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(C){if(!A(C))return!1;if(C.length===R)return!0;throw t.tfCustomError(M+"(Length: "+R+")",M+"(Length: "+C.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(C,q){return M(C,q)&&C>A&&C<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 S(A){return(A&65535)===A}function _(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:S,UInt32:_,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 D8(){if(z0)return Sf;z0=1;var e=Kw(),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,S){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(_,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,S){if(!t.Object(E)||t.Nil(E))return!1;for(var _ in E){try{g&&u(g,_,S)}catch(T){throw s(T,_,"key")}try{var w=E[_];u(y,w,S)}catch(T){throw s(T,_)}}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(S)||t.Nil(S))return!1;var w;try{for(w in g){var T=g[w],O=S[w];u(T,O,_)}}catch(A){throw s(A,w)}if(_){for(w in S)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(S){try{return u(S,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(S){try{return u(S,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(S,m[_],E)}catch(w){throw s(w,_)}})}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=V8();for(f in l)u[f]=l[f];return u.compile=a,u.TfTypeError=r,u.TfPropertyTypeError=i,Sf=u,Sf}var Y0;function zt(){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=ec();e.typeforce=D8();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 $8(){if(Z0)return Si;Z0=1,Object.defineProperty(Si,"__esModule",{value:!0}),Si.encode=Si.decode=void 0;const e=jw(),t=rn(),n=zt(),{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}}Si.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 Si.encode=a,Si}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=jw(),n=bh();Object.defineProperty(e,"OPS",{enumerable:!0,get:function(){return n.OPS}});const r=L8(),i=q8(),s=$8(),o=zt(),{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 S(v){if(g(v))return v;c(o.Array,v);const C=v.reduce((H,D)=>E(D)?D.length===1&&y(D)!==void 0?H+1:H+r.encodingLength(D.length)+D.length:H+1,0),q=Buffer.allocUnsafe(C);let K=0;if(v.forEach(H=>{if(E(H)){const D=y(H);if(D!==void 0){q.writeUInt8(D,K),K+=1;return}K+=r.encode(q,H.length,K),H.copy(q,K),K+=H.length}else q.writeUInt8(H,K),K+=1}),K!==q.length)throw new Error("Could not decode chunks");return q}e.compile=S;function _(v){if(m(v))return v;c(o.Buffer,v);const C=[];let q=0;for(;q<v.length;){const K=v[q];if(K>n.OPS.OP_0&&K<=n.OPS.OP_PUSHDATA4){const H=r.decode(v,q);if(H===null||(q+=H.size,q+H.number>v.length))return null;const D=v.slice(q,q+H.number);q+=H.number;const P=y(D);P!==void 0?C.push(P):C.push(D)}else C.push(K),q+=1}return C}e.decompile=_;function w(v){if(g(v)&&(v=_(v)),!v)throw new Error("Could not convert invalid chunks to ASM");return v.map(C=>{if(E(C)){const q=y(C);if(q===void 0)return C.toString("hex");C=q}return n.REVERSE_OPS[C]}).join(" ")}e.toASM=w;function T(v){return c(o.String,v),S(v.split(" ").map(C=>n.OPS[C]!==void 0?n.OPS[C]:(c(o.Hex,C),Buffer.from(C,"hex"))))}e.fromASM=T;function O(v){return v=_(v),c(l,v),v.map(C=>E(C)?C:C===n.OPS.OP_0?Buffer.allocUnsafe(0):i.encode(C-a))}e.toStack=O;function A(v){return o.isPoint(v)}e.isCanonicalPubKey=A;function R(v){const C=v&-129;return C>0&&C<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 Ti={},Q0;function yi(){if(Q0)return Ti;Q0=1,Object.defineProperty(Ti,"__esModule",{value:!0}),Ti.value=Ti.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})}})}Ti.prop=e;function t(n){let r;return()=>(r!==void 0||(r=n()),r)}return Ti.value=t,Ti}var ep;function j8(){if(ep)return so;ep=1,Object.defineProperty(so,"__esModule",{value:!0}),so.p2data=void 0;const e=Wn(),t=rn(),n=zt(),r=yi(),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 K8(){if(tp)return oo;tp=1,Object.defineProperty(oo,"__esModule",{value:!0}),oo.p2ms=void 0;const e=Wn(),t=rn(),n=zt(),r=yi(),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 G8(){if(np)return co;np=1,Object.defineProperty(co,"__esModule",{value:!0}),co.p2pk=void 0;const e=Wn(),t=rn(),n=zt(),r=yi(),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={},xi={},Jt={},rp;function Gw(){if(rp)return Jt;rp=1,Object.defineProperty(Jt,"__esModule",{value:!0}),Jt.ripemd160=Jt.RIPEMD160=Jt.md5=Jt.MD5=Jt.sha1=Jt.SHA1=void 0;const e=ky(),t=ai(),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:C,C:q,D:K,E:H}=this;return[v,C,q,K,H]}set(v,C,q,K,H){this.A=v|0,this.B=C|0,this.C=q|0,this.D=K|0,this.E=H|0}process(v,C){for(let $=0;$<16;$++,C+=4)r[$]=v.getUint32(C,!1);for(let $=16;$<80;$++)r[$]=(0,t.rotl)(r[$-3]^r[$-8]^r[$-14]^r[$-16],1);let{A:q,B:K,C:H,D,E:P}=this;for(let $=0;$<80;$++){let F,x;$<20?(F=(0,e.Chi)(K,H,D),x=1518500249):$<40?(F=K^H^D,x=1859775393):$<60?(F=(0,e.Maj)(K,H,D),x=2400959708):(F=K^H^D,x=3395469782);const B=(0,t.rotl)(q,5)+F+P+x+r[$]|0;P=D,D=H,H=(0,t.rotl)(K,30),K=q,q=B}q=q+this.A|0,K=K+this.B|0,H=H+this.C|0,D=D+this.D|0,P=P+this.E|0,this.set(q,K,H,D,P)}roundClean(){(0,t.clean)(r)}destroy(){this.set(0,0,0,0,0),(0,t.clean)(this.buffer)}}Jt.SHA1=i,Jt.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:C,C:q,D:K}=this;return[v,C,q,K]}set(v,C,q,K){this.A=v|0,this.B=C|0,this.C=q|0,this.D=K|0}process(v,C){for(let P=0;P<16;P++,C+=4)a[P]=v.getUint32(C,!0);let{A:q,B:K,C:H,D}=this;for(let P=0;P<64;P++){let $,F,x;P<16?($=(0,e.Chi)(K,H,D),F=P,x=[7,12,17,22]):P<32?($=(0,e.Chi)(D,K,H),F=(5*P+1)%16,x=[5,9,14,20]):P<48?($=K^H^D,F=(3*P+5)%16,x=[4,11,16,23]):($=H^(K|~D),F=7*P%16,x=[6,10,15,21]),$=$+q+o[P]+a[F],q=D,D=H,H=K,K=K+(0,t.rotl)($,x[P%4])}q=q+this.A|0,K=K+this.B|0,H=H+this.C|0,D=D+this.D|0,this.set(q,K,H,D)}roundClean(){(0,t.clean)(a)}destroy(){this.set(0,0,0,0),(0,t.clean)(this.buffer)}}Jt.MD5=u,Jt.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 C=[[l],[d]];for(let q=0;q<4;q++)for(let K of C)K.push(K[q].map(H=>f[H]));return C})(),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)),S=g.map((M,v)=>M.map(C=>E[v][C])),_=m.map((M,v)=>M.map(C=>E[v][C])),w=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),T=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function O(M,v,C,q){return M===0?v^C^q:M===1?v&C|~v&q:M===2?(v|~C)^q:M===3?v&q|C&~q:v^(C|~q)}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:C,h2:q,h3:K,h4:H}=this;return[v,C,q,K,H]}set(v,C,q,K,H){this.h0=v|0,this.h1=C|0,this.h2=q|0,this.h3=K|0,this.h4=H|0}process(v,C){for(let N=0;N<16;N++,C+=4)A[N]=v.getUint32(C,!0);let q=this.h0|0,K=q,H=this.h1|0,D=H,P=this.h2|0,$=P,F=this.h3|0,x=F,B=this.h4|0,L=B;for(let N=0;N<5;N++){const V=4-N,G=w[N],X=T[N],Y=g[N],ce=m[N],ue=S[N],te=_[N];for(let Z=0;Z<16;Z++){const ae=(0,t.rotl)(q+O(N,H,P,F)+A[Y[Z]]+G,ue[Z])+B|0;q=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(V,D,$,x)+A[ce[Z]]+X,te[Z])+L|0;K=L,L=x,x=(0,t.rotl)($,10)|0,$=D,D=ae}}this.set(this.h1+P+x|0,this.h2+F+L|0,this.h3+B+K|0,this.h4+q+D|0,this.h0+H+$|0)}roundClean(){(0,t.clean)(A)}destroy(){this.destroyed=!0,(0,t.clean)(this.buffer),this.set(0,0,0,0,0)}}return Jt.RIPEMD160=R,Jt.ripemd160=(0,t.createHasher)(()=>new R),Jt}var ip;function W8(){if(ip)return xi;ip=1,Object.defineProperty(xi,"__esModule",{value:!0}),xi.ripemd160=xi.RIPEMD160=void 0;const e=Gw();return xi.RIPEMD160=e.RIPEMD160,xi.ripemd160=e.ripemd160,xi}var Ai={},sp;function X8(){if(sp)return Ai;sp=1,Object.defineProperty(Ai,"__esModule",{value:!0}),Ai.sha1=Ai.SHA1=void 0;const e=Gw();return Ai.SHA1=e.SHA1,Ai.sha1=e.sha1,Ai}var Cn={},op;function Ww(){if(op)return Cn;op=1,Object.defineProperty(Cn,"__esModule",{value:!0}),Cn.sha224=Cn.SHA224=Cn.sha256=Cn.SHA256=void 0;const e=Py();return Cn.SHA256=e.SHA256,Cn.sha256=e.sha256,Cn.SHA224=e.SHA224,Cn.sha224=e.sha224,Cn}var cp;function Rr(){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=W8(),n=X8(),r=Ww();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 z8(){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,S=0,_=g.length;S!==_&&g[S]===0;)S++,m++;for(var w=(_-S)*f+1>>>0,T=new Uint8Array(w);S!==_;){for(var O=g[S],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,S++}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,S=0;g[m]===a;)E++,m++;for(var _=(g.length-m)*u+1>>>0,w=new Uint8Array(_);g[m];){var T=g.charCodeAt(m);if(T>255)return;var O=n[T];if(O===255)return;for(var A=0,R=_-1;(O!==0||A<S)&&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");S=A,m++}for(var M=_-S;M!==_&&w[M]===0;)M++;for(var v=new Uint8Array(E+(_-M)),C=E;M!==_;)v[C++]=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 Y8(){return up||(up=1,Af=z8()("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")),Af}var vf,fp;function Z8(){if(fp)return vf;fp=1;var e=Y8();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}=Ww(),t=Z8();function n(r){return e(e(r))}return If=t(n),If}var hp;function J8(){if(hp)return ao;hp=1,Object.defineProperty(ao,"__esModule",{value:!0}),ao.p2pkh=void 0;const e=Rr(),t=Wn(),n=rn(),r=zt(),i=yi(),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 Q8(){if(dp)return uo;dp=1,Object.defineProperty(uo,"__esModule",{value:!0}),uo.p2sh=void 0;const e=Rr(),t=Wn(),n=rn(),r=zt(),i=yi(),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),S=m.slice(1);return{version:E,hash:S}}),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 S=a.output.slice(2,22);if(m.length>0&&!m.equals(S))throw new TypeError("Hash mismatch");m=S}const E=S=>{if(S.output){const _=n.decompile(S.output);if(!_||_.length<1)throw new TypeError("Redeem.output too short");if(S.output.byteLength>520)throw new TypeError("Redeem.output unspendable if larger than 520 bytes");if(n.countNonPushOnlyOPs(_)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const w=e.hash160(S.output);if(m.length>0&&!m.equals(w))throw new TypeError("Hash mismatch");m=w}if(S.input){const _=S.input.length>0,w=S.witness&&S.witness.length>0;if(!_&&!w)throw new TypeError("Empty input");if(_&&w)throw new TypeError("Input and witness provided");if(_){const T=n.decompile(S.input);if(!n.isPushOnly(T))throw new TypeError("Non push-only scriptSig")}}};if(a.input){const S=y();if(!S||S.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 S=g();if(a.redeem.output&&!a.redeem.output.equals(S.output))throw new TypeError("Redeem.output mismatch");if(a.redeem.input&&!a.redeem.input.equals(S.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 eA(){if(pp)return fo;pp=1,Object.defineProperty(fo,"__esModule",{value:!0}),fo.p2wpkh=void 0;const e=Rr(),t=Wn(),n=rn(),r=zt(),i=yi(),s=cc(),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 tA(){if(yp)return lo;yp=1,Object.defineProperty(lo,"__esModule",{value:!0}),lo.p2wsh=void 0;const e=Rr(),t=Wn(),n=rn(),r=zt(),i=yi(),s=cc(),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),S=E.words.shift(),_=s.bech32.fromWords(E.words);return{version:S,prefix:E.prefix,data:Buffer.from(_)}}),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 S=f.output.slice(2);if(E.length>0&&!E.equals(S))throw new TypeError("Hash mismatch");E=S}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 S=n.decompile(f.redeem.output);if(!S||S.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(S)>201)throw new TypeError("Redeem.output unspendable with more than 201 non-push ops");const _=e.sha256(f.redeem.output);if(E.length>0&&!E.equals(_))throw new TypeError("Hash mismatch");E=_}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 S=f.witness[f.witness.length-1];if(f.redeem&&f.redeem.output&&!f.redeem.output.equals(S))throw new TypeError("Witness and redeem.output mismatch");if(f.witness.some(a)||(n.decompile(S)||[]).some(a))throw new TypeError("Witness contains uncompressed pubkey")}}return Object.assign(m,f)}return lo.p2wsh=u,lo}var ho={},vi={},gp;function Sh(){if(gp)return vi;gp=1,Object.defineProperty(vi,"__esModule",{value:!0}),vi.getEccLib=vi.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}vi.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}vi.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 vi}var Of={},Pt={},Hc={exports:{}};/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */var mp;function nA(){return mp||(mp=1,(function(e,t){var n=ec(),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)}})(Hc,Hc.exports)),Hc.exports}var Bf,wp;function rA(){if(wp)return Bf;wp=1;var e=nA().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 Pt;bp=1,Object.defineProperty(Pt,"__esModule",{value:!0}),Pt.BufferReader=Pt.BufferWriter=Pt.cloneBuffer=Pt.reverseBuffer=Pt.writeUInt64LE=Pt.readUInt64LE=Pt.varuint=void 0;const e=zt(),{typeforce:t}=e,n=rA();Pt.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}Pt.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}Pt.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}Pt.reverseBuffer=o;function c(f){const l=Buffer.allocUnsafe(f.length);return f.copy(l),l}Pt.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}`)}}Pt.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 Pt.BufferReader=u,Pt}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=ec(),n=Sh(),r=Rr(),i=Eu(),s=zt();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 S=(m.length-33)/32;let _=E;for(let w=0;w<S;w++){const T=m.slice(33+32*w,65+32*w);_.compare(T)<0?_=y(_,T):_=y(T,_)}return _}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(S.hash,_.hash),left:S,right:_}}e.toHashTree=a;function u(m,E){if(o(m)){const S=u(m.left,E);if(S!==void 0)return[...S,m.right.hash];const _=u(m.right,E);if(_!==void 0)return[..._,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 S=l(m,E),_=(0,n.getEccLib)().xOnlyPointAddTweak(m,S);return!_||_.xOnlyPubkey===null?null:{parity:_.parity,x:t.Buffer.from(_.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),S=t.Buffer.allocUnsafe(E);return i.varuint.encode(m.length,S),t.Buffer.concat([S,m])}})(Of)),Of}var _p;function iA(){if(_p)return ho;_p=1,Object.defineProperty(ho,"__esModule",{value:!0}),ho.p2tr=void 0;const e=ec(),t=Wn(),n=rn(),r=zt(),i=Sh(),s=Th(),o=yi(),c=cc(),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()}),S=o.value(()=>{if(y.scriptTree)return(0,s.toHashTree)(y.scriptTree);if(y.hash)return{hash:y.hash}}),_=y.network||t.bitcoin,w={name:"p2tr",network:_};if(o.prop(w,"address",()=>{if(!w.pubkey)return;const T=c.bech32m.toWords(w.pubkey);return T.unshift(f),c.bech32m.encode(_.bech32,T)}),o.prop(w,"hash",()=>{const T=S();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=S();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(_&&_.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=S();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 C=R[0]&r.TAPLEAF_VERSION_MASK,q=A[A.length-2],K=(0,s.tapleafHash)({output:q,version:C}),H=(0,s.rootHashFromPath)(R,K),D=(0,s.tweakKey)(v,H);if(!D)throw new TypeError("Invalid outputKey for p2tr witness");if(T.length&&!T.equals(D.x))throw new TypeError("Pubkey mismatch for p2tr witness");if(D.parity!==(R[0]&1))throw new Error("Incorrect parity")}}return Object.assign(w,y)}return ho.p2tr=d,ho}var Sp;function bc(){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=j8();Object.defineProperty(e,"embed",{enumerable:!0,get:function(){return t.p2data}});const n=K8();Object.defineProperty(e,"p2ms",{enumerable:!0,get:function(){return n.p2ms}});const r=G8();Object.defineProperty(e,"p2pk",{enumerable:!0,get:function(){return r.p2pk}});const i=J8();Object.defineProperty(e,"p2pkh",{enumerable:!0,get:function(){return i.p2pkh}});const s=Q8();Object.defineProperty(e,"p2sh",{enumerable:!0,get:function(){return s.p2sh}});const o=eA();Object.defineProperty(e,"p2wpkh",{enumerable:!0,get:function(){return o.p2wpkh}});const c=tA();Object.defineProperty(e,"p2wsh",{enumerable:!0,get:function(){return c.p2wsh}});const a=iA();Object.defineProperty(e,"p2tr",{enumerable:!0,get:function(){return a.p2tr}})})(gf)),gf}var Tp;function xh(){if(Tp)return Zt;Tp=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.toOutputScript=Zt.fromOutputScript=Zt.toBech32=Zt.toBase58Check=Zt.fromBech32=Zt.fromBase58Check=void 0;const e=Wn(),t=bc(),n=rn(),r=zt(),i=cc(),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}}Zt.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)}}Zt.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)}Zt.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)}Zt.toBech32=E;function S(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")}Zt.fromOutputScript=S;function _(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 Zt.toOutputScript=_,Zt}var po={},yo={},xp;function sA(){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 Ec(){if(Ap)return go;Ap=1,Object.defineProperty(go,"__esModule",{value:!0}),go.Transaction=void 0;const e=Eu(),t=Rr(),n=rn(),r=rn(),i=zt(),{typeforce:s}=i;function o(E){const S=E.length;return e.varuint.encodingLength(S)+S}function c(E){const S=E.length;return e.varuint.encodingLength(S)+E.reduce((_,w)=>_+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(S),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 C=0;C<M;++C)T.ins.push({hash:w.readSlice(32),index:w.readUInt32(),script:w.readVarSlice(),sequence:w.readUInt32(),witness:u});const v=w.readVarInt();for(let C=0;C<v;++C)T.outs.push({value:w.readUInt64(),script:w.readVarSlice()});if(R){for(let C=0;C<M;++C)T.ins[C].witness=w.readVector();if(!T.hasWitnesses())throw new Error("Transaction has superfluous witness data")}if(T.locktime=w.readUInt32(),_)return T;if(w.offset!==S.length)throw new Error("Transaction has unexpected data");return T}static fromHex(S){return m.fromBuffer(Buffer.from(S,"hex"),!1)}static isCoinbaseHash(S){s(i.Hash256bit,S);for(let _=0;_<32;++_)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:S,index:_,script:T||a,sequence:w,witness:u})-1}addOutput(S,_){return s(i.tuple(i.Buffer,i.Satoshi),arguments),this.outs.push({script:S,value:_})-1}hasWitnesses(){return this.ins.some(S=>S.witness.length!==0)}stripWitnesses(){this.ins.forEach(S=>{S.witness=u})}weight(){const S=this.byteLength(!1),_=this.byteLength(!0);return S*3+_}virtualSize(){return Math.ceil(this.weight()/4)}byteLength(S=!0){const _=S&&this.hasWitnesses();return(_?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)+(_?this.ins.reduce((w,T)=>w+c(T.witness),0):0)}clone(){const S=new m;return S.version=this.version,S.locktime=this.locktime,S.ins=this.ins.map(_=>({hash:_.hash,index:_.index,script:_.script,sequence:_.sequence,witness:_.witness})),S.outs=this.outs.map(_=>({script:_.script,value:_.value})),S}hashForSignature(S,_,w){if(s(i.tuple(i.UInt32,i.Buffer,i.Number),arguments),S>=this.ins.length)return l;const T=n.compile(n.decompile(_).filter(R=>R!==r.OPS.OP_CODESEPARATOR)),O=this.clone();if((w&31)===m.SIGHASH_NONE)O.outs=[],O.ins.forEach((R,M)=>{M!==S&&(R.sequence=0)});else if((w&31)===m.SIGHASH_SINGLE){if(S>=this.outs.length)return l;O.outs.length=S+1;for(let R=0;R<S;R++)O.outs[R]=y;O.ins.forEach((R,M)=>{M!==S&&(R.sequence=0)})}w&m.SIGHASH_ANYONECANPAY?(O.ins=[O.ins[S]],O.ins[0].script=T):(O.ins.forEach(R=>{R.script=a}),O.ins[S].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||_.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,C=R===m.SIGHASH_NONE,q=R===m.SIGHASH_SINGLE;let K=a,H=a,D=a,P=a,$=a;if(!v){let L=e.BufferWriter.withCapacity(36*this.ins.length);this.ins.forEach(N=>{L.writeSlice(N.hash),L.writeUInt32(N.index)}),K=t.sha256(L.end()),L=e.BufferWriter.withCapacity(8*this.ins.length),w.forEach(N=>L.writeUInt64(N)),H=t.sha256(L.end()),L=e.BufferWriter.withCapacity(_.map(o).reduce((N,V)=>N+V)),_.forEach(N=>L.writeVarSlice(N)),D=t.sha256(L.end()),L=e.BufferWriter.withCapacity(4*this.ins.length),this.ins.forEach(N=>L.writeUInt32(N.sequence)),P=t.sha256(L.end())}if(C||q){if(q&&S<this.outs.length){const L=this.outs[S],N=e.BufferWriter.withCapacity(8+o(L.script));N.writeUInt64(L.value),N.writeVarSlice(L.script),$=t.sha256(N.end())}}else{const L=this.outs.map(V=>8+o(V.script)).reduce((V,G)=>V+G),N=e.BufferWriter.withCapacity(L);this.outs.forEach(V=>{N.writeUInt64(V.value),N.writeVarSlice(V.script)}),$=t.sha256(N.end())}const F=(O?2:0)+(A?1:0),x=174-(v?49:0)-(C?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(D),B.writeSlice(P),C||q||B.writeSlice($),B.writeUInt8(F),v){const L=this.ins[S];B.writeSlice(L.hash),B.writeUInt32(L.index),B.writeUInt64(w[S]),B.writeVarSlice(_[S]),B.writeUInt32(L.sequence)}else B.writeUInt32(S);if(A){const L=e.BufferWriter.withCapacity(o(A));L.writeVarSlice(A),B.writeSlice(t.sha256(L.end()))}return q&&B.writeSlice($),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(q=>{A.writeSlice(q.hash),A.writeUInt32(q.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(q=>{A.writeUInt32(q.sequence)}),v=t.hash256(O)),(T&31)!==m.SIGHASH_SINGLE&&(T&31)!==m.SIGHASH_NONE){const q=this.outs.reduce((K,H)=>K+8+o(H.script),0);O=Buffer.allocUnsafe(q),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&&S<this.outs.length){const q=this.outs[S];O=Buffer.allocUnsafe(8+o(q.script)),A=new e.BufferWriter(O,0),A.writeUInt64(q.value),A.writeVarSlice(q.script),R=t.hash256(O)}O=Buffer.allocUnsafe(156+o(_)),A=new e.BufferWriter(O,0);const C=this.ins[S];return A.writeInt32(this.version),A.writeSlice(M),A.writeSlice(v),A.writeSlice(C.hash),A.writeUInt32(C.index),A.writeVarSlice(_),A.writeUInt64(w),A.writeUInt32(C.sequence),A.writeSlice(R),A.writeUInt32(this.locktime),A.writeUInt32(T),t.hash256(O)}getHash(S){return S&&this.isCoinbase()?Buffer.alloc(32,0):t.hash256(this.__toBuffer(void 0,void 0,S))}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[S].script=_}setWitness(S,_){s(i.tuple(i.Number,[i.Buffer]),arguments),this.ins[S].witness=_}__toBuffer(S,_,w=!1){S||(S=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),_!==void 0?S.slice(_,T.offset):S}}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 oA(){if(vp)return po;vp=1,Object.defineProperty(po,"__esModule",{value:!0}),po.Block=void 0;const e=Eu(),t=Rr(),n=sA(),r=Ec(),i=zt(),{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 _=r.Transaction.fromBuffer(y.buffer.slice(y.offset),!0);return y.offset+=_.byteLength(),_},E=y.readVarInt();g.transactions=[];for(let _=0;_<E;++_){const w=m();g.transactions.push(w)}const S=g.getWitnessCommit();return S&&(g.witnessCommit=S),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={},Fc={},Mc={},Nf={},os={},cs={},kf={},Ip;function Lt(){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 Dr={},Op;function cA(){if(Op)return Dr;Op=1,Object.defineProperty(Dr,"__esModule",{value:!0});const e=Lt(),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}Dr.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}}Dr.encode=r,Dr.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+'?)*$/)}Dr.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 Dr.canAddToArray=s,Dr}var Lc={},Bp;function aA(){if(Bp)return Lc;Bp=1,Object.defineProperty(Lc,"__esModule",{value:!0});const e=Lt();function t(n){return{key:Buffer.from([e.GlobalTypes.UNSIGNED_TX]),value:n.toBuffer()}}return Lc.encode=t,Lc}var $r={},Np;function uA(){if(Np)return $r;Np=1,Object.defineProperty($r,"__esModule",{value:!0});const e=Lt();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}$r.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.FINAL_SCRIPTSIG]),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.finalScriptSig===void 0}return $r.canAdd=i,$r}var jr={},kp;function fA(){if(kp)return jr;kp=1,Object.defineProperty(jr,"__esModule",{value:!0});const e=Lt();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}jr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.FINAL_SCRIPTWITNESS]),value:s}}jr.encode=n,jr.expected="Buffer";function r(s){return Buffer.isBuffer(s)}jr.check=r;function i(s,o){return!!s&&!!o&&s.finalScriptWitness===void 0}return jr.canAdd=i,jr}var Kr={},Pp;function lA(){if(Pp)return Kr;Pp=1,Object.defineProperty(Kr,"__esModule",{value:!0});const e=Lt();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}Kr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.NON_WITNESS_UTXO]),value:s}}Kr.encode=n,Kr.expected="Buffer";function r(s){return Buffer.isBuffer(s)}Kr.check=r;function i(s,o){return!!s&&!!o&&s.nonWitnessUtxo===void 0}return Kr.canAdd=i,Kr}var Gr={},Rp;function hA(){if(Rp)return Gr;Rp=1,Object.defineProperty(Gr,"__esModule",{value:!0});const e=Lt();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}}Gr.decode=t;function n(o){const c=Buffer.from([e.InputTypes.PARTIAL_SIG]);return{key:Buffer.concat([c,o.pubkey]),value:o.signature}}Gr.encode=n,Gr.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)}Gr.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 Gr.canAddToArray=s,Gr}var Wr={},Cp;function dA(){if(Cp)return Wr;Cp=1,Object.defineProperty(Wr,"__esModule",{value:!0});const e=Lt();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")}Wr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.POR_COMMITMENT]),value:Buffer.from(s,"utf8")}}Wr.encode=n,Wr.expected="string";function r(s){return typeof s=="string"}Wr.check=r;function i(s,o){return!!s&&!!o&&s.porCommitment===void 0}return Wr.canAdd=i,Wr}var Xr={},Up;function pA(){if(Up)return Xr;Up=1,Object.defineProperty(Xr,"__esModule",{value:!0});const e=Lt();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)}Xr.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}}Xr.encode=n,Xr.expected="number";function r(s){return typeof s=="number"}Xr.check=r;function i(s,o){return!!s&&!!o&&s.sighashType===void 0}return Xr.canAdd=i,Xr}var zr={},Hp;function yA(){if(Hp)return zr;Hp=1,Object.defineProperty(zr,"__esModule",{value:!0});const e=Lt();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}zr.decode=t;function n(s){return{key:Buffer.from([e.InputTypes.TAP_KEY_SIG]),value:s}}zr.encode=n,zr.expected="Buffer";function r(s){return Buffer.isBuffer(s)&&(s.length===64||s.length===65)}zr.check=r;function i(s,o){return!!s&&!!o&&s.tapKeySig===void 0}return zr.canAdd=i,zr}var Yr={},Fp;function gA(){if(Fp)return Yr;Fp=1,Object.defineProperty(Yr,"__esModule",{value:!0});const e=Lt();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}}Yr.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])}}Yr.encode=n,Yr.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)}Yr.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 Yr.canAddToArray=i,Yr}var Zr={},Mp;function mA(){if(Mp)return Zr;Mp=1,Object.defineProperty(Zr,"__esModule",{value:!0});const e=Lt();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 Jr={},Lp;function wA(){if(Lp)return Jr;Lp=1,Object.defineProperty(Jr,"__esModule",{value:!0});const e=Lt();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}}Jr.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}}Jr.encode=n,Jr.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)}Jr.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 Jr.canAddToArray=i,Jr}var Qr={},hr={},as={},qp;function es(){if(qp)return as;qp=1,Object.defineProperty(as,"__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}as.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}}as.decode=r;function i(s){return t(s),s<253?1:s<=65535?3:s<=4294967295?5:9}return as.encodingLength=i,as}var Vp;function Ah(){if(Vp)return hr;Vp=1,Object.defineProperty(hr,"__esModule",{value:!0});const e=es();hr.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}hr.reverseBuffer=t;function n(c){const a=c.map(r);return a.push(Buffer.from([0])),Buffer.concat(a)}hr.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}hr.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}hr.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 hr.writeUInt64LE=o,hr}var Dp;function bA(){if(Dp)return Qr;Dp=1,Object.defineProperty(Qr,"__esModule",{value:!0});const e=Lt(),t=Ah(),n=es();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}}Qr.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}}Qr.encode=i,Qr.expected="{ script: Buffer; value: number; }";function s(c){return Buffer.isBuffer(c.script)&&typeof c.value=="number"}Qr.check=s;function o(c,a){return!!c&&!!a&&c.witnessUtxo===void 0}return Qr.canAdd=o,Qr}var ei={},$p;function EA(){if($p)return ei;$p=1,Object.defineProperty(ei,"__esModule",{value:!0});const e=Lt(),t=es();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}}ei.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)}}ei.encode=r,ei.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))}ei.check=i;function s(o,c){return!!o&&!!c&&o.tapTree===void 0}return ei.canAdd=s,ei}var qc={},jp;function Xw(){if(jp)return qc;jp=1,Object.defineProperty(qc,"__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 S=E.slice(-1)==="'";let _=2147483647&parseInt(S?E.slice(0,-1):E,10);S&&(_+=2147483648),g.writeUInt32LE(_,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 qc.makeConverter=n,qc}var Vc={},Kp;function _A(){if(Kp)return Vc;Kp=1,Object.defineProperty(Vc,"__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 Vc.makeChecker=e,Vc}var Dc={},Gp;function SA(){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 $c={},Wp;function TA(){if(Wp)return $c;Wp=1,Object.defineProperty($c,"__esModule",{value:!0});const e=es(),t=Xw(),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 $c.makeConverter=r,$c}var jc={},Xp;function xA(){if(Xp)return jc;Xp=1,Object.defineProperty(jc,"__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 jc.makeConverter=e,jc}var Kc={},zp;function AA(){if(zp)return Kc;zp=1,Object.defineProperty(Kc,"__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 Kc.makeConverter=e,Kc}var Yp;function vh(){if(Yp)return cs;Yp=1,Object.defineProperty(cs,"__esModule",{value:!0});const e=Lt(),t=cA(),n=aA(),r=uA(),i=fA(),s=lA(),o=hA(),c=dA(),a=pA(),u=yA(),f=gA(),l=mA(),d=wA(),y=bA(),g=EA(),m=Xw(),E=_A(),S=SA(),_=TA(),w=xA(),T=AA(),O={unsignedTx:n,globalXpub:t,checkPubkey:E.makeChecker([])};cs.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:S.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:_.makeConverter(e.InputTypes.TAP_BIP32_DERIVATION),tapInternalKey:w.makeConverter(e.InputTypes.TAP_INTERNAL_KEY),tapMerkleRoot:l};cs.inputs=A;const R={bip32Derivation:m.makeConverter(e.OutputTypes.BIP32_DERIVATION),redeemScript:S.makeConverter(e.OutputTypes.REDEEM_SCRIPT),witnessScript:T.makeConverter(e.OutputTypes.WITNESS_SCRIPT),checkPubkey:E.makeChecker([e.OutputTypes.BIP32_DERIVATION]),tapBip32Derivation:_.makeConverter(e.OutputTypes.TAP_BIP32_DERIVATION),tapTree:g,tapInternalKey:w.makeConverter(e.OutputTypes.TAP_INTERNAL_KEY)};return cs.outputs=R,cs}var Zp;function vA(){if(Zp)return os;Zp=1,Object.defineProperty(os,"__esModule",{value:!0});const e=vh(),t=Ah(),n=es(),r=Lt();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 S=m.filter(R=>R.key[0]===r.GlobalTypes.UNSIGNED_TX);if(S.length!==1)throw new Error("Format Error: Only one UNSIGNED_TX allowed");const _=a(S[0].value),{inputCount:w,outputCount:T}=_.getInputOutputCounts(),O=[],A=[];for(const R of t.range(w)){const M={},v=[];for(;!g();){const C=y(),q=C.key.toString("hex");if(M[q])throw new Error("Format Error: Keys must be unique for each input: input index "+R+" key "+q);M[q]=1,v.push(C)}O.push(v)}for(const R of t.range(T)){const M={},v=[];for(;!g();){const C=y(),q=C.key.toString("hex");if(M[q])throw new Error("Format Error: Keys must be unique for each output: output index "+R+" key "+q);M[q]=1,v.push(C)}A.push(v)}return o(_,{globalMapKeyVals:m,inputKeyVals:O,outputKeyVals:A})}os.psbtFromBuffer=i;function s(c,a,u){if(!a.equals(Buffer.from([u])))throw new Error(`Format Error: Invalid ${c} key: ${a.toString("hex")}`)}os.checkKeyBuffer=s;function o(c,{globalMapKeyVals:a,inputKeyVals:u,outputKeyVals:f}){const l={unsignedTx:c};let d=0;for(const S of a)switch(S.key[0]){case r.GlobalTypes.UNSIGNED_TX:if(s("global",S.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(S));break;default:l.unknownKeyVals||(l.unknownKeyVals=[]),l.unknownKeyVals.push(S)}const y=u.length,g=f.length,m=[],E=[];for(const S of t.range(y)){const _={};for(const w of u[S])switch(e.inputs.checkPubkey(w),w.key[0]){case r.InputTypes.NON_WITNESS_UTXO:if(s("input",w.key,r.InputTypes.NON_WITNESS_UTXO),_.nonWitnessUtxo!==void 0)throw new Error("Format Error: Input has multiple NON_WITNESS_UTXO");_.nonWitnessUtxo=e.inputs.nonWitnessUtxo.decode(w);break;case r.InputTypes.WITNESS_UTXO:if(s("input",w.key,r.InputTypes.WITNESS_UTXO),_.witnessUtxo!==void 0)throw new Error("Format Error: Input has multiple WITNESS_UTXO");_.witnessUtxo=e.inputs.witnessUtxo.decode(w);break;case r.InputTypes.PARTIAL_SIG:_.partialSig===void 0&&(_.partialSig=[]),_.partialSig.push(e.inputs.partialSig.decode(w));break;case r.InputTypes.SIGHASH_TYPE:if(s("input",w.key,r.InputTypes.SIGHASH_TYPE),_.sighashType!==void 0)throw new Error("Format Error: Input has multiple SIGHASH_TYPE");_.sighashType=e.inputs.sighashType.decode(w);break;case r.InputTypes.REDEEM_SCRIPT:if(s("input",w.key,r.InputTypes.REDEEM_SCRIPT),_.redeemScript!==void 0)throw new Error("Format Error: Input has multiple REDEEM_SCRIPT");_.redeemScript=e.inputs.redeemScript.decode(w);break;case r.InputTypes.WITNESS_SCRIPT:if(s("input",w.key,r.InputTypes.WITNESS_SCRIPT),_.witnessScript!==void 0)throw new Error("Format Error: Input has multiple WITNESS_SCRIPT");_.witnessScript=e.inputs.witnessScript.decode(w);break;case r.InputTypes.BIP32_DERIVATION:_.bip32Derivation===void 0&&(_.bip32Derivation=[]),_.bip32Derivation.push(e.inputs.bip32Derivation.decode(w));break;case r.InputTypes.FINAL_SCRIPTSIG:s("input",w.key,r.InputTypes.FINAL_SCRIPTSIG),_.finalScriptSig=e.inputs.finalScriptSig.decode(w);break;case r.InputTypes.FINAL_SCRIPTWITNESS:s("input",w.key,r.InputTypes.FINAL_SCRIPTWITNESS),_.finalScriptWitness=e.inputs.finalScriptWitness.decode(w);break;case r.InputTypes.POR_COMMITMENT:s("input",w.key,r.InputTypes.POR_COMMITMENT),_.porCommitment=e.inputs.porCommitment.decode(w);break;case r.InputTypes.TAP_KEY_SIG:s("input",w.key,r.InputTypes.TAP_KEY_SIG),_.tapKeySig=e.inputs.tapKeySig.decode(w);break;case r.InputTypes.TAP_SCRIPT_SIG:_.tapScriptSig===void 0&&(_.tapScriptSig=[]),_.tapScriptSig.push(e.inputs.tapScriptSig.decode(w));break;case r.InputTypes.TAP_LEAF_SCRIPT:_.tapLeafScript===void 0&&(_.tapLeafScript=[]),_.tapLeafScript.push(e.inputs.tapLeafScript.decode(w));break;case r.InputTypes.TAP_BIP32_DERIVATION:_.tapBip32Derivation===void 0&&(_.tapBip32Derivation=[]),_.tapBip32Derivation.push(e.inputs.tapBip32Derivation.decode(w));break;case r.InputTypes.TAP_INTERNAL_KEY:s("input",w.key,r.InputTypes.TAP_INTERNAL_KEY),_.tapInternalKey=e.inputs.tapInternalKey.decode(w);break;case r.InputTypes.TAP_MERKLE_ROOT:s("input",w.key,r.InputTypes.TAP_MERKLE_ROOT),_.tapMerkleRoot=e.inputs.tapMerkleRoot.decode(w);break;default:_.unknownKeyVals||(_.unknownKeyVals=[]),_.unknownKeyVals.push(w)}m.push(_)}for(const S of t.range(g)){const _={};for(const w of f[S])switch(e.outputs.checkPubkey(w),w.key[0]){case r.OutputTypes.REDEEM_SCRIPT:if(s("output",w.key,r.OutputTypes.REDEEM_SCRIPT),_.redeemScript!==void 0)throw new Error("Format Error: Output has multiple REDEEM_SCRIPT");_.redeemScript=e.outputs.redeemScript.decode(w);break;case r.OutputTypes.WITNESS_SCRIPT:if(s("output",w.key,r.OutputTypes.WITNESS_SCRIPT),_.witnessScript!==void 0)throw new Error("Format Error: Output has multiple WITNESS_SCRIPT");_.witnessScript=e.outputs.witnessScript.decode(w);break;case r.OutputTypes.BIP32_DERIVATION:_.bip32Derivation===void 0&&(_.bip32Derivation=[]),_.bip32Derivation.push(e.outputs.bip32Derivation.decode(w));break;case r.OutputTypes.TAP_INTERNAL_KEY:s("output",w.key,r.OutputTypes.TAP_INTERNAL_KEY),_.tapInternalKey=e.outputs.tapInternalKey.decode(w);break;case r.OutputTypes.TAP_TREE:s("output",w.key,r.OutputTypes.TAP_TREE),_.tapTree=e.outputs.tapTree.decode(w);break;case r.OutputTypes.TAP_BIP32_DERIVATION:_.tapBip32Derivation===void 0&&(_.tapBip32Derivation=[]),_.tapBip32Derivation.push(e.outputs.tapBip32Derivation.decode(w));break;default:_.unknownKeyVals||(_.unknownKeyVals=[]),_.unknownKeyVals.push(w)}E.push(_)}return{globalMap:l,inputs:m,outputs:E}}return os.psbtFromKeyVals=o,os}var wo={},Jp;function IA(){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=S=>S.length===0?[Buffer.from([0])]:S.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(S=>S.key.toString("hex")).forEach(S=>{if(a.has(S))throw new Error("Serialize Error: Duplicate key: "+S);a.add(S)}),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 zw(){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(vA()),t(IA())})(Nf)),Nf}var ey;function OA(){if(ey)return Mc;ey=1,Object.defineProperty(Mc,"__esModule",{value:!0});const e=zw();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})}Mc.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 Mc}var Pf={},ty;function Yw(){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,S=!!g.witnessScript,_=!E||!!g.finalScriptSig,w=!S||!!g.finalScriptWitness,T=!!g.finalScriptSig||!!g.finalScriptWitness;m=_&&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 S=g[E],{canAdd:_,canAddToArray:w,check:T,expected:O}=t[y+"s"][E]||{},A=!!w;if(T)if(A){if(!Array.isArray(S)||m[E]&&!Array.isArray(m[E]))throw new Error(`Key type ${E} must be an array`);S.every(T)||c(y,E,O,S);const R=m[E]||[],M=new Set;if(!S.every(v=>w(R,v,M)))throw new Error("Can not add duplicate data to array");m[E]=R.concat(S)}else{if(T(S)||c(y,E,O,S),!_(m,S))throw new Error(`Can not add duplicate data to ${y}`);m[E]=S}}}}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 BA(){if(ny)return Fc;ny=1,Object.defineProperty(Fc,"__esModule",{value:!0});const e=OA(),t=zw(),n=Lt(),r=Yw();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 Fc.Psbt=i,Fc}var et={},Ye={},ry;function dl(){if(ry)return Ye;ry=1,Object.defineProperty(Ye,"__esModule",{value:!0}),Ye.signatureBlocksAction=Ye.checkInputForSig=Ye.pubkeyInScript=Ye.pubkeyPositionInScript=Ye.witnessStackToScriptWitness=Ye.isP2TR=Ye.isP2SHScript=Ye.isP2WSHScript=Ye.isP2WPKH=Ye.isP2PKH=Ye.isP2PK=Ye.isP2MS=void 0;const e=es(),t=rn(),n=Ec(),r=Rr(),i=bc();function s(y){return g=>{try{return y({output:g}),!0}catch{return!1}}}Ye.isP2MS=s(i.p2ms),Ye.isP2PK=s(i.p2pk),Ye.isP2PKH=s(i.p2pkh),Ye.isP2WPKH=s(i.p2wpkh),Ye.isP2WSHScript=s(i.p2wsh),Ye.isP2SHScript=s(i.p2sh),Ye.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 S(w){E(w.length),m(w)}function _(w){E(w.length),w.forEach(S)}return _(y),g}Ye.witnessStackToScriptWitness=o;function c(y,g){const m=(0,r.hash160)(y),E=y.slice(1,33),S=t.decompile(g);if(S===null)throw new Error("Unknown script error");return S.findIndex(_=>typeof _=="number"?!1:_.equals(y)||_.equals(m)||_.equals(E))}Ye.pubkeyPositionInScript=c;function a(y,g){return c(y,g)!==-1}Ye.pubkeyInScript=a;function u(y,g){return l(y).some(E=>f(E,t.signature.decode,g))}Ye.checkInputForSig=u;function f(y,g,m){const{hashType:E}=g(y),S=[];switch(E&n.Transaction.SIGHASH_ANYONECANPAY&&S.push("addInput"),E&31){case n.Transaction.SIGHASH_ALL:break;case n.Transaction.SIGHASH_SINGLE:case n.Transaction.SIGHASH_NONE:S.push("addOutput"),S.push("setInputSequence");break}return S.indexOf(m)===-1}Ye.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 Ye}var iy;function NA(){if(iy)return et;iy=1,Object.defineProperty(et,"__esModule",{value:!0}),et.checkTaprootInputForSigs=et.tapTreeFromList=et.tapTreeToList=et.tweakInternalPubKey=et.checkTaprootOutputFields=et.checkTaprootInputFields=et.isTaprootOutput=et.isTaprootInput=et.serializeTaprootSignature=et.tapScriptFinalizer=et.toXOnly=void 0;const e=zt(),t=Ec(),n=dl(),r=Th(),i=bc(),s=dl(),o=x=>x.length===32?x:x.slice(1,33);et.toXOnly=o;function c(x,B,L){const N=P(B,x,L);try{const G=H(B,N).concat(N.script).concat(N.controlBlock);return{finalScriptWitness:(0,n.witnessStackToScriptWitness)(G)}}catch(V){throw new Error(`Can not finalize taproot input #${x}: ${V}`)}}et.tapScriptFinalizer=c;function a(x,B){const L=B?Buffer.from([B]):Buffer.from([]);return Buffer.concat([x,L])}et.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))}et.isTaprootInput=u;function f(x,B){return x&&!!(x.tapInternalKey||x.tapTree||x.tapBip32Derivation&&x.tapBip32Derivation.length||B&&(0,n.isP2TR)(B))}et.isTaprootOutput=f;function l(x,B,L){v(x,B,L),q(x,B,L)}et.checkTaprootInputFields=l;function d(x,B,L){C(x,B,L),y(x,B)}et.checkTaprootOutputFields=d;function y(x,B){if(!B.tapTree&&!B.tapInternalKey)return;const L=B.tapInternalKey||x.tapInternalKey,N=B.tapTree||x.tapTree;if(L){const{script:V}=x,G=g(L,N);if(V&&!V.equals(G))throw new Error("Error adding output. Script or address missmatch.")}}function g(x,B){const L=B&&S(B.leaves),{output:N}=(0,i.p2tr)({internalPubkey:x,scriptTree:L});return N}function m(x,B){const L=B.tapInternalKey,N=L&&(0,r.tweakKey)(L,B.tapMerkleRoot);if(!N)throw new Error(`Cannot tweak tap internal key for input #${x}. Public key: ${L&&L.toString("hex")}`);return N.x}et.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)}et.tapTreeToList=E;function S(x=[]){return x.length===1&&x[0].depth===0?{output:x[0].script,version:x[0].leafVersion}:R(x)}et.tapTreeFromList=S;function _(x,B){return T(x).some(N=>(0,s.signatureBlocksAction)(N,w,B))}et.checkTaprootInputForSigs=_;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(L=>L.signature)),!B.length){const L=O(x.finalScriptWitness);L&&B.push(L)}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=[],L=0){if(L>r.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");return x?(0,e.isTapleaf)(x)?(B.push({depth:L,leafVersion:x.version||r.LEAF_VERSION_TAPSCRIPT,script:x.output}),B):(x[0]&&A(x[0],B,L+1),x[1]&&A(x[1],B,L+1),B):[]}function R(x){let B;for(const L of x)if(B=M(L,B),!B)throw new Error("No room left to insert tapleaf in tree");return B}function M(x,B,L=0){if(L>r.MAX_TAPTREE_DEPTH)throw new Error("Max taptree depth exceeded.");if(x.depth===L)return B?void 0:{output:x.script,version:x.leafVersion};if((0,e.isTapleaf)(B))return;const N=M(x,B&&B[0],L+1);if(N)return[N,B&&B[1]];const V=M(x,B&&B[1],L+1);if(V)return[B&&B[0],V]}function v(x,B,L){const N=u(x)&&F(B),V=F(x)&&u(B),G=x===B&&u(B)&&F(B);if(N||V||G)throw new Error(`Invalid arguments for Psbt.${L}. Cannot use both taproot and non-taproot fields.`)}function C(x,B,L){const N=f(x)&&F(B),V=F(x)&&f(B),G=x===B&&f(B)&&F(B);if(N||V||G)throw new Error(`Invalid arguments for Psbt.${L}. Cannot use both taproot and non-taproot fields.`)}function q(x,B,L){if(B.tapMerkleRoot){const N=(B.tapLeafScript||[]).every(G=>K(G,B.tapMerkleRoot)),V=(x.tapLeafScript||[]).every(G=>K(G,B.tapMerkleRoot));if(!N||!V)throw new Error(`Invalid arguments for Psbt.${L}. Tapleaf not part of taptree.`)}else if(x.tapMerkleRoot&&!(B.tapLeafScript||[]).every(V=>K(V,x.tapMerkleRoot)))throw new Error(`Invalid arguments for Psbt.${L}. Tapleaf not part of taptree.`)}function K(x,B){if(!B)return!0;const L=(0,r.tapleafHash)({output:x.script,version:x.leafVersion});return(0,r.rootHashFromPath)(x.controlBlock,L).equals(B)}function H(x,B){const L=(0,r.tapleafHash)({output:B.script,version:B.leafVersion});return(x.tapScriptSig||[]).filter(N=>N.leafHash.equals(L)).map(N=>D(B.script,N)).sort((N,V)=>V.positionInScript-N.positionInScript).map(N=>N.signature)}function D(x,B){return Object.assign({positionInScript:(0,n.pubkeyPositionInScript)(B.pubkey,x)},B)}function P(x,B,L){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((V,G)=>V.controlBlock.length-G.controlBlock.length).find(V=>$(V,x.tapScriptSig,L));if(!N)throw new Error(`Can not finalize taproot input #${B}. Signature for tapleaf script not found.`);return N}function $(x,B,L){const N=(0,r.tapleafHash)({output:x.script,version:x.leafVersion});return(!L||L.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 et}var sy;function kA(){if(sy)return mo;sy=1,Object.defineProperty(mo,"__esModule",{value:!0}),mo.Psbt=void 0;const e=BA(),t=es(),n=Yw(),r=xh(),i=Eu(),s=Wn(),o=bc(),c=Th(),a=rn(),u=Ec(),f=NA(),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),U=new y(b,I);return q(U.__CACHE.__TX,U.__CACHE),U}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=(U,j,W,ie)=>Object.defineProperty(U,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 U=this.data.inputs.length-1,j=this.data.inputs[U];return j.nonWitnessUtxo&&ge(this.__CACHE,j,U),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:U}=this.opts,j=(0,r.toOutputScript)(b,U);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 $("__FEE_RATE","fee rate",this.data.inputs,this.__CACHE)}getFee(){return $("__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 U=(0,n.checkForInput)(this.data.inputs,h);if((0,f.isTaprootInput)(U))return this._finalizeTaprootInput(h,U,b,I);throw new Error(`Cannot finalize input #${h}. Not Taproot.`)}_finalizeInput(h,b,I=F){const{script:U,isP2SH:j,isP2WSH:W,isSegwit:ie}=ue(h,b,this.__CACHE);if(!U)throw new Error(`No script found for input #${h}`);M(b);const{finalScriptSig:Q,finalScriptWitness:fe}=I(h,b,U,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,U=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}=U(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=Oe(h,b,this.__CACHE),U=oe(I,h,"input",b.redeemScript||Ot(b.finalScriptSig),b.witnessScript||Be(b.finalScriptWitness)),j=U.type==="raw"?"":U.type+"-",W=re(U.meaningfulScript);return j+W}inputHasPubkey(h,b){const I=(0,n.checkForInput)(this.data.inputs,h);return ut(b,I,h,this.__CACHE)}inputHasHDKey(h,b){const I=(0,n.checkForInput)(this.data.inputs,h),U=T(b);return!!I.bip32Derivation&&I.bip32Derivation.some(U)}outputHasPubkey(h,b){const I=(0,n.checkForOutput)(this.data.outputs,h);return bt(b,I,h,this.__CACHE)}outputHasHDKey(h,b){const I=(0,n.checkForOutput)(this.data.outputs,h),U=T(b);return!!I.bip32Derivation&&I.bip32Derivation.some(U)}validateSignaturesOfAllInputs(h){return(0,n.checkForInput)(this.data.inputs,0),k(this.data.inputs.length).map(I=>this.validateSignaturesOfInput(I,h)).reduce((I,U)=>U===!0&&I,!0)}validateSignaturesOfInput(h,b,I){const U=this.data.inputs[h];return(0,f.isTaprootInput)(U)?this.validateSignaturesOfTaprootInput(h,b,I):this._validateSignaturesOfInput(h,b,I)}_validateSignaturesOfInput(h,b,I){const U=this.data.inputs[h],j=(U||{}).partialSig;if(!U||!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(ke=>ke.pubkey.equals(I)):j;if(W.length<1)throw new Error("No signatures for this pubkey");const ie=[];let Q,fe,le;for(const ke of W){const Re=a.signature.decode(ke.signature),{hash:nt,script:Ke}=le!==Re.hashType?L(h,Object.assign({},U,{sighashType:Re.hashType}),this.__CACHE,!0):{hash:Q,script:fe};le=Re.hashType,Q=nt,fe=Ke,v(ke.pubkey,Ke,"verify"),ie.push(b(ke.pubkey,nt,Re.signature))}return ie.every(ke=>ke===!0)}validateSignaturesOfTaprootInput(h,b,I){const U=this.data.inputs[h],j=(U||{}).tapKeySig,W=(U||{}).tapScriptSig;if(!U&&!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,U,this.data.inputs,I,this.__CACHE):N(h,U,this.data.inputs,this.__CACHE);if(!ie.length)throw new Error("No signatures for this pubkey");const Q=ie.find(le=>!le.leafHash);let fe=0;if(j&&Q){if(!b(Q.pubkey,Q.hash,G(j)))return!1;fe++}if(W)for(const le of W){const ke=ie.find(Re=>le.pubkey.equals(Re.pubkey));if(ke){if(!b(le.pubkey,ke.hash,G(le.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 U of k(this.data.inputs.length))try{this.signInputHD(U,h,b),I.push(!0)}catch{I.push(!1)}if(I.every(U=>U===!1))throw new Error("No inputs were signed");return this}signAllInputsHDAsync(h,b=[u.Transaction.SIGHASH_ALL]){return new Promise((I,U)=>{if(!h||!h.publicKey||!h.fingerprint)return U(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 U(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((U,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(()=>{U()}).catch(j)})}signAllInputs(h,b){if(!h||!h.publicKey)throw new Error("Need Signer to sign input");const I=[];for(const U of k(this.data.inputs.length))try{this.signInput(U,h,b),I.push(!0)}catch{I.push(!1)}if(I.every(U=>U===!1))throw new Error("No inputs were signed");return this}signAllInputsAsync(h,b){return new Promise((I,U)=>{if(!h||!h.publicKey)return U(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 U(new Error("No inputs were signed"));I()})})}signInput(h,b,I){if(!b||!b.publicKey)throw new Error("Need Signer to sign input");const U=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(U)?this._signTaprootInput(h,U,b,void 0,I):this._signInput(h,b,I)}signTaprootInput(h,b,I,U){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,U);throw new Error(`Input #${h} is not of type Taproot.`)}_signInput(h,b,I=[u.Transaction.SIGHASH_ALL]){const{hash:U,sighashType:j}=B(this.data.inputs,h,b.publicKey,this.__CACHE,I),W=[{pubkey:b.publicKey,signature:a.signature.encode(b.sign(U),j)}];return this.data.updateInput(h,{partialSig:W}),this}_signTaprootInput(h,b,I,U,j=[u.Transaction.SIGHASH_DEFAULT]){const W=this.checkTaprootHashesForSig(h,b,I,U,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 U=(0,n.checkForInput)(this.data.inputs,h);return(0,f.isTaprootInput)(U)?this._signTaprootInputAsync(h,U,b,void 0,I):this._signInputAsync(h,b,I)})}signTaprootInputAsync(h,b,I,U){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,U);throw new Error(`Input #${h} is not of type Taproot.`)})}_signInputAsync(h,b,I=[u.Transaction.SIGHASH_ALL]){const{hash:U,sighashType:j}=B(this.data.inputs,h,b.publicKey,this.__CACHE,I);return Promise.resolve(b.sign(U)).then(W=>{const ie=[{pubkey:b.publicKey,signature:a.signature.encode(W,j)}];this.data.updateInput(h,{partialSig:ie})})}async _signTaprootInputAsync(h,b,I,U,j=[u.Transaction.SIGHASH_DEFAULT]){const W=this.checkTaprootHashesForSig(h,b,I,U,j),ie=[],Q=W.filter(le=>!le.leafHash)[0];if(Q){const le=Promise.resolve(I.signSchnorr(Q.hash)).then(ke=>({tapKeySig:(0,f.serializeTaprootSignature)(ke,b.sighashType)}));ie.push(le)}const fe=W.filter(le=>!!le.leafHash);if(fe.length){const le=fe.map(ke=>Promise.resolve(I.signSchnorr(ke.hash)).then(Re=>({tapScriptSig:[{pubkey:(0,f.toXOnly)(I.publicKey),signature:(0,f.serializeTaprootSignature)(Re,b.sighashType),leafHash:ke.leafHash}]})));ie.push(...le)}return Promise.all(ie).then(le=>{le.forEach(ke=>this.data.updateInput(h,ke))})}checkTaprootHashesForSig(h,b,I,U,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,U,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 S(this.__CACHE),this.data.toBuffer()}toHex(){return S(this.__CACHE),this.data.toHex()}toBase64(){return S(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&&ge(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),C(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 _(1,p.partialSig);case"multisig":const I=o.p2ms({output:h});return _(I.m,p.partialSig,I.pubkeys);default:return!1}}function S(p){if(p.__UNSAFE_SIGN_NONSEGWIT!==!1)throw new Error("Not BIP174 compliant, can not export")}function _(p,h,b){if(!h)return!1;let I;if(b?I=b.map(U=>{const j=gn(U);return h.find(W=>W.pubkey.equals(j))}).filter(U=>!!U):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(),U=h.__EXTRACTED_TX.virtualSize(),j=I*U;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 ${U} 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:U}=a.signature.decode(I.signature);if(b!==U)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 C(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 q(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,U,j)=>{const W=p({redeem:{output:U}}).output;if(!I.equals(W))throw new Error(`${h} for ${j} #${b} doesn't match the scriptPubKey in the prevout`)}}const D=H(o.p2sh,"Redeem script"),P=H(o.p2wsh,"Witness script");function $(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 U,j=!0;if(I.__EXTRACTED_TX?(U=I.__EXTRACTED_TX,j=!1):U=I.__TX.clone(),J(b,U,I,j),p==="__FEE_RATE")return I.__FEE_RATE;if(p==="__FEE")return I.__FEE}function F(p,h,b,I,U,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,U,j)}function x(p,h,b,I,U,j){let W,ie;const Q=ce(p,h,b),fe=j?o.p2wsh({redeem:Q}):null,le=U?o.p2sh({redeem:fe||Q}):null;return I?(fe?ie=(0,l.witnessStackToScriptWitness)(fe.witness):ie=(0,l.witnessStackToScriptWitness)(Q.witness),le&&(W=le.input)):le?W=le.input:W=Q.input,{finalScriptSig:W,finalScriptWitness:ie}}function B(p,h,b,I,U){const j=(0,n.checkForInput)(p,h),{hash:W,sighashType:ie,script:Q}=L(h,j,I,!1,U);return v(b,Q,"sign"),{hash:W,sighashType:ie}}function L(p,h,b,I,U){const j=b.__TX,W=h.sighashType||u.Transaction.SIGHASH_ALL;Y(W,U);let ie,Q;if(h.nonWitnessUtxo){const ke=he(b,h,p),Re=j.ins[p].hash,nt=ke.getHash();if(!Re.equals(nt))throw new Error(`Non-witness UTXO hash for input #${p} doesn't match the hash specified in the prevout`);const Ke=j.ins[p].index;Q=ke.outs[Ke]}else if(h.witnessUtxo)Q=h.witnessUtxo;else throw new Error("Need a Utxo input item for signing");const{meaningfulScript:fe,type:le}=oe(Q.script,p,"input",h.redeemScript,h.witnessScript);if(["p2sh-p2wsh","p2wsh"].indexOf(le)>=0)ie=j.hashForWitnessV0(p,fe,Q.value,W);else if((0,l.isP2WPKH)(fe)){const ke=o.p2pkh({hash:fe.slice(2)}).output;ie=j.hashForWitnessV0(p,ke,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 U=[];if(h.tapInternalKey){const W=V(p,h,I);W&&U.push(W)}if(h.tapScriptSig){const W=h.tapScriptSig.map(ie=>ie.pubkey);U.push(...W)}return U.map(W=>X(p,h,b,W,I)).flat()}function V(p,h,b){const{script:I}=De(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,U,j,W){const ie=U.__TX,Q=h.sighashType||u.Transaction.SIGHASH_DEFAULT;Y(Q,W);const fe=b.map((Ke,Xn)=>De(Xn,Ke,U)),le=fe.map(Ke=>Ke.script),ke=fe.map(Ke=>Ke.value),Re=[];if(h.tapInternalKey&&!j){const Ke=V(p,h,U)||Buffer.from([]);if((0,f.toXOnly)(I).equals(Ke)){const Xn=ie.hashForWitnessV1(p,le,ke,Q);Re.push({pubkey:I,hash:Xn})}}const nt=(h.tapLeafScript||[]).filter(Ke=>(0,l.pubkeyInScript)(I,Ke.script)).map(Ke=>{const Xn=(0,c.tapleafHash)({output:Ke.script,version:Ke.leafVersion});return Object.assign({hash:Xn},Ke)}).filter(Ke=>!j||j.equals(Ke.hash)).map(Ke=>{const Xn=ie.hashForWitnessV1(p,le,ke,Q,Ke.hash);return{pubkey:I,hash:Xn,leafHash:Ke.hash}});return Re.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 U=Z(p,b);I=o.p2ms({output:p,signatures:U});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,U={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(U.isP2SH=!!h.redeemScript,U.isP2WSH=!!h.witnessScript,h.witnessScript)U.script=h.witnessScript;else if(h.redeemScript)U.script=h.redeemScript;else if(h.nonWitnessUtxo){const j=he(b,h,p),W=I.ins[p].index;U.script=j.outs[W].script}else h.witnessUtxo&&(U.script=h.witnessUtxo.script);return(h.witnessScript||(0,l.isP2WPKH)(U.script))&&(U.isSegwit=!0),U}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 U=I.bip32Derivation.map(W=>{if(W.masterFingerprint.equals(b.fingerprint))return W}).filter(W=>!!W);if(U.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return U.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(U=>U.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 U(){return b(I())}function j(){const W=I(),ie=[];for(let Q=0;Q<W;Q++)ie.push(U());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 ge(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 U=p,j=b;delete h.nonWitnessUtxo,Object.defineProperty(h,"nonWitnessUtxo",{enumerable:!0,get(){const W=U.__NON_WITNESS_UTXO_BUF_CACHE[j],ie=U.__NON_WITNESS_UTXO_TX_CACHE[j];if(W!==void 0)return W;{const Q=ie.toBuffer();return U.__NON_WITNESS_UTXO_BUF_CACHE[j]=Q,Q}},set(W){U.__NON_WITNESS_UTXO_BUF_CACHE[j]=W}})}function J(p,h,b,I){let U=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)U+=Q.witnessUtxo.value;else if(Q.nonWitnessUtxo){const le=he(b,Q,fe),ke=h.ins[fe].index,Re=le.outs[ke];U+=Re.value}});const j=h.outs.reduce((Q,fe)=>Q+fe.value,0),W=U-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 he(p,h,b){const I=p.__NON_WITNESS_UTXO_TX_CACHE;return I[b]||ge(p,h,b),I[b]}function Oe(p,h,b){const{script:I}=De(p,h,b);return I}function De(p,h,b){if(h.witnessUtxo!==void 0)return{script:h.witnessUtxo.script,value:h.witnessUtxo.value};if(h.nonWitnessUtxo!==void 0){const U=he(b,h,p).outs[b.__TX.ins[p].index];return{script:U.script,value:U.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function ut(p,h,b,I){const U=Oe(b,h,I),{meaningfulScript:j}=oe(U,b,"input",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(p,j)}function bt(p,h,b,I){const U=I.__TX.outs[b].script,{meaningfulScript:j}=oe(U,b,"output",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(p,j)}function Ot(p){if(!p)return;const h=a.decompile(p);if(!h)return;const b=h[h.length-1];if(!(!Buffer.isBuffer(b)||it(b)||He(b)||!a.decompile(b)))return b}function Be(p){if(!p)return;const h=ae(p),b=h[h.length-1];if(!(it(b)||!a.decompile(b)))return b}function gn(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 He(p){return a.isCanonicalScriptSignature(p)}function oe(p,h,b,I,U){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)&&U===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let Q;return W?(Q=U,D(h,p,I,b),P(h,I,U,b),ne(Q)):ie?(Q=U,P(h,p,U,b),ne(Q)):j?(Q=I,D(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 go}var oy;function PA(){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=Rr();e.crypto=n;const r=Wn();e.networks=r;const i=bc();e.payments=i;const s=nn();e.script=s;var o=oA();Object.defineProperty(e,"Block",{enumerable:!0,get:function(){return o.Block}});var c=kA();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=Ec();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 Ii={},cy;function RA(){if(cy)return Ii;cy=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.base26Decode=Ii.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}Ii.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 Ii.base26Decode=t,Ii}var Oi={},ay;function Zw(){if(ay)return Oi;ay=1,Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.none=Oi.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)}Oi.some=n;function r(){return new e}return Oi.none=r,Oi}var Bi={},uy;function CA(){if(uy)return Bi;uy=1,Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.decodeLEB128=Bi.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}Bi.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 Bi.decodeLEB128=t,Bi}var Rf={},fy;function UA(){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 dr={},ly;function Jw(){if(ly)return dr;ly=1,Object.defineProperty(dr,"__esModule",{value:!0}),dr.removeSpacers=dr.getSpacersVal=dr.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}dr.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}dr.getSpacersVal=t;function n(r){return r.replace(/[•]+/g,"")}return dr.removeSpacers=n,dr}var hy;function HA(){if(hy)return ze;hy=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.EtchInscription=ze.Message=ze.Runestone=ze.Etching=ze.Rune=ze.Terms=ze.Range=ze.Flaw=ze.Tag=ze.Flag=ze.Edict=ze.RuneId=void 0;const e=PA(),t=RA(),n=Zw(),r=CA(),i=UA(),s=Jw();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)))}}ze.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)))}}ze.Edict=c;var a;(function(_){_[_.Etching=0]="Etching",_[_.Terms=1]="Terms",_[_.Turbo=2]="Turbo",_[_.Cenotaph=127]="Cenotaph"})(a||(ze.Flag=a={}));var u;(function(_){_[_.Body=0]="Body",_[_.Flags=2]="Flags",_[_.Rune=4]="Rune",_[_.Premine=6]="Premine",_[_.Cap=8]="Cap",_[_.Amount=10]="Amount",_[_.HeightStart=12]="HeightStart",_[_.HeightEnd=14]="HeightEnd",_[_.OffsetStart=16]="OffsetStart",_[_.OffsetEnd=18]="OffsetEnd",_[_.Mint=20]="Mint",_[_.Pointer=22]="Pointer",_[_.Cenotaph=126]="Cenotaph",_[_.Divisibility=1]="Divisibility",_[_.Spacers=3]="Spacers",_[_.Symbol=5]="Symbol",_[_.Nop=127]="Nop"})(u||(ze.Tag=u={}));var f;(function(_){_[_.EdictOutput=0]="EdictOutput",_[_.EdictRuneId=1]="EdictRuneId",_[_.InvalidScript=2]="InvalidScript",_[_.Opcode=3]="Opcode",_[_.SupplyOverflow=4]="SupplyOverflow",_[_.TrailingIntegers=5]="TrailingIntegers",_[_.TruncatedField=6]="TruncatedField",_[_.UnrecognizedEvenTag=7]="UnrecognizedEvenTag",_[_.UnrecognizedFlag=8]="UnrecognizedFlag",_[_.Varint=9]="Varint"})(f||(ze.Flaw=f={}));class l{constructor(w,T){this.start=w,this.end=T}}ze.Range=l;class d{constructor(w,T,O,A){this.amount=w,this.cap=T,this.height=O,this.offset=A}}ze.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}}ze.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}}ze.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)(),C=w.symbol?(0,n.some)(w.symbol):(0,n.none)(),q=typeof w.pointer=="number"?(0,n.some)(w.pointer):(0,n.none)(),K=new g(R,M,(0,n.some)(O),v,C,(0,n.some)(A),!0);return new m([],(0,n.some)(K),(0,n.none)(),q)}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(),C=R.getPointer();return(0,n.some)(new m(R.edicts,M,v,C))}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 D=1<<a.Terms;R|=D}if(T.turbo){let D=1<<a.Turbo;R|=D}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 C=T.spacers.value();C!==null&&w.set(u.Spacers,[BigInt(C)]);const q=T.symbol.value();q!==null&&w.set(u.Symbol,[BigInt(q.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 D=H.height.start.value();D&&w.set(u.HeightStart,[BigInt(D)]);const P=H.height.end.value();P&&w.set(u.HeightEnd,[BigInt(P)]);const $=H.offset.start.value();$&&w.set(u.OffsetStart,[BigInt($)]);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)}}ze.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 C=T[v];if(Number(C)===u.Body){M=!0,v+=1;continue}if(M){let q=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=q.next(K[0],K[1]);if(!H.isSome()){R|=f.EdictRuneId;break}const D=c.from_integers(w,H.value(),K[2],K[3]);if(!D.isSome()){R|=f.EdictOutput;break}q=H.value(),A.push(D.value())}v+=4}else{let q=T[v+1];const K=O.get(Number(C))||[];K.push(q),O.set(Number(C),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 C=v-O;O=v,w.push(Buffer.from((0,r.encodeLEB128)(0n))),w.push(Buffer.from((0,r.encodeLEB128)(C)))}else{const C=M-T;T=M,O=v,w.push(Buffer.from((0,r.encodeLEB128)(C))),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),C=new l(R,M);return(0,n.some)(new d(T.value(),w.value(),v,C))}getPointer(){if(!this.fields.has(u.Pointer))return(0,n.none)();const[w]=this.fields.get(u.Pointer);return(0,n.some)(Number(w))}}ze.Message=E;class S{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(S.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,C=[];let q=!1;for(let K=5;K<M.length-1;){const H=M[K];if(H===0){q=!0,K++;continue}else if(q)C.push(H),K++;else{const D=H-80,P=M[K+1];if(typeof P=="number"){const $=Buffer.alloc(1);$.writeUint8(P),v.set(D,$)}else v.set(D,P);K+=2}}return new S(v,Buffer.concat(C))}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(S.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 ze.EtchInscription=S,S.Tag={CONTENT_TYPE:1,POINTER:2,PARENT:3,METADATA:5,METAPROTOCOL:7,CONTENT_ENCODING:9,DELEGATE:11,RUNE:13},ze}var dy;function FA(){return dy||(dy=1,(function(e){var t=bi&&bi.__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=bi&&bi.__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(HA(),e);var r=Zw();Object.defineProperty(e,"none",{enumerable:!0,get:function(){return r.none}}),Object.defineProperty(e,"some",{enumerable:!0,get:function(){return r.some}});var i=Jw();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}})})(bi)),bi}var us=FA();function Qw(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===Bs.Mainnet?Pn:Uy}const Tn={P2PKH:{P2PKH:null},P2SH_P2WPKH:{P2SH_P2WPKH:null},P2WPKH:{P2WPKH:null},P2WSH:{P2WSH:null},P2SH:{P2SH:null},P2TR:{P2TR:null},UNKNOWN:{UNKNOWN:null}};function Bh(e,t=Bs.Testnet){const n=Oh(t);return Tg(e,n)}function bo(e){const t=Pn,n=Uy,r=W1;let i,s,o=Tn.UNKNOWN;if(e.startsWith("bc1")||e.startsWith("tb1")||e.startsWith("bcrt1"))try{return s=kl(e),s.version===0?s.data.length===20?o=Tn.P2WPKH:o=Tn.P2WSH:o=Tn.P2TR,o}catch{return Tn.UNKNOWN}else try{return i=Sg(e),i.version===t.pubKeyHash||i.version===n.pubKeyHash||i.version===r.pubKeyHash?o=Tn.P2PKH:(i.version===t.scriptHash||(i.version,n.scriptHash),o=Tn.P2SH_P2WPKH),o}catch{return Tn.UNKNOWN}}function MA(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===Bs.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 LA=Object.freeze(Object.defineProperty({__proto__:null,bytesToHex:Ih,formatPoolUtxo:MA,getAddressType:bo,getScriptByAddress:Bh,getUtxoProof:e1,hexToBytes:Qw,toBitcoinNetwork:Oh},Symbol.toStringTag,{value:"Module"})),qA="kqs64-paaaa-aaaar-qamza-cai",VA="hvyp5-5yaaa-aaaao-qjxha-cai",Gc=BigInt(546),Jn="0:0",DA="https://runescan-hasura-mainnet.omnity.network/v1/graphql",$A="https://runescan-hasura-testnet.omnity.network/v1/graphql";class t1{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(r=>r.txid===t.txid&&r.vout===t.vout)>=0)return;const{address:n}=t;this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:Qw(t.scriptPk)}}),this.inputAddressTypes.push(bo(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(bo(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=this.userInputUtxoDusts;this.outputAddressTypes.push(bo(r));let o=BigInt(0),c=BigInt(0),a=[],u=BigInt(0),f=BigInt(0);const l=[...this.inputAddressTypes];do if(o=c,c=(await this.client.orchestrator.estimate_min_tx_fee({input_types:this.inputAddressTypes,pool_address:this.intentions.map(m=>m.poolAddress),output_types:this.outputAddressTypes})).Ok,u=n+c+i-s,c>o&&u>0){const m=this.selectBtcUtxos(t,u);if(m.length===0)throw new Error("INSUFFICIENT_BTC_UTXOs");this.inputAddressTypes=l.concat([...m.map(()=>bo(r))]);const E=m.reduce((S,_)=>S+BigInt(_.satoshis),BigInt(0));E-u>0&&E-u>Gc||this.outputAddressTypes.pop(),a=m}while(c>o&&u>0);let d=BigInt(0);a.forEach(g=>{this.addInput(g),d+=BigInt(g.satoshis)});const y=d-u;if(y<0)throw new Error("Insufficient UTXO(s)");y>Gc?this.addOutput(r,y):y>BigInt(0)&&(f=y),this.txFee=f+c}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===Jn?f.needBtc=!0:f.runeIds.add(u.coin.id)}for(const u of o.outputCoins){const f=s(u.to);u.coin.id===Jn?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===Jn?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(s=>s.poolAddress),r={},i={};this.intentions.forEach(({poolAddress:s,inputCoins:o,outputCoins:c})=>{const a=[...o],u=[...c];a.forEach(({coin:f,from:l})=>{!u.find(d=>d.coin.id===f.id)&&!n.includes(l)&&u.push({coin:f,to:s})}),u.forEach(({coin:f,to:l})=>{!a.find(d=>d.coin.id===f.id)&&!n.includes(l)&&a.push({coin:f,from:s})}),a.forEach(({coin:f,from:l})=>{r[l]??={},r[l][f.id]=(r[l][f.id]??BigInt(0))+BigInt(f.value)}),u.forEach(({coin:f,to:l})=>{i[l]??={},i[l][f.id]=(i[l][f.id]??BigInt(0))+BigInt(f.value)})});for(const[s,o]of Object.entries(r))for(const[c,a]of Object.entries(o))if(c===Jn){if(s===this.config.paymentAddress){i[s]??={},i[s][c]=(i[s][c]??BigInt(0))-a;continue}const u=t.btc[s]||[],f=this.selectBtcUtxos(u,a,n.includes(s)),d=f.reduce((y,g)=>y+BigInt(g.satoshis),BigInt(0))-a;d>BigInt(0)&&(i[s]??={},i[s][c]=(i[s][c]??BigInt(0))+d),f.forEach(y=>{this.addInput(y),n.includes(s)&&y.runes.forEach(g=>{i[s]??={},i[s][g.id]=(i[s][g.id]??BigInt(0))+BigInt(g.amount)})})}else{const u=t.rune[s]?.[c]||[],f=this.selectRuneUtxos(u,c,a),d=f.reduce((y,g)=>{const m=g.runes.find(E=>E.id===c);return y+BigInt(m?.amount??0)},BigInt(0))-a;d>BigInt(0)&&(i[s]??={},i[s][c]=(i[s][c]??BigInt(0))+d),f.forEach(y=>this.addInput(y))}for(const[s,o]of Object.entries(i))if(!(r[s]||!n.includes(s)))for(const[c]of Object.entries(o))if(c===Jn){const a=t.btc[s]||[],u=a.reduce((f,l)=>f+BigInt(l.satoshis),BigInt(0));i[s]??={},i[s][c]=(i[s][c]??BigInt(0))+u,a.forEach(f=>{this.addInput(f),f.runes.forEach(l=>{i[s]??={},i[s][l.id]=(i[s][l.id]??BigInt(0))+BigInt(l.amount)})})}else{const a=t.rune[s]?.[c]||[],u=a.reduce((f,l)=>{const d=l.runes.find(y=>y.id===c);return f+BigInt(d?.amount??0)},BigInt(0));i[s]??={},i[s][c]=(i[s][c]??BigInt(0))+u,a.forEach(f=>this.addInput(f))}return i}addOutputs(t){const n=new Set;for(const[,i]of Object.entries(t))for(const s of Object.keys(i))s!==Jn&&n.add(s);const r=Array.from(n);if(r.length>0){const i=[],s=[];let o=1;r.forEach(a=>{const u=new us.RuneId(Number(a.split(":")[0]),Number(a.split(":")[1]));for(const[f,l]of Object.entries(t)){const d=l[a]??BigInt(0);d>BigInt(0)&&(i.push(new us.Edict(u,d,o)),s.push(f),o++)}});const c=new us.Runestone(i,us.none(),us.none(),us.none());this.addScriptOutput(new Uint8Array(c.encipher())),s.forEach(a=>{const u=t[a]?.[Jn]??BigInt(0),f=u>BigInt(0)&&a!==this.config.address?u:Gc;this.addOutput(a,f),u>BigInt(0)&&a!==this.config.address?delete t[a][Jn]:this.additionalDustNeeded+=Gc})}for(const[i,s]of Object.entries(t)){const o=s[Jn]??BigInt(0);o>BigInt(0)&&this.addOutput(i,o)}}addIntention(t){this.intentions.push(t)}async build(){const t=await this.getInvolvedAddressUtxos();for(const o of this.intentions){const c=o.poolUtxos;if(!c?.length)continue;t.btc[o.poolAddress]=c,t.rune[o.poolAddress]={};const a=t.rune[o.poolAddress];for(const u of c)for(const f of u.runes)(a[f.id]??=[]).push(u)}const n=this.addInputsAndCalculateOutputs(t);this.addOutputs(n);const r=this.config.paymentAddress,i=t.btc[r]??[],s=n[r]?.[Jn]??BigInt(0);return await this.addBtcAndFees(i,s<0?-s:BigInt(0)),this.psbt}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,nonce:u})=>({exchange_id:this.config.exchangeId,input_coins:c,output_coins:a,pool_address:o,action:i,action_params:s??"",pool_utxo_spent:[],pool_utxo_received:[],nonce:u}))},initiator_utxo_proof:r,psbt_hex:t}).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 vs extends Error{response;request;constructor(t,n){const r=`${vs.extractMessage(t)}: ${JSON.stringify({response:t,request:n})}`;super(r),Object.setPrototypeOf(this,vs.prototype),this.response=t,this.request=n,typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,vs)}static extractMessage(t){return t.errors?.[0]?.message??`GraphQL Error (Code: ${String(t.status)})`}}const py=e=>e.toUpperCase(),Cf=e=>typeof e=="function"?e():e,n1=(e,t)=>e.map((n,r)=>[n,t[r]]),fs=e=>{let t={};return e instanceof Headers?t=jA(e):Array.isArray(e)?e.forEach(([n,r])=>{n&&r!==void 0&&(t[n]=r)}):e&&(t=e),t},jA=e=>{const t={};return e.forEach((n,r)=>{t[r]=n}),t},KA=e=>{try{const t=e();return GA(t)?t.catch(n=>yy(n)):t}catch(t){return yy(t)}},yy=e=>e instanceof Error?e:new Error(String(e)),GA=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),WA=(e,t)=>e.documents?e:{documents:e,requestHeaders:t,signal:void 0},XA=(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 zA(e){return typeof e=="object"&&e!==null}function YA(e,t){if(!!!e)throw new Error("Unexpected invariant triggered.")}const ZA=/\r\n|[\n\r]/g;function pl(e,t){let n=0,r=1;for(const i of e.body.matchAll(ZA)){if(typeof i.index=="number"||YA(!1),i.index>=t)break;n=i.index+i[0].length,r+=1}return{line:r,column:t+1-n}}function JA(e){return r1(e.source,pl(e.source,e.start))}function r1(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 U=[];if(h.tapInternalKey){const W=V(p,h,I);W&&U.push(W)}if(h.tapScriptSig){const W=h.tapScriptSig.map(ie=>ie.pubkey);U.push(...W)}return U.map(W=>X(p,h,b,W,I)).flat()}function V(p,h,b){const{script:I}=De(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,U,j,W){const ie=U.__TX,Q=h.sighashType||u.Transaction.SIGHASH_DEFAULT;Y(Q,W);const fe=b.map((Ke,Xn)=>De(Xn,Ke,U)),le=fe.map(Ke=>Ke.script),ke=fe.map(Ke=>Ke.value),Re=[];if(h.tapInternalKey&&!j){const Ke=V(p,h,U)||Buffer.from([]);if((0,f.toXOnly)(I).equals(Ke)){const Xn=ie.hashForWitnessV1(p,le,ke,Q);Re.push({pubkey:I,hash:Xn})}}const nt=(h.tapLeafScript||[]).filter(Ke=>(0,l.pubkeyInScript)(I,Ke.script)).map(Ke=>{const Xn=(0,c.tapleafHash)({output:Ke.script,version:Ke.leafVersion});return Object.assign({hash:Xn},Ke)}).filter(Ke=>!j||j.equals(Ke.hash)).map(Ke=>{const Xn=ie.hashForWitnessV1(p,le,ke,Q,Ke.hash);return{pubkey:I,hash:Xn,leafHash:Ke.hash}});return Re.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 U=Z(p,b);I=o.p2ms({output:p,signatures:U});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,U={script:null,isSegwit:!1,isP2SH:!1,isP2WSH:!1};if(U.isP2SH=!!h.redeemScript,U.isP2WSH=!!h.witnessScript,h.witnessScript)U.script=h.witnessScript;else if(h.redeemScript)U.script=h.redeemScript;else if(h.nonWitnessUtxo){const j=he(b,h,p),W=I.ins[p].index;U.script=j.outs[W].script}else h.witnessUtxo&&(U.script=h.witnessUtxo.script);return(h.witnessScript||(0,l.isP2WPKH)(U.script))&&(U.isSegwit=!0),U}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 U=I.bip32Derivation.map(W=>{if(W.masterFingerprint.equals(b.fingerprint))return W}).filter(W=>!!W);if(U.length===0)throw new Error("Need one bip32Derivation masterFingerprint to match the HDSigner fingerprint");return U.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(U=>U.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 U(){return b(I())}function j(){const W=I(),ie=[];for(let Q=0;Q<W;Q++)ie.push(U());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 ge(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 U=p,j=b;delete h.nonWitnessUtxo,Object.defineProperty(h,"nonWitnessUtxo",{enumerable:!0,get(){const W=U.__NON_WITNESS_UTXO_BUF_CACHE[j],ie=U.__NON_WITNESS_UTXO_TX_CACHE[j];if(W!==void 0)return W;{const Q=ie.toBuffer();return U.__NON_WITNESS_UTXO_BUF_CACHE[j]=Q,Q}},set(W){U.__NON_WITNESS_UTXO_BUF_CACHE[j]=W}})}function J(p,h,b,I){let U=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)U+=Q.witnessUtxo.value;else if(Q.nonWitnessUtxo){const le=he(b,Q,fe),ke=h.ins[fe].index,Re=le.outs[ke];U+=Re.value}});const j=h.outs.reduce((Q,fe)=>Q+fe.value,0),W=U-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 he(p,h,b){const I=p.__NON_WITNESS_UTXO_TX_CACHE;return I[b]||ge(p,h,b),I[b]}function Oe(p,h,b){const{script:I}=De(p,h,b);return I}function De(p,h,b){if(h.witnessUtxo!==void 0)return{script:h.witnessUtxo.script,value:h.witnessUtxo.value};if(h.nonWitnessUtxo!==void 0){const U=he(b,h,p).outs[b.__TX.ins[p].index];return{script:U.script,value:U.value}}else throw new Error("Can't find pubkey in input without Utxo data")}function ut(p,h,b,I){const U=Oe(b,h,I),{meaningfulScript:j}=oe(U,b,"input",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(p,j)}function bt(p,h,b,I){const U=I.__TX.outs[b].script,{meaningfulScript:j}=oe(U,b,"output",h.redeemScript,h.witnessScript);return(0,l.pubkeyInScript)(p,j)}function Ot(p){if(!p)return;const h=a.decompile(p);if(!h)return;const b=h[h.length-1];if(!(!Buffer.isBuffer(b)||it(b)||He(b)||!a.decompile(b)))return b}function Be(p){if(!p)return;const h=ae(p),b=h[h.length-1];if(!(it(b)||!a.decompile(b)))return b}function gn(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 He(p){return a.isCanonicalScriptSignature(p)}function oe(p,h,b,I,U){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)&&U===void 0)throw new Error("scriptPubkey or redeemScript is P2WSH but witnessScript missing");let Q;return W?(Q=U,D(h,p,I,b),P(h,I,U,b),ne(Q)):ie?(Q=U,P(h,p,U,b),ne(Q)):j?(Q=I,D(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 PA(){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=Rr();e.crypto=n;const r=Wn();e.networks=r;const i=bc();e.payments=i;const s=rn();e.script=s;var o=oA();Object.defineProperty(e,"Block",{enumerable:!0,get:function(){return o.Block}});var c=kA();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=Ec();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 Ii={},cy;function RA(){if(cy)return Ii;cy=1,Object.defineProperty(Ii,"__esModule",{value:!0}),Ii.base26Decode=Ii.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}Ii.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 Ii.base26Decode=t,Ii}var Oi={},ay;function Zw(){if(ay)return Oi;ay=1,Object.defineProperty(Oi,"__esModule",{value:!0}),Oi.none=Oi.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)}Oi.some=n;function r(){return new e}return Oi.none=r,Oi}var Bi={},uy;function CA(){if(uy)return Bi;uy=1,Object.defineProperty(Bi,"__esModule",{value:!0}),Bi.decodeLEB128=Bi.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}Bi.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 Bi.decodeLEB128=t,Bi}var Rf={},fy;function UA(){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 dr={},ly;function Jw(){if(ly)return dr;ly=1,Object.defineProperty(dr,"__esModule",{value:!0}),dr.removeSpacers=dr.getSpacersVal=dr.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}dr.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}dr.getSpacersVal=t;function n(r){return r.replace(/[•]+/g,"")}return dr.removeSpacers=n,dr}var hy;function HA(){if(hy)return ze;hy=1,Object.defineProperty(ze,"__esModule",{value:!0}),ze.EtchInscription=ze.Message=ze.Runestone=ze.Etching=ze.Rune=ze.Terms=ze.Range=ze.Flaw=ze.Tag=ze.Flag=ze.Edict=ze.RuneId=void 0;const e=PA(),t=RA(),n=Zw(),r=CA(),i=UA(),s=Jw();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)))}}ze.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)))}}ze.Edict=c;var a;(function(_){_[_.Etching=0]="Etching",_[_.Terms=1]="Terms",_[_.Turbo=2]="Turbo",_[_.Cenotaph=127]="Cenotaph"})(a||(ze.Flag=a={}));var u;(function(_){_[_.Body=0]="Body",_[_.Flags=2]="Flags",_[_.Rune=4]="Rune",_[_.Premine=6]="Premine",_[_.Cap=8]="Cap",_[_.Amount=10]="Amount",_[_.HeightStart=12]="HeightStart",_[_.HeightEnd=14]="HeightEnd",_[_.OffsetStart=16]="OffsetStart",_[_.OffsetEnd=18]="OffsetEnd",_[_.Mint=20]="Mint",_[_.Pointer=22]="Pointer",_[_.Cenotaph=126]="Cenotaph",_[_.Divisibility=1]="Divisibility",_[_.Spacers=3]="Spacers",_[_.Symbol=5]="Symbol",_[_.Nop=127]="Nop"})(u||(ze.Tag=u={}));var f;(function(_){_[_.EdictOutput=0]="EdictOutput",_[_.EdictRuneId=1]="EdictRuneId",_[_.InvalidScript=2]="InvalidScript",_[_.Opcode=3]="Opcode",_[_.SupplyOverflow=4]="SupplyOverflow",_[_.TrailingIntegers=5]="TrailingIntegers",_[_.TruncatedField=6]="TruncatedField",_[_.UnrecognizedEvenTag=7]="UnrecognizedEvenTag",_[_.UnrecognizedFlag=8]="UnrecognizedFlag",_[_.Varint=9]="Varint"})(f||(ze.Flaw=f={}));class l{constructor(w,T){this.start=w,this.end=T}}ze.Range=l;class d{constructor(w,T,O,A){this.amount=w,this.cap=T,this.height=O,this.offset=A}}ze.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}}ze.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}}ze.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)(),C=w.symbol?(0,n.some)(w.symbol):(0,n.none)(),q=typeof w.pointer=="number"?(0,n.some)(w.pointer):(0,n.none)(),K=new g(R,M,(0,n.some)(O),v,C,(0,n.some)(A),!0);return new m([],(0,n.some)(K),(0,n.none)(),q)}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(),C=R.getPointer();return(0,n.some)(new m(R.edicts,M,v,C))}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 D=1<<a.Terms;R|=D}if(T.turbo){let D=1<<a.Turbo;R|=D}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 C=T.spacers.value();C!==null&&w.set(u.Spacers,[BigInt(C)]);const q=T.symbol.value();q!==null&&w.set(u.Symbol,[BigInt(q.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 D=H.height.start.value();D&&w.set(u.HeightStart,[BigInt(D)]);const P=H.height.end.value();P&&w.set(u.HeightEnd,[BigInt(P)]);const $=H.offset.start.value();$&&w.set(u.OffsetStart,[BigInt($)]);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)}}ze.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 C=T[v];if(Number(C)===u.Body){M=!0,v+=1;continue}if(M){let q=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=q.next(K[0],K[1]);if(!H.isSome()){R|=f.EdictRuneId;break}const D=c.from_integers(w,H.value(),K[2],K[3]);if(!D.isSome()){R|=f.EdictOutput;break}q=H.value(),A.push(D.value())}v+=4}else{let q=T[v+1];const K=O.get(Number(C))||[];K.push(q),O.set(Number(C),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 C=v-O;O=v,w.push(Buffer.from((0,r.encodeLEB128)(0n))),w.push(Buffer.from((0,r.encodeLEB128)(C)))}else{const C=M-T;T=M,O=v,w.push(Buffer.from((0,r.encodeLEB128)(C))),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),C=new l(R,M);return(0,n.some)(new d(T.value(),w.value(),v,C))}getPointer(){if(!this.fields.has(u.Pointer))return(0,n.none)();const[w]=this.fields.get(u.Pointer);return(0,n.some)(Number(w))}}ze.Message=E;class S{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(S.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,C=[];let q=!1;for(let K=5;K<M.length-1;){const H=M[K];if(H===0){q=!0,K++;continue}else if(q)C.push(H),K++;else{const D=H-80,P=M[K+1];if(typeof P=="number"){const $=Buffer.alloc(1);$.writeUint8(P),v.set(D,$)}else v.set(D,P);K+=2}}return new S(v,Buffer.concat(C))}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(S.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 ze.EtchInscription=S,S.Tag={CONTENT_TYPE:1,POINTER:2,PARENT:3,METADATA:5,METAPROTOCOL:7,CONTENT_ENCODING:9,DELEGATE:11,RUNE:13},ze}var dy;function FA(){return dy||(dy=1,(function(e){var t=bi&&bi.__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=bi&&bi.__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(HA(),e);var r=Zw();Object.defineProperty(e,"none",{enumerable:!0,get:function(){return r.none}}),Object.defineProperty(e,"some",{enumerable:!0,get:function(){return r.some}});var i=Jw();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}})})(bi)),bi}var us=FA();function Qw(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:Uy}function Bh(e,t=Ns.Testnet){const n=Oh(t);return Tg(e,n)}function ds(e){const t=Pn,n=Uy,r=W1;let i,s,o=mn.UNKNOWN;if(e.startsWith("bc1")||e.startsWith("tb1")||e.startsWith("bcrt1"))try{return s=kl(e),s.version===0?s.data.length===20?o=mn.P2WPKH:o=mn.P2WSH:o=mn.P2TR,o}catch{return mn.UNKNOWN}else try{return i=Sg(e),i.version===t.pubKeyHash||i.version===n.pubKeyHash||i.version===r.pubKeyHash?o=mn.P2PKH:(i.version===t.scriptHash||(i.version,n.scriptHash),o=mn.P2SH_P2WPKH),o}catch{return mn.UNKNOWN}}function MA(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 LA=Object.freeze(Object.defineProperty({__proto__:null,bytesToHex:Ih,formatPoolUtxo:MA,getAddressType:ds,getScriptByAddress:Bh,getUtxoProof:e1,hexToBytes:Qw,toBitcoinNetwork:Oh},Symbol.toStringTag,{value:"Module"})),qA="kqs64-paaaa-aaaar-qamza-cai",VA="hvyp5-5yaaa-aaaao-qjxha-cai",Gc=BigInt(546),Jn="0:0",DA="https://runescan-hasura-mainnet.omnity.network/v1/graphql",$A="https://runescan-hasura-testnet.omnity.network/v1/graphql";class t1{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(r=>r.txid===t.txid&&r.vout===t.vout)>=0)return;const{address:n}=t;this.psbt.data.addInput({hash:t.txid,index:t.vout,witnessUtxo:{value:BigInt(t.satoshis),script:Qw(t.scriptPk)}}),this.inputAddressTypes.push(ds(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(ds(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=this.userInputUtxoDusts;this.outputAddressTypes.push(ds(r));let o=BigInt(0),c=BigInt(0),a=[],u=BigInt(0),f=BigInt(0);const l=[...this.inputAddressTypes];do if(o=c,c=(await this.client.orchestrator.estimate_min_tx_fee({input_types:this.inputAddressTypes,pool_address:this.intentions.map(m=>m.poolAddress),output_types:this.outputAddressTypes})).Ok,u=n+c+i-s,c>o&&u>0){const m=this.selectBtcUtxos(t,u);if(m.length===0)throw new Error("INSUFFICIENT_BTC_UTXOs");this.inputAddressTypes=l.concat([...m.map(()=>ds(r))]);const E=m.reduce((S,_)=>S+BigInt(_.satoshis),BigInt(0));E-u>0&&E-u>Gc||this.outputAddressTypes.pop(),a=m}while(c>o&&u>0);let d=BigInt(0);a.forEach(g=>{this.addInput(g),d+=BigInt(g.satoshis)});const y=d-u;if(y<0)throw new Error("Insufficient UTXO(s)");y>Gc?this.addOutput(r,y):y>BigInt(0)&&(f=y),this.txFee=f+c}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===Jn?f.needBtc=!0:f.runeIds.add(u.coin.id)}for(const u of o.outputCoins){const f=s(u.to);u.coin.id===Jn?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===Jn?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(s=>s.poolAddress),r={},i={};this.intentions.forEach(({poolAddress:s,inputCoins:o,outputCoins:c})=>{const a=[...o],u=[...c];a.forEach(({coin:f,from:l})=>{!u.find(d=>d.coin.id===f.id)&&!(n.includes(l)&&l!==s)&&u.push({coin:f,to:s})}),u.forEach(({coin:f,to:l})=>{!a.find(d=>d.coin.id===f.id)&&!n.includes(l)&&a.push({coin:f,from:s})}),a.forEach(({coin:f,from:l})=>{r[l]??={},r[l][f.id]=(r[l][f.id]??BigInt(0))+BigInt(f.value)}),u.forEach(({coin:f,to:l})=>{i[l]??={},i[l][f.id]=(i[l][f.id]??BigInt(0))+BigInt(f.value)})});for(const[s,o]of Object.entries(r))for(const[c,a]of Object.entries(o))if(c===Jn){if(s===this.config.paymentAddress){i[s]??={},i[s][c]=(i[s][c]??BigInt(0))-a;continue}const u=t.btc[s]||[],f=this.selectBtcUtxos(u,a,n.includes(s)),d=f.reduce((y,g)=>y+BigInt(g.satoshis),BigInt(0))-a;d>BigInt(0)&&(i[s]??={},i[s][c]=(i[s][c]??BigInt(0))+d),f.forEach(y=>{this.addInput(y),n.includes(s)&&y.runes.forEach(g=>{i[s]??={},i[s][g.id]=(i[s][g.id]??BigInt(0))+BigInt(g.amount)})})}else{const u=t.rune[s]?.[c]||[],f=this.selectRuneUtxos(u,c,a),d=f.reduce((y,g)=>{const m=g.runes.find(E=>E.id===c);return y+BigInt(m?.amount??0)},BigInt(0))-a;d>BigInt(0)&&(i[s]??={},i[s][c]=(i[s][c]??BigInt(0))+d),f.forEach(y=>this.addInput(y))}for(const[s,o]of Object.entries(i))if(!(r[s]||!n.includes(s)))for(const[c]of Object.entries(o))if(c===Jn){const a=t.btc[s]||[],u=a.reduce((f,l)=>f+BigInt(l.satoshis),BigInt(0));i[s]??={},i[s][c]=(i[s][c]??BigInt(0))+u,a.forEach(f=>{this.addInput(f),f.runes.forEach(l=>{i[s]??={},i[s][l.id]=(i[s][l.id]??BigInt(0))+BigInt(l.amount)})})}else{const a=t.rune[s]?.[c]||[],u=a.reduce((f,l)=>{const d=l.runes.find(y=>y.id===c);return f+BigInt(d?.amount??0)},BigInt(0));i[s]??={},i[s][c]=(i[s][c]??BigInt(0))+u,a.forEach(f=>this.addInput(f))}return i}addOutputs(t){const n=new Set;for(const[,i]of Object.entries(t))for(const s of Object.keys(i))s!==Jn&&n.add(s);const r=Array.from(n);if(r.length>0){const i=[],s=[];let o=1;r.forEach(a=>{const u=new us.RuneId(Number(a.split(":")[0]),Number(a.split(":")[1]));for(const[f,l]of Object.entries(t)){const d=l[a]??BigInt(0);d>BigInt(0)&&(i.push(new us.Edict(u,d,o)),s.push(f),o++)}});const c=new us.Runestone(i,us.none(),us.none(),us.none());this.addScriptOutput(new Uint8Array(c.encipher())),s.forEach(a=>{const u=t[a]?.[Jn]??BigInt(0),f=u>BigInt(0)&&a!==this.config.address?u:Gc;this.addOutput(a,f),u>BigInt(0)&&a!==this.config.address?delete t[a][Jn]:this.additionalDustNeeded+=Gc})}for(const[i,s]of Object.entries(t)){const o=s[Jn]??BigInt(0);o>BigInt(0)&&this.addOutput(i,o)}}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?.length)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 n=this.addInputsAndCalculateOutputs(t);this.addOutputs(n);const r=this.config.paymentAddress,i=t.btc[r]??[],s=n[r]?.[Jn]??BigInt(0);await this.addBtcAndFees(i,s<0?-s:BigInt(0));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=ds(l);if(d&&y===mn.P2SH_P2WPKH){const g=nn([d]);c.setInputScript(u,g)}}const a=c.getId();return{psbt:this.psbt,txid:a}}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,nonce:u})=>({exchange_id:this.config.exchangeId,input_coins:c.filter(f=>f.from!==o),output_coins:a,pool_address:o,action:i,action_params:s??"",pool_utxo_spent:[],pool_utxo_received:[],nonce:u}))},initiator_utxo_proof:r,psbt_hex:t}).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 py=e=>e.toUpperCase(),Cf=e=>typeof e=="function"?e():e,n1=(e,t)=>e.map((n,r)=>[n,t[r]]),fs=e=>{let t={};return e instanceof Headers?t=jA(e):Array.isArray(e)?e.forEach(([n,r])=>{n&&r!==void 0&&(t[n]=r)}):e&&(t=e),t},jA=e=>{const t={};return e.forEach((n,r)=>{t[r]=n}),t},KA=e=>{try{const t=e();return GA(t)?t.catch(n=>yy(n)):t}catch(t){return yy(t)}},yy=e=>e instanceof Error?e:new Error(String(e)),GA=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),WA=(e,t)=>e.documents?e:{documents:e,requestHeaders:t,signal:void 0},XA=(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 zA(e){return typeof e=="object"&&e!==null}function YA(e,t){if(!!!e)throw new Error("Unexpected invariant triggered.")}const ZA=/\r\n|[\n\r]/g;function pl(e,t){let n=0,r=1;for(const i of e.body.matchAll(ZA)){if(typeof i.index=="number"||YA(!1),i.index>=t)break;n=i.index+i[0].length,r+=1}return{line:r,column:t+1-n}}function JA(e){return r1(e.source,pl(e.source,e.start))}function r1(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+gy([[`${o} |`,g[0]],...g.slice(1,d+1).map(m=>["|",m]),["|","^".padStart(y)],["|",g[d+1]]])}return u+gy([[`${o-1} |`,f[i-1]],[`${o} |`,l],["|","^".padStart(a)],[`${o+1} |`,f[i+1]]])}function gy(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 QA(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}=QA(n);super(t),this.name="GraphQLError",this.path=u??void 0,this.originalError=f??void 0,this.nodes=my(Array.isArray(o)?o:o?[o]:void 0);const d=my((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=zA(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
 
80
80
  `+JA(n.loc));else if(this.source&&this.locations)for(const n of this.locations)t+=`
81
81
 
82
- `+r1(this.source,n);return t}toJSON(){const t={message:this.message};return this.locations!=null&&(t.locations=this.locations),this.path!=null&&(t.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(t.extensions=this.extensions),t}}function my(e){return e===void 0||e.length===0?void 0:e}function kt(e,t,n){return new kh(`Syntax Error: ${n}`,{source:e,positions:[t]})}class ev{constructor(t,n,r){this.start=t.start,this.end=n.end,this.startToken=t,this.endToken=n,this.source=r}get[Symbol.toStringTag](){return"Location"}toJSON(){return{start:this.start,end:this.end}}}class i1{constructor(t,n,r,i,s,o){this.kind=t,this.start=n,this.end=r,this.line=i,this.column=s,this.value=o,this.prev=null,this.next=null}get[Symbol.toStringTag](){return"Token"}toJSON(){return{kind:this.kind,value:this.value,line:this.line,column:this.column}}}const s1={Name:[],Document:["definitions"],OperationDefinition:["name","variableDefinitions","directives","selectionSet"],VariableDefinition:["variable","type","defaultValue","directives"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["name","variableDefinitions","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["description","directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["description","name","directives"],ObjectTypeDefinition:["description","name","interfaces","directives","fields"],FieldDefinition:["description","name","arguments","type","directives"],InputValueDefinition:["description","name","type","defaultValue","directives"],InterfaceTypeDefinition:["description","name","interfaces","directives","fields"],UnionTypeDefinition:["description","name","directives","types"],EnumTypeDefinition:["description","name","directives","values"],EnumValueDefinition:["description","name","directives"],InputObjectTypeDefinition:["description","name","directives","fields"],DirectiveDefinition:["description","name","arguments","locations"],SchemaExtension:["directives","operationTypes"],ScalarTypeExtension:["name","directives"],ObjectTypeExtension:["name","interfaces","directives","fields"],InterfaceTypeExtension:["name","interfaces","directives","fields"],UnionTypeExtension:["name","directives","types"],EnumTypeExtension:["name","directives","values"],InputObjectTypeExtension:["name","directives","fields"]},tv=new Set(Object.keys(s1));function wy(e){const t=e?.kind;return typeof t=="string"&&tv.has(t)}var gs;(function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription"})(gs||(gs={}));var yl;(function(e){e.QUERY="QUERY",e.MUTATION="MUTATION",e.SUBSCRIPTION="SUBSCRIPTION",e.FIELD="FIELD",e.FRAGMENT_DEFINITION="FRAGMENT_DEFINITION",e.FRAGMENT_SPREAD="FRAGMENT_SPREAD",e.INLINE_FRAGMENT="INLINE_FRAGMENT",e.VARIABLE_DEFINITION="VARIABLE_DEFINITION",e.SCHEMA="SCHEMA",e.SCALAR="SCALAR",e.OBJECT="OBJECT",e.FIELD_DEFINITION="FIELD_DEFINITION",e.ARGUMENT_DEFINITION="ARGUMENT_DEFINITION",e.INTERFACE="INTERFACE",e.UNION="UNION",e.ENUM="ENUM",e.ENUM_VALUE="ENUM_VALUE",e.INPUT_OBJECT="INPUT_OBJECT",e.INPUT_FIELD_DEFINITION="INPUT_FIELD_DEFINITION"})(yl||(yl={}));var Se;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(Se||(Se={}));function gl(e){return e===9||e===32}function $o(e){return e>=48&&e<=57}function o1(e){return e>=97&&e<=122||e>=65&&e<=90}function c1(e){return o1(e)||e===95}function nv(e){return o1(e)||$o(e)||e===95}function rv(e){var t;let n=Number.MAX_SAFE_INTEGER,r=null,i=-1;for(let o=0;o<e.length;++o){var s;const c=e[o],a=iv(c);a!==c.length&&(r=(s=r)!==null&&s!==void 0?s:o,i=o,o!==0&&a<n&&(n=a))}return e.map((o,c)=>c===0?o:o.slice(n)).slice((t=r)!==null&&t!==void 0?t:0,i+1)}function iv(e){let t=0;for(;t<e.length&&gl(e.charCodeAt(t));)++t;return t}function sv(e,t){const n=e.replace(/"""/g,'\\"""'),r=n.split(/\r\n|[\n\r]/g),i=r.length===1,s=r.length>1&&r.slice(1).every(y=>y.length===0||gl(y.charCodeAt(0))),o=n.endsWith('\\"""'),c=e.endsWith('"')&&!o,a=e.endsWith("\\"),u=c||a,f=!i||e.length>70||u||s||o;let l="";const d=i&&gl(e.charCodeAt(0));return(f&&!d||s)&&(l+=`
82
+ `+r1(this.source,n);return t}toJSON(){const t={message:this.message};return this.locations!=null&&(t.locations=this.locations),this.path!=null&&(t.path=this.path),this.extensions!=null&&Object.keys(this.extensions).length>0&&(t.extensions=this.extensions),t}}function my(e){return e===void 0||e.length===0?void 0:e}function kt(e,t,n){return new kh(`Syntax Error: ${n}`,{source:e,positions:[t]})}class ev{constructor(t,n,r){this.start=t.start,this.end=n.end,this.startToken=t,this.endToken=n,this.source=r}get[Symbol.toStringTag](){return"Location"}toJSON(){return{start:this.start,end:this.end}}}class i1{constructor(t,n,r,i,s,o){this.kind=t,this.start=n,this.end=r,this.line=i,this.column=s,this.value=o,this.prev=null,this.next=null}get[Symbol.toStringTag](){return"Token"}toJSON(){return{kind:this.kind,value:this.value,line:this.line,column:this.column}}}const s1={Name:[],Document:["definitions"],OperationDefinition:["name","variableDefinitions","directives","selectionSet"],VariableDefinition:["variable","type","defaultValue","directives"],Variable:["name"],SelectionSet:["selections"],Field:["alias","name","arguments","directives","selectionSet"],Argument:["name","value"],FragmentSpread:["name","directives"],InlineFragment:["typeCondition","directives","selectionSet"],FragmentDefinition:["name","variableDefinitions","typeCondition","directives","selectionSet"],IntValue:[],FloatValue:[],StringValue:[],BooleanValue:[],NullValue:[],EnumValue:[],ListValue:["values"],ObjectValue:["fields"],ObjectField:["name","value"],Directive:["name","arguments"],NamedType:["name"],ListType:["type"],NonNullType:["type"],SchemaDefinition:["description","directives","operationTypes"],OperationTypeDefinition:["type"],ScalarTypeDefinition:["description","name","directives"],ObjectTypeDefinition:["description","name","interfaces","directives","fields"],FieldDefinition:["description","name","arguments","type","directives"],InputValueDefinition:["description","name","type","defaultValue","directives"],InterfaceTypeDefinition:["description","name","interfaces","directives","fields"],UnionTypeDefinition:["description","name","directives","types"],EnumTypeDefinition:["description","name","directives","values"],EnumValueDefinition:["description","name","directives"],InputObjectTypeDefinition:["description","name","directives","fields"],DirectiveDefinition:["description","name","arguments","locations"],SchemaExtension:["directives","operationTypes"],ScalarTypeExtension:["name","directives"],ObjectTypeExtension:["name","interfaces","directives","fields"],InterfaceTypeExtension:["name","interfaces","directives","fields"],UnionTypeExtension:["name","directives","types"],EnumTypeExtension:["name","directives","values"],InputObjectTypeExtension:["name","directives","fields"]},tv=new Set(Object.keys(s1));function wy(e){const t=e?.kind;return typeof t=="string"&&tv.has(t)}var ms;(function(e){e.QUERY="query",e.MUTATION="mutation",e.SUBSCRIPTION="subscription"})(ms||(ms={}));var yl;(function(e){e.QUERY="QUERY",e.MUTATION="MUTATION",e.SUBSCRIPTION="SUBSCRIPTION",e.FIELD="FIELD",e.FRAGMENT_DEFINITION="FRAGMENT_DEFINITION",e.FRAGMENT_SPREAD="FRAGMENT_SPREAD",e.INLINE_FRAGMENT="INLINE_FRAGMENT",e.VARIABLE_DEFINITION="VARIABLE_DEFINITION",e.SCHEMA="SCHEMA",e.SCALAR="SCALAR",e.OBJECT="OBJECT",e.FIELD_DEFINITION="FIELD_DEFINITION",e.ARGUMENT_DEFINITION="ARGUMENT_DEFINITION",e.INTERFACE="INTERFACE",e.UNION="UNION",e.ENUM="ENUM",e.ENUM_VALUE="ENUM_VALUE",e.INPUT_OBJECT="INPUT_OBJECT",e.INPUT_FIELD_DEFINITION="INPUT_FIELD_DEFINITION"})(yl||(yl={}));var Se;(function(e){e.NAME="Name",e.DOCUMENT="Document",e.OPERATION_DEFINITION="OperationDefinition",e.VARIABLE_DEFINITION="VariableDefinition",e.SELECTION_SET="SelectionSet",e.FIELD="Field",e.ARGUMENT="Argument",e.FRAGMENT_SPREAD="FragmentSpread",e.INLINE_FRAGMENT="InlineFragment",e.FRAGMENT_DEFINITION="FragmentDefinition",e.VARIABLE="Variable",e.INT="IntValue",e.FLOAT="FloatValue",e.STRING="StringValue",e.BOOLEAN="BooleanValue",e.NULL="NullValue",e.ENUM="EnumValue",e.LIST="ListValue",e.OBJECT="ObjectValue",e.OBJECT_FIELD="ObjectField",e.DIRECTIVE="Directive",e.NAMED_TYPE="NamedType",e.LIST_TYPE="ListType",e.NON_NULL_TYPE="NonNullType",e.SCHEMA_DEFINITION="SchemaDefinition",e.OPERATION_TYPE_DEFINITION="OperationTypeDefinition",e.SCALAR_TYPE_DEFINITION="ScalarTypeDefinition",e.OBJECT_TYPE_DEFINITION="ObjectTypeDefinition",e.FIELD_DEFINITION="FieldDefinition",e.INPUT_VALUE_DEFINITION="InputValueDefinition",e.INTERFACE_TYPE_DEFINITION="InterfaceTypeDefinition",e.UNION_TYPE_DEFINITION="UnionTypeDefinition",e.ENUM_TYPE_DEFINITION="EnumTypeDefinition",e.ENUM_VALUE_DEFINITION="EnumValueDefinition",e.INPUT_OBJECT_TYPE_DEFINITION="InputObjectTypeDefinition",e.DIRECTIVE_DEFINITION="DirectiveDefinition",e.SCHEMA_EXTENSION="SchemaExtension",e.SCALAR_TYPE_EXTENSION="ScalarTypeExtension",e.OBJECT_TYPE_EXTENSION="ObjectTypeExtension",e.INTERFACE_TYPE_EXTENSION="InterfaceTypeExtension",e.UNION_TYPE_EXTENSION="UnionTypeExtension",e.ENUM_TYPE_EXTENSION="EnumTypeExtension",e.INPUT_OBJECT_TYPE_EXTENSION="InputObjectTypeExtension"})(Se||(Se={}));function gl(e){return e===9||e===32}function $o(e){return e>=48&&e<=57}function o1(e){return e>=97&&e<=122||e>=65&&e<=90}function c1(e){return o1(e)||e===95}function nv(e){return o1(e)||$o(e)||e===95}function rv(e){var t;let n=Number.MAX_SAFE_INTEGER,r=null,i=-1;for(let o=0;o<e.length;++o){var s;const c=e[o],a=iv(c);a!==c.length&&(r=(s=r)!==null&&s!==void 0?s:o,i=o,o!==0&&a<n&&(n=a))}return e.map((o,c)=>c===0?o:o.slice(n)).slice((t=r)!==null&&t!==void 0?t:0,i+1)}function iv(e){let t=0;for(;t<e.length&&gl(e.charCodeAt(t));)++t;return t}function sv(e,t){const n=e.replace(/"""/g,'\\"""'),r=n.split(/\r\n|[\n\r]/g),i=r.length===1,s=r.length>1&&r.slice(1).every(y=>y.length===0||gl(y.charCodeAt(0))),o=n.endsWith('\\"""'),c=e.endsWith('"')&&!o,a=e.endsWith("\\"),u=c||a,f=!i||e.length>70||u||s||o;let l="";const d=i&&gl(e.charCodeAt(0));return(f&&!d||s)&&(l+=`
83
83
  `),l+=n,(f||u)&&(l+=`
84
- `),'"""'+l+'"""'}var ee;(function(e){e.SOF="<SOF>",e.EOF="<EOF>",e.BANG="!",e.DOLLAR="$",e.AMP="&",e.PAREN_L="(",e.PAREN_R=")",e.SPREAD="...",e.COLON=":",e.EQUALS="=",e.AT="@",e.BRACKET_L="[",e.BRACKET_R="]",e.BRACE_L="{",e.PIPE="|",e.BRACE_R="}",e.NAME="Name",e.INT="Int",e.FLOAT="Float",e.STRING="String",e.BLOCK_STRING="BlockString",e.COMMENT="Comment"})(ee||(ee={}));class ov{constructor(t){const n=new i1(ee.SOF,0,0,0,0);this.source=t,this.lastToken=n,this.token=n,this.line=1,this.lineStart=0}get[Symbol.toStringTag](){return"Lexer"}advance(){return this.lastToken=this.token,this.token=this.lookahead()}lookahead(){let t=this.token;if(t.kind!==ee.EOF)do if(t.next)t=t.next;else{const n=av(this,t.end);t.next=n,n.prev=t,t=n}while(t.kind===ee.COMMENT);return t}}function cv(e){return e===ee.BANG||e===ee.DOLLAR||e===ee.AMP||e===ee.PAREN_L||e===ee.PAREN_R||e===ee.SPREAD||e===ee.COLON||e===ee.EQUALS||e===ee.AT||e===ee.BRACKET_L||e===ee.BRACKET_R||e===ee.BRACE_L||e===ee.PIPE||e===ee.BRACE_R}function Ws(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function _u(e,t){return a1(e.charCodeAt(t))&&u1(e.charCodeAt(t+1))}function a1(e){return e>=55296&&e<=56319}function u1(e){return e>=56320&&e<=57343}function Wi(e,t){const n=e.source.body.codePointAt(t);if(n===void 0)return ee.EOF;if(n>=32&&n<=126){const r=String.fromCodePoint(n);return r==='"'?`'"'`:`"${r}"`}return"U+"+n.toString(16).toUpperCase().padStart(4,"0")}function Et(e,t,n,r,i){const s=e.line,o=1+n-e.lineStart;return new i1(t,n,r,s,o,i)}function av(e,t){const n=e.source.body,r=n.length;let i=t;for(;i<r;){const s=n.charCodeAt(i);switch(s){case 65279:case 9:case 32:case 44:++i;continue;case 10:++i,++e.line,e.lineStart=i;continue;case 13:n.charCodeAt(i+1)===10?i+=2:++i,++e.line,e.lineStart=i;continue;case 35:return uv(e,i);case 33:return Et(e,ee.BANG,i,i+1);case 36:return Et(e,ee.DOLLAR,i,i+1);case 38:return Et(e,ee.AMP,i,i+1);case 40:return Et(e,ee.PAREN_L,i,i+1);case 41:return Et(e,ee.PAREN_R,i,i+1);case 46:if(n.charCodeAt(i+1)===46&&n.charCodeAt(i+2)===46)return Et(e,ee.SPREAD,i,i+3);break;case 58:return Et(e,ee.COLON,i,i+1);case 61:return Et(e,ee.EQUALS,i,i+1);case 64:return Et(e,ee.AT,i,i+1);case 91:return Et(e,ee.BRACKET_L,i,i+1);case 93:return Et(e,ee.BRACKET_R,i,i+1);case 123:return Et(e,ee.BRACE_L,i,i+1);case 124:return Et(e,ee.PIPE,i,i+1);case 125:return Et(e,ee.BRACE_R,i,i+1);case 34:return n.charCodeAt(i+1)===34&&n.charCodeAt(i+2)===34?yv(e,i):lv(e,i)}if($o(s)||s===45)return fv(e,i,s);if(c1(s))return gv(e,i);throw kt(e.source,i,s===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:Ws(s)||_u(n,i)?`Unexpected character: ${Wi(e,i)}.`:`Invalid character: ${Wi(e,i)}.`)}return Et(e,ee.EOF,r,r)}function uv(e,t){const n=e.source.body,r=n.length;let i=t+1;for(;i<r;){const s=n.charCodeAt(i);if(s===10||s===13)break;if(Ws(s))++i;else if(_u(n,i))i+=2;else break}return Et(e,ee.COMMENT,t,i,n.slice(t+1,i))}function fv(e,t,n){const r=e.source.body;let i=t,s=n,o=!1;if(s===45&&(s=r.charCodeAt(++i)),s===48){if(s=r.charCodeAt(++i),$o(s))throw kt(e.source,i,`Invalid number, unexpected digit after 0: ${Wi(e,i)}.`)}else i=Uf(e,i,s),s=r.charCodeAt(i);if(s===46&&(o=!0,s=r.charCodeAt(++i),i=Uf(e,i,s),s=r.charCodeAt(i)),(s===69||s===101)&&(o=!0,s=r.charCodeAt(++i),(s===43||s===45)&&(s=r.charCodeAt(++i)),i=Uf(e,i,s),s=r.charCodeAt(i)),s===46||c1(s))throw kt(e.source,i,`Invalid number, expected digit but got: ${Wi(e,i)}.`);return Et(e,o?ee.FLOAT:ee.INT,t,i,r.slice(t,i))}function Uf(e,t,n){if(!$o(n))throw kt(e.source,t,`Invalid number, expected digit but got: ${Wi(e,t)}.`);const r=e.source.body;let i=t+1;for(;$o(r.charCodeAt(i));)++i;return i}function lv(e,t){const n=e.source.body,r=n.length;let i=t+1,s=i,o="";for(;i<r;){const c=n.charCodeAt(i);if(c===34)return o+=n.slice(s,i),Et(e,ee.STRING,t,i+1,o);if(c===92){o+=n.slice(s,i);const a=n.charCodeAt(i+1)===117?n.charCodeAt(i+2)===123?hv(e,i):dv(e,i):pv(e,i);o+=a.value,i+=a.size,s=i;continue}if(c===10||c===13)break;if(Ws(c))++i;else if(_u(n,i))i+=2;else throw kt(e.source,i,`Invalid character within String: ${Wi(e,i)}.`)}throw kt(e.source,i,"Unterminated string.")}function hv(e,t){const n=e.source.body;let r=0,i=3;for(;i<12;){const s=n.charCodeAt(t+i++);if(s===125){if(i<5||!Ws(r))break;return{value:String.fromCodePoint(r),size:i}}if(r=r<<4|Eo(s),r<0)break}throw kt(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+i)}".`)}function dv(e,t){const n=e.source.body,r=by(n,t+2);if(Ws(r))return{value:String.fromCodePoint(r),size:6};if(a1(r)&&n.charCodeAt(t+6)===92&&n.charCodeAt(t+7)===117){const i=by(n,t+8);if(u1(i))return{value:String.fromCodePoint(r,i),size:12}}throw kt(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+6)}".`)}function by(e,t){return Eo(e.charCodeAt(t))<<12|Eo(e.charCodeAt(t+1))<<8|Eo(e.charCodeAt(t+2))<<4|Eo(e.charCodeAt(t+3))}function Eo(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:-1}function pv(e,t){const n=e.source.body;switch(n.charCodeAt(t+1)){case 34:return{value:'"',size:2};case 92:return{value:"\\",size:2};case 47:return{value:"/",size:2};case 98:return{value:"\b",size:2};case 102:return{value:"\f",size:2};case 110:return{value:`
84
+ `),'"""'+l+'"""'}var ee;(function(e){e.SOF="<SOF>",e.EOF="<EOF>",e.BANG="!",e.DOLLAR="$",e.AMP="&",e.PAREN_L="(",e.PAREN_R=")",e.SPREAD="...",e.COLON=":",e.EQUALS="=",e.AT="@",e.BRACKET_L="[",e.BRACKET_R="]",e.BRACE_L="{",e.PIPE="|",e.BRACE_R="}",e.NAME="Name",e.INT="Int",e.FLOAT="Float",e.STRING="String",e.BLOCK_STRING="BlockString",e.COMMENT="Comment"})(ee||(ee={}));class ov{constructor(t){const n=new i1(ee.SOF,0,0,0,0);this.source=t,this.lastToken=n,this.token=n,this.line=1,this.lineStart=0}get[Symbol.toStringTag](){return"Lexer"}advance(){return this.lastToken=this.token,this.token=this.lookahead()}lookahead(){let t=this.token;if(t.kind!==ee.EOF)do if(t.next)t=t.next;else{const n=av(this,t.end);t.next=n,n.prev=t,t=n}while(t.kind===ee.COMMENT);return t}}function cv(e){return e===ee.BANG||e===ee.DOLLAR||e===ee.AMP||e===ee.PAREN_L||e===ee.PAREN_R||e===ee.SPREAD||e===ee.COLON||e===ee.EQUALS||e===ee.AT||e===ee.BRACKET_L||e===ee.BRACKET_R||e===ee.BRACE_L||e===ee.PIPE||e===ee.BRACE_R}function Xs(e){return e>=0&&e<=55295||e>=57344&&e<=1114111}function _u(e,t){return a1(e.charCodeAt(t))&&u1(e.charCodeAt(t+1))}function a1(e){return e>=55296&&e<=56319}function u1(e){return e>=56320&&e<=57343}function Wi(e,t){const n=e.source.body.codePointAt(t);if(n===void 0)return ee.EOF;if(n>=32&&n<=126){const r=String.fromCodePoint(n);return r==='"'?`'"'`:`"${r}"`}return"U+"+n.toString(16).toUpperCase().padStart(4,"0")}function Et(e,t,n,r,i){const s=e.line,o=1+n-e.lineStart;return new i1(t,n,r,s,o,i)}function av(e,t){const n=e.source.body,r=n.length;let i=t;for(;i<r;){const s=n.charCodeAt(i);switch(s){case 65279:case 9:case 32:case 44:++i;continue;case 10:++i,++e.line,e.lineStart=i;continue;case 13:n.charCodeAt(i+1)===10?i+=2:++i,++e.line,e.lineStart=i;continue;case 35:return uv(e,i);case 33:return Et(e,ee.BANG,i,i+1);case 36:return Et(e,ee.DOLLAR,i,i+1);case 38:return Et(e,ee.AMP,i,i+1);case 40:return Et(e,ee.PAREN_L,i,i+1);case 41:return Et(e,ee.PAREN_R,i,i+1);case 46:if(n.charCodeAt(i+1)===46&&n.charCodeAt(i+2)===46)return Et(e,ee.SPREAD,i,i+3);break;case 58:return Et(e,ee.COLON,i,i+1);case 61:return Et(e,ee.EQUALS,i,i+1);case 64:return Et(e,ee.AT,i,i+1);case 91:return Et(e,ee.BRACKET_L,i,i+1);case 93:return Et(e,ee.BRACKET_R,i,i+1);case 123:return Et(e,ee.BRACE_L,i,i+1);case 124:return Et(e,ee.PIPE,i,i+1);case 125:return Et(e,ee.BRACE_R,i,i+1);case 34:return n.charCodeAt(i+1)===34&&n.charCodeAt(i+2)===34?yv(e,i):lv(e,i)}if($o(s)||s===45)return fv(e,i,s);if(c1(s))return gv(e,i);throw kt(e.source,i,s===39?`Unexpected single quote character ('), did you mean to use a double quote (")?`:Xs(s)||_u(n,i)?`Unexpected character: ${Wi(e,i)}.`:`Invalid character: ${Wi(e,i)}.`)}return Et(e,ee.EOF,r,r)}function uv(e,t){const n=e.source.body,r=n.length;let i=t+1;for(;i<r;){const s=n.charCodeAt(i);if(s===10||s===13)break;if(Xs(s))++i;else if(_u(n,i))i+=2;else break}return Et(e,ee.COMMENT,t,i,n.slice(t+1,i))}function fv(e,t,n){const r=e.source.body;let i=t,s=n,o=!1;if(s===45&&(s=r.charCodeAt(++i)),s===48){if(s=r.charCodeAt(++i),$o(s))throw kt(e.source,i,`Invalid number, unexpected digit after 0: ${Wi(e,i)}.`)}else i=Uf(e,i,s),s=r.charCodeAt(i);if(s===46&&(o=!0,s=r.charCodeAt(++i),i=Uf(e,i,s),s=r.charCodeAt(i)),(s===69||s===101)&&(o=!0,s=r.charCodeAt(++i),(s===43||s===45)&&(s=r.charCodeAt(++i)),i=Uf(e,i,s),s=r.charCodeAt(i)),s===46||c1(s))throw kt(e.source,i,`Invalid number, expected digit but got: ${Wi(e,i)}.`);return Et(e,o?ee.FLOAT:ee.INT,t,i,r.slice(t,i))}function Uf(e,t,n){if(!$o(n))throw kt(e.source,t,`Invalid number, expected digit but got: ${Wi(e,t)}.`);const r=e.source.body;let i=t+1;for(;$o(r.charCodeAt(i));)++i;return i}function lv(e,t){const n=e.source.body,r=n.length;let i=t+1,s=i,o="";for(;i<r;){const c=n.charCodeAt(i);if(c===34)return o+=n.slice(s,i),Et(e,ee.STRING,t,i+1,o);if(c===92){o+=n.slice(s,i);const a=n.charCodeAt(i+1)===117?n.charCodeAt(i+2)===123?hv(e,i):dv(e,i):pv(e,i);o+=a.value,i+=a.size,s=i;continue}if(c===10||c===13)break;if(Xs(c))++i;else if(_u(n,i))i+=2;else throw kt(e.source,i,`Invalid character within String: ${Wi(e,i)}.`)}throw kt(e.source,i,"Unterminated string.")}function hv(e,t){const n=e.source.body;let r=0,i=3;for(;i<12;){const s=n.charCodeAt(t+i++);if(s===125){if(i<5||!Xs(r))break;return{value:String.fromCodePoint(r),size:i}}if(r=r<<4|Eo(s),r<0)break}throw kt(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+i)}".`)}function dv(e,t){const n=e.source.body,r=by(n,t+2);if(Xs(r))return{value:String.fromCodePoint(r),size:6};if(a1(r)&&n.charCodeAt(t+6)===92&&n.charCodeAt(t+7)===117){const i=by(n,t+8);if(u1(i))return{value:String.fromCodePoint(r,i),size:12}}throw kt(e.source,t,`Invalid Unicode escape sequence: "${n.slice(t,t+6)}".`)}function by(e,t){return Eo(e.charCodeAt(t))<<12|Eo(e.charCodeAt(t+1))<<8|Eo(e.charCodeAt(t+2))<<4|Eo(e.charCodeAt(t+3))}function Eo(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-55:e>=97&&e<=102?e-87:-1}function pv(e,t){const n=e.source.body;switch(n.charCodeAt(t+1)){case 34:return{value:'"',size:2};case 92:return{value:"\\",size:2};case 47:return{value:"/",size:2};case 98:return{value:"\b",size:2};case 102:return{value:"\f",size:2};case 110:return{value:`
85
85
  `,size:2};case 114:return{value:"\r",size:2};case 116:return{value:" ",size:2}}throw kt(e.source,t,`Invalid character escape sequence: "${n.slice(t,t+2)}".`)}function yv(e,t){const n=e.source.body,r=n.length;let i=e.lineStart,s=t+3,o=s,c="";const a=[];for(;s<r;){const u=n.charCodeAt(s);if(u===34&&n.charCodeAt(s+1)===34&&n.charCodeAt(s+2)===34){c+=n.slice(o,s),a.push(c);const f=Et(e,ee.BLOCK_STRING,t,s+3,rv(a).join(`
86
- `));return e.line+=a.length-1,e.lineStart=i,f}if(u===92&&n.charCodeAt(s+1)===34&&n.charCodeAt(s+2)===34&&n.charCodeAt(s+3)===34){c+=n.slice(o,s),o=s+1,s+=4;continue}if(u===10||u===13){c+=n.slice(o,s),a.push(c),u===13&&n.charCodeAt(s+1)===10?s+=2:++s,c="",o=s,i=s;continue}if(Ws(u))++s;else if(_u(n,s))s+=2;else throw kt(e.source,s,`Invalid character within String: ${Wi(e,s)}.`)}throw kt(e.source,s,"Unterminated string.")}function gv(e,t){const n=e.source.body,r=n.length;let i=t+1;for(;i<r;){const s=n.charCodeAt(i);if(nv(s))++i;else break}return Et(e,ee.NAME,t,i,n.slice(t,i))}const mv=10,f1=2;function Ph(e){return Su(e,[])}function Su(e,t){switch(typeof e){case"string":return JSON.stringify(e);case"function":return e.name?`[function ${e.name}]`:"[function]";case"object":return wv(e,t);default:return String(e)}}function wv(e,t){if(e===null)return"null";if(t.includes(e))return"[Circular]";const n=[...t,e];if(bv(e)){const r=e.toJSON();if(r!==e)return typeof r=="string"?r:Su(r,n)}else if(Array.isArray(e))return _v(e,n);return Ev(e,n)}function bv(e){return typeof e.toJSON=="function"}function Ev(e,t){const n=Object.entries(e);return n.length===0?"{}":t.length>f1?"["+Sv(e)+"]":"{ "+n.map(([i,s])=>i+": "+Su(s,t)).join(", ")+" }"}function _v(e,t){if(e.length===0)return"[]";if(t.length>f1)return"[Array]";const n=Math.min(mv,e.length),r=e.length-n,i=[];for(let s=0;s<n;++s)i.push(Su(e[s],t));return r===1?i.push("... 1 more item"):r>1&&i.push(`... ${r} more items`),"["+i.join(", ")+"]"}function Sv(e){const t=Object.prototype.toString.call(e).replace(/^\[object /,"").replace(/]$/,"");if(t==="Object"&&typeof e.constructor=="function"){const n=e.constructor.name;if(typeof n=="string"&&n!=="")return n}return t}const Tv=globalThis.process&&process.env.NODE_ENV==="production",xv=Tv?function(t,n){return t instanceof n}:function(t,n){if(t instanceof n)return!0;if(typeof t=="object"&&t!==null){var r;const i=n.prototype[Symbol.toStringTag],s=Symbol.toStringTag in t?t[Symbol.toStringTag]:(r=t.constructor)===null||r===void 0?void 0:r.name;if(i===s){const o=Ph(t);throw new Error(`Cannot use ${i} "${o}" from another module or realm.
86
+ `));return e.line+=a.length-1,e.lineStart=i,f}if(u===92&&n.charCodeAt(s+1)===34&&n.charCodeAt(s+2)===34&&n.charCodeAt(s+3)===34){c+=n.slice(o,s),o=s+1,s+=4;continue}if(u===10||u===13){c+=n.slice(o,s),a.push(c),u===13&&n.charCodeAt(s+1)===10?s+=2:++s,c="",o=s,i=s;continue}if(Xs(u))++s;else if(_u(n,s))s+=2;else throw kt(e.source,s,`Invalid character within String: ${Wi(e,s)}.`)}throw kt(e.source,s,"Unterminated string.")}function gv(e,t){const n=e.source.body,r=n.length;let i=t+1;for(;i<r;){const s=n.charCodeAt(i);if(nv(s))++i;else break}return Et(e,ee.NAME,t,i,n.slice(t,i))}const mv=10,f1=2;function Ph(e){return Su(e,[])}function Su(e,t){switch(typeof e){case"string":return JSON.stringify(e);case"function":return e.name?`[function ${e.name}]`:"[function]";case"object":return wv(e,t);default:return String(e)}}function wv(e,t){if(e===null)return"null";if(t.includes(e))return"[Circular]";const n=[...t,e];if(bv(e)){const r=e.toJSON();if(r!==e)return typeof r=="string"?r:Su(r,n)}else if(Array.isArray(e))return _v(e,n);return Ev(e,n)}function bv(e){return typeof e.toJSON=="function"}function Ev(e,t){const n=Object.entries(e);return n.length===0?"{}":t.length>f1?"["+Sv(e)+"]":"{ "+n.map(([i,s])=>i+": "+Su(s,t)).join(", ")+" }"}function _v(e,t){if(e.length===0)return"[]";if(t.length>f1)return"[Array]";const n=Math.min(mv,e.length),r=e.length-n,i=[];for(let s=0;s<n;++s)i.push(Su(e[s],t));return r===1?i.push("... 1 more item"):r>1&&i.push(`... ${r} more items`),"["+i.join(", ")+"]"}function Sv(e){const t=Object.prototype.toString.call(e).replace(/^\[object /,"").replace(/]$/,"");if(t==="Object"&&typeof e.constructor=="function"){const n=e.constructor.name;if(typeof n=="string"&&n!=="")return n}return t}const Tv=globalThis.process&&process.env.NODE_ENV==="production",xv=Tv?function(t,n){return t instanceof n}:function(t,n){if(t instanceof n)return!0;if(typeof t=="object"&&t!==null){var r;const i=n.prototype[Symbol.toStringTag],s=Symbol.toStringTag in t?t[Symbol.toStringTag]:(r=t.constructor)===null||r===void 0?void 0:r.name;if(i===s){const o=Ph(t);throw new Error(`Cannot use ${i} "${o}" from another module or realm.
87
87
 
88
88
  Ensure that there is only one instance of "graphql" in the node_modules
89
89
  directory. If different versions of "graphql" are the dependencies of other
@@ -94,7 +94,7 @@ https://yarnpkg.com/en/docs/selective-version-resolutions
94
94
  Duplicate "graphql" modules cannot be used at the same time since different
95
95
  versions may have different capabilities and behavior. The data from one
96
96
  version used in the function from another could produce confusing and
97
- spurious results.`)}}return!1};class l1{constructor(t,n="GraphQL request",r={line:1,column:1}){typeof t=="string"||ia(!1,`Body must be a string. Received: ${Ph(t)}.`),this.body=t,this.name=n,this.locationOffset=r,this.locationOffset.line>0||ia(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||ia(!1,"column in locationOffset is 1-indexed and must be positive.")}get[Symbol.toStringTag](){return"Source"}}function Av(e){return xv(e,l1)}function vv(e,t){const n=new Iv(e,t),r=n.parseDocument();return Object.defineProperty(r,"tokenCount",{enumerable:!1,value:n.tokenCount}),r}class Iv{constructor(t,n={}){const r=Av(t)?t:new l1(t);this._lexer=new ov(r),this._options=n,this._tokenCounter=0}get tokenCount(){return this._tokenCounter}parseName(){const t=this.expectToken(ee.NAME);return this.node(t,{kind:Se.NAME,value:t.value})}parseDocument(){return this.node(this._lexer.token,{kind:Se.DOCUMENT,definitions:this.many(ee.SOF,this.parseDefinition,ee.EOF)})}parseDefinition(){if(this.peek(ee.BRACE_L))return this.parseOperationDefinition();const t=this.peekDescription(),n=t?this._lexer.lookahead():this._lexer.token;if(n.kind===ee.NAME){switch(n.value){case"schema":return this.parseSchemaDefinition();case"scalar":return this.parseScalarTypeDefinition();case"type":return this.parseObjectTypeDefinition();case"interface":return this.parseInterfaceTypeDefinition();case"union":return this.parseUnionTypeDefinition();case"enum":return this.parseEnumTypeDefinition();case"input":return this.parseInputObjectTypeDefinition();case"directive":return this.parseDirectiveDefinition()}if(t)throw kt(this._lexer.source,this._lexer.token.start,"Unexpected description, descriptions are supported only on type definitions.");switch(n.value){case"query":case"mutation":case"subscription":return this.parseOperationDefinition();case"fragment":return this.parseFragmentDefinition();case"extend":return this.parseTypeSystemExtension()}}throw this.unexpected(n)}parseOperationDefinition(){const t=this._lexer.token;if(this.peek(ee.BRACE_L))return this.node(t,{kind:Se.OPERATION_DEFINITION,operation:gs.QUERY,name:void 0,variableDefinitions:[],directives:[],selectionSet:this.parseSelectionSet()});const n=this.parseOperationType();let r;return this.peek(ee.NAME)&&(r=this.parseName()),this.node(t,{kind:Se.OPERATION_DEFINITION,operation:n,name:r,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseOperationType(){const t=this.expectToken(ee.NAME);switch(t.value){case"query":return gs.QUERY;case"mutation":return gs.MUTATION;case"subscription":return gs.SUBSCRIPTION}throw this.unexpected(t)}parseVariableDefinitions(){return this.optionalMany(ee.PAREN_L,this.parseVariableDefinition,ee.PAREN_R)}parseVariableDefinition(){return this.node(this._lexer.token,{kind:Se.VARIABLE_DEFINITION,variable:this.parseVariable(),type:(this.expectToken(ee.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(ee.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()})}parseVariable(){const t=this._lexer.token;return this.expectToken(ee.DOLLAR),this.node(t,{kind:Se.VARIABLE,name:this.parseName()})}parseSelectionSet(){return this.node(this._lexer.token,{kind:Se.SELECTION_SET,selections:this.many(ee.BRACE_L,this.parseSelection,ee.BRACE_R)})}parseSelection(){return this.peek(ee.SPREAD)?this.parseFragment():this.parseField()}parseField(){const t=this._lexer.token,n=this.parseName();let r,i;return this.expectOptionalToken(ee.COLON)?(r=n,i=this.parseName()):i=n,this.node(t,{kind:Se.FIELD,alias:r,name:i,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(ee.BRACE_L)?this.parseSelectionSet():void 0})}parseArguments(t){const n=t?this.parseConstArgument:this.parseArgument;return this.optionalMany(ee.PAREN_L,n,ee.PAREN_R)}parseArgument(t=!1){const n=this._lexer.token,r=this.parseName();return this.expectToken(ee.COLON),this.node(n,{kind:Se.ARGUMENT,name:r,value:this.parseValueLiteral(t)})}parseConstArgument(){return this.parseArgument(!0)}parseFragment(){const t=this._lexer.token;this.expectToken(ee.SPREAD);const n=this.expectOptionalKeyword("on");return!n&&this.peek(ee.NAME)?this.node(t,{kind:Se.FRAGMENT_SPREAD,name:this.parseFragmentName(),directives:this.parseDirectives(!1)}):this.node(t,{kind:Se.INLINE_FRAGMENT,typeCondition:n?this.parseNamedType():void 0,directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentDefinition(){const t=this._lexer.token;return this.expectKeyword("fragment"),this._options.allowLegacyFragmentVariables===!0?this.node(t,{kind:Se.FRAGMENT_DEFINITION,name:this.parseFragmentName(),variableDefinitions:this.parseVariableDefinitions(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()}):this.node(t,{kind:Se.FRAGMENT_DEFINITION,name:this.parseFragmentName(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentName(){if(this._lexer.token.value==="on")throw this.unexpected();return this.parseName()}parseValueLiteral(t){const n=this._lexer.token;switch(n.kind){case ee.BRACKET_L:return this.parseList(t);case ee.BRACE_L:return this.parseObject(t);case ee.INT:return this.advanceLexer(),this.node(n,{kind:Se.INT,value:n.value});case ee.FLOAT:return this.advanceLexer(),this.node(n,{kind:Se.FLOAT,value:n.value});case ee.STRING:case ee.BLOCK_STRING:return this.parseStringLiteral();case ee.NAME:switch(this.advanceLexer(),n.value){case"true":return this.node(n,{kind:Se.BOOLEAN,value:!0});case"false":return this.node(n,{kind:Se.BOOLEAN,value:!1});case"null":return this.node(n,{kind:Se.NULL});default:return this.node(n,{kind:Se.ENUM,value:n.value})}case ee.DOLLAR:if(t)if(this.expectToken(ee.DOLLAR),this._lexer.token.kind===ee.NAME){const r=this._lexer.token.value;throw kt(this._lexer.source,n.start,`Unexpected variable "$${r}" in constant value.`)}else throw this.unexpected(n);return this.parseVariable();default:throw this.unexpected()}}parseConstValueLiteral(){return this.parseValueLiteral(!0)}parseStringLiteral(){const t=this._lexer.token;return this.advanceLexer(),this.node(t,{kind:Se.STRING,value:t.value,block:t.kind===ee.BLOCK_STRING})}parseList(t){const n=()=>this.parseValueLiteral(t);return this.node(this._lexer.token,{kind:Se.LIST,values:this.any(ee.BRACKET_L,n,ee.BRACKET_R)})}parseObject(t){const n=()=>this.parseObjectField(t);return this.node(this._lexer.token,{kind:Se.OBJECT,fields:this.any(ee.BRACE_L,n,ee.BRACE_R)})}parseObjectField(t){const n=this._lexer.token,r=this.parseName();return this.expectToken(ee.COLON),this.node(n,{kind:Se.OBJECT_FIELD,name:r,value:this.parseValueLiteral(t)})}parseDirectives(t){const n=[];for(;this.peek(ee.AT);)n.push(this.parseDirective(t));return n}parseConstDirectives(){return this.parseDirectives(!0)}parseDirective(t){const n=this._lexer.token;return this.expectToken(ee.AT),this.node(n,{kind:Se.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(t)})}parseTypeReference(){const t=this._lexer.token;let n;if(this.expectOptionalToken(ee.BRACKET_L)){const r=this.parseTypeReference();this.expectToken(ee.BRACKET_R),n=this.node(t,{kind:Se.LIST_TYPE,type:r})}else n=this.parseNamedType();return this.expectOptionalToken(ee.BANG)?this.node(t,{kind:Se.NON_NULL_TYPE,type:n}):n}parseNamedType(){return this.node(this._lexer.token,{kind:Se.NAMED_TYPE,name:this.parseName()})}peekDescription(){return this.peek(ee.STRING)||this.peek(ee.BLOCK_STRING)}parseDescription(){if(this.peekDescription())return this.parseStringLiteral()}parseSchemaDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("schema");const r=this.parseConstDirectives(),i=this.many(ee.BRACE_L,this.parseOperationTypeDefinition,ee.BRACE_R);return this.node(t,{kind:Se.SCHEMA_DEFINITION,description:n,directives:r,operationTypes:i})}parseOperationTypeDefinition(){const t=this._lexer.token,n=this.parseOperationType();this.expectToken(ee.COLON);const r=this.parseNamedType();return this.node(t,{kind:Se.OPERATION_TYPE_DEFINITION,operation:n,type:r})}parseScalarTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("scalar");const r=this.parseName(),i=this.parseConstDirectives();return this.node(t,{kind:Se.SCALAR_TYPE_DEFINITION,description:n,name:r,directives:i})}parseObjectTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("type");const r=this.parseName(),i=this.parseImplementsInterfaces(),s=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(t,{kind:Se.OBJECT_TYPE_DEFINITION,description:n,name:r,interfaces:i,directives:s,fields:o})}parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(ee.AMP,this.parseNamedType):[]}parseFieldsDefinition(){return this.optionalMany(ee.BRACE_L,this.parseFieldDefinition,ee.BRACE_R)}parseFieldDefinition(){const t=this._lexer.token,n=this.parseDescription(),r=this.parseName(),i=this.parseArgumentDefs();this.expectToken(ee.COLON);const s=this.parseTypeReference(),o=this.parseConstDirectives();return this.node(t,{kind:Se.FIELD_DEFINITION,description:n,name:r,arguments:i,type:s,directives:o})}parseArgumentDefs(){return this.optionalMany(ee.PAREN_L,this.parseInputValueDef,ee.PAREN_R)}parseInputValueDef(){const t=this._lexer.token,n=this.parseDescription(),r=this.parseName();this.expectToken(ee.COLON);const i=this.parseTypeReference();let s;this.expectOptionalToken(ee.EQUALS)&&(s=this.parseConstValueLiteral());const o=this.parseConstDirectives();return this.node(t,{kind:Se.INPUT_VALUE_DEFINITION,description:n,name:r,type:i,defaultValue:s,directives:o})}parseInterfaceTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("interface");const r=this.parseName(),i=this.parseImplementsInterfaces(),s=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(t,{kind:Se.INTERFACE_TYPE_DEFINITION,description:n,name:r,interfaces:i,directives:s,fields:o})}parseUnionTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("union");const r=this.parseName(),i=this.parseConstDirectives(),s=this.parseUnionMemberTypes();return this.node(t,{kind:Se.UNION_TYPE_DEFINITION,description:n,name:r,directives:i,types:s})}parseUnionMemberTypes(){return this.expectOptionalToken(ee.EQUALS)?this.delimitedMany(ee.PIPE,this.parseNamedType):[]}parseEnumTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("enum");const r=this.parseName(),i=this.parseConstDirectives(),s=this.parseEnumValuesDefinition();return this.node(t,{kind:Se.ENUM_TYPE_DEFINITION,description:n,name:r,directives:i,values:s})}parseEnumValuesDefinition(){return this.optionalMany(ee.BRACE_L,this.parseEnumValueDefinition,ee.BRACE_R)}parseEnumValueDefinition(){const t=this._lexer.token,n=this.parseDescription(),r=this.parseEnumValueName(),i=this.parseConstDirectives();return this.node(t,{kind:Se.ENUM_VALUE_DEFINITION,description:n,name:r,directives:i})}parseEnumValueName(){if(this._lexer.token.value==="true"||this._lexer.token.value==="false"||this._lexer.token.value==="null")throw kt(this._lexer.source,this._lexer.token.start,`${Wc(this._lexer.token)} is reserved and cannot be used for an enum value.`);return this.parseName()}parseInputObjectTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("input");const r=this.parseName(),i=this.parseConstDirectives(),s=this.parseInputFieldsDefinition();return this.node(t,{kind:Se.INPUT_OBJECT_TYPE_DEFINITION,description:n,name:r,directives:i,fields:s})}parseInputFieldsDefinition(){return this.optionalMany(ee.BRACE_L,this.parseInputValueDef,ee.BRACE_R)}parseTypeSystemExtension(){const t=this._lexer.lookahead();if(t.kind===ee.NAME)switch(t.value){case"schema":return this.parseSchemaExtension();case"scalar":return this.parseScalarTypeExtension();case"type":return this.parseObjectTypeExtension();case"interface":return this.parseInterfaceTypeExtension();case"union":return this.parseUnionTypeExtension();case"enum":return this.parseEnumTypeExtension();case"input":return this.parseInputObjectTypeExtension()}throw this.unexpected(t)}parseSchemaExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("schema");const n=this.parseConstDirectives(),r=this.optionalMany(ee.BRACE_L,this.parseOperationTypeDefinition,ee.BRACE_R);if(n.length===0&&r.length===0)throw this.unexpected();return this.node(t,{kind:Se.SCHEMA_EXTENSION,directives:n,operationTypes:r})}parseScalarTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("scalar");const n=this.parseName(),r=this.parseConstDirectives();if(r.length===0)throw this.unexpected();return this.node(t,{kind:Se.SCALAR_TYPE_EXTENSION,name:n,directives:r})}parseObjectTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("type");const n=this.parseName(),r=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),s=this.parseFieldsDefinition();if(r.length===0&&i.length===0&&s.length===0)throw this.unexpected();return this.node(t,{kind:Se.OBJECT_TYPE_EXTENSION,name:n,interfaces:r,directives:i,fields:s})}parseInterfaceTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("interface");const n=this.parseName(),r=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),s=this.parseFieldsDefinition();if(r.length===0&&i.length===0&&s.length===0)throw this.unexpected();return this.node(t,{kind:Se.INTERFACE_TYPE_EXTENSION,name:n,interfaces:r,directives:i,fields:s})}parseUnionTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("union");const n=this.parseName(),r=this.parseConstDirectives(),i=this.parseUnionMemberTypes();if(r.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:Se.UNION_TYPE_EXTENSION,name:n,directives:r,types:i})}parseEnumTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("enum");const n=this.parseName(),r=this.parseConstDirectives(),i=this.parseEnumValuesDefinition();if(r.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:Se.ENUM_TYPE_EXTENSION,name:n,directives:r,values:i})}parseInputObjectTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("input");const n=this.parseName(),r=this.parseConstDirectives(),i=this.parseInputFieldsDefinition();if(r.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:Se.INPUT_OBJECT_TYPE_EXTENSION,name:n,directives:r,fields:i})}parseDirectiveDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("directive"),this.expectToken(ee.AT);const r=this.parseName(),i=this.parseArgumentDefs(),s=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");const o=this.parseDirectiveLocations();return this.node(t,{kind:Se.DIRECTIVE_DEFINITION,description:n,name:r,arguments:i,repeatable:s,locations:o})}parseDirectiveLocations(){return this.delimitedMany(ee.PIPE,this.parseDirectiveLocation)}parseDirectiveLocation(){const t=this._lexer.token,n=this.parseName();if(Object.prototype.hasOwnProperty.call(yl,n.value))return n;throw this.unexpected(t)}node(t,n){return this._options.noLocation!==!0&&(n.loc=new ev(t,this._lexer.lastToken,this._lexer.source)),n}peek(t){return this._lexer.token.kind===t}expectToken(t){const n=this._lexer.token;if(n.kind===t)return this.advanceLexer(),n;throw kt(this._lexer.source,n.start,`Expected ${h1(t)}, found ${Wc(n)}.`)}expectOptionalToken(t){return this._lexer.token.kind===t?(this.advanceLexer(),!0):!1}expectKeyword(t){const n=this._lexer.token;if(n.kind===ee.NAME&&n.value===t)this.advanceLexer();else throw kt(this._lexer.source,n.start,`Expected "${t}", found ${Wc(n)}.`)}expectOptionalKeyword(t){const n=this._lexer.token;return n.kind===ee.NAME&&n.value===t?(this.advanceLexer(),!0):!1}unexpected(t){const n=t??this._lexer.token;return kt(this._lexer.source,n.start,`Unexpected ${Wc(n)}.`)}any(t,n,r){this.expectToken(t);const i=[];for(;!this.expectOptionalToken(r);)i.push(n.call(this));return i}optionalMany(t,n,r){if(this.expectOptionalToken(t)){const i=[];do i.push(n.call(this));while(!this.expectOptionalToken(r));return i}return[]}many(t,n,r){this.expectToken(t);const i=[];do i.push(n.call(this));while(!this.expectOptionalToken(r));return i}delimitedMany(t,n){this.expectOptionalToken(t);const r=[];do r.push(n.call(this));while(this.expectOptionalToken(t));return r}advanceLexer(){const{maxTokens:t}=this._options,n=this._lexer.advance();if(n.kind!==ee.EOF&&(++this._tokenCounter,t!==void 0&&this._tokenCounter>t))throw kt(this._lexer.source,n.start,`Document contains more that ${t} tokens. Parsing aborted.`)}}function Wc(e){const t=e.value;return h1(e.kind)+(t!=null?` "${t}"`:"")}function h1(e){return cv(e)?`"${e}"`:e}function Ov(e){return`"${e.replace(Bv,Nv)}"`}const Bv=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function Nv(e){return kv[e.charCodeAt(0)]}const kv=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000B","\\f","\\r","\\u000E","\\u000F","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001A","\\u001B","\\u001C","\\u001D","\\u001E","\\u001F","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\u007F","\\u0080","\\u0081","\\u0082","\\u0083","\\u0084","\\u0085","\\u0086","\\u0087","\\u0088","\\u0089","\\u008A","\\u008B","\\u008C","\\u008D","\\u008E","\\u008F","\\u0090","\\u0091","\\u0092","\\u0093","\\u0094","\\u0095","\\u0096","\\u0097","\\u0098","\\u0099","\\u009A","\\u009B","\\u009C","\\u009D","\\u009E","\\u009F"],Pv=Object.freeze({});function Rv(e,t,n=s1){const r=new Map;for(const S of Object.values(Se))r.set(S,Cv(t,S));let i,s=Array.isArray(e),o=[e],c=-1,a=[],u=e,f,l;const d=[],y=[];do{c++;const S=c===o.length,_=S&&a.length!==0;if(S){if(f=y.length===0?void 0:d[d.length-1],u=l,l=y.pop(),_)if(s){u=u.slice();let T=0;for(const[O,A]of a){const R=O-T;A===null?(u.splice(R,1),T++):u[R]=A}}else{u={...u};for(const[T,O]of a)u[T]=O}c=i.index,o=i.keys,a=i.edits,s=i.inArray,i=i.prev}else if(l){if(f=s?c:o[c],u=l[f],u==null)continue;d.push(f)}let w;if(!Array.isArray(u)){var g,m;wy(u)||ia(!1,`Invalid AST Node: ${Ph(u)}.`);const T=S?(g=r.get(u.kind))===null||g===void 0?void 0:g.leave:(m=r.get(u.kind))===null||m===void 0?void 0:m.enter;if(w=T?.call(t,u,f,l,d,y),w===Pv)break;if(w===!1){if(!S){d.pop();continue}}else if(w!==void 0&&(a.push([f,w]),!S))if(wy(w))u=w;else{d.pop();continue}}if(w===void 0&&_&&a.push([f,u]),S)d.pop();else{var E;i={inArray:s,index:c,keys:o,edits:a,prev:i},s=Array.isArray(u),o=s?u:(E=n[u.kind])!==null&&E!==void 0?E:[],c=-1,a=[],l&&y.push(l),l=u}}while(i!==void 0);return a.length!==0?a[a.length-1][1]:e}function Cv(e,t){const n=e[t];return typeof n=="object"?n:typeof n=="function"?{enter:n,leave:void 0}:{enter:e.enter,leave:e.leave}}function Uv(e){return Rv(e,Fv)}const Hv=80,Fv={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>ye(e.definitions,`
97
+ spurious results.`)}}return!1};class l1{constructor(t,n="GraphQL request",r={line:1,column:1}){typeof t=="string"||ia(!1,`Body must be a string. Received: ${Ph(t)}.`),this.body=t,this.name=n,this.locationOffset=r,this.locationOffset.line>0||ia(!1,"line in locationOffset is 1-indexed and must be positive."),this.locationOffset.column>0||ia(!1,"column in locationOffset is 1-indexed and must be positive.")}get[Symbol.toStringTag](){return"Source"}}function Av(e){return xv(e,l1)}function vv(e,t){const n=new Iv(e,t),r=n.parseDocument();return Object.defineProperty(r,"tokenCount",{enumerable:!1,value:n.tokenCount}),r}class Iv{constructor(t,n={}){const r=Av(t)?t:new l1(t);this._lexer=new ov(r),this._options=n,this._tokenCounter=0}get tokenCount(){return this._tokenCounter}parseName(){const t=this.expectToken(ee.NAME);return this.node(t,{kind:Se.NAME,value:t.value})}parseDocument(){return this.node(this._lexer.token,{kind:Se.DOCUMENT,definitions:this.many(ee.SOF,this.parseDefinition,ee.EOF)})}parseDefinition(){if(this.peek(ee.BRACE_L))return this.parseOperationDefinition();const t=this.peekDescription(),n=t?this._lexer.lookahead():this._lexer.token;if(n.kind===ee.NAME){switch(n.value){case"schema":return this.parseSchemaDefinition();case"scalar":return this.parseScalarTypeDefinition();case"type":return this.parseObjectTypeDefinition();case"interface":return this.parseInterfaceTypeDefinition();case"union":return this.parseUnionTypeDefinition();case"enum":return this.parseEnumTypeDefinition();case"input":return this.parseInputObjectTypeDefinition();case"directive":return this.parseDirectiveDefinition()}if(t)throw kt(this._lexer.source,this._lexer.token.start,"Unexpected description, descriptions are supported only on type definitions.");switch(n.value){case"query":case"mutation":case"subscription":return this.parseOperationDefinition();case"fragment":return this.parseFragmentDefinition();case"extend":return this.parseTypeSystemExtension()}}throw this.unexpected(n)}parseOperationDefinition(){const t=this._lexer.token;if(this.peek(ee.BRACE_L))return this.node(t,{kind:Se.OPERATION_DEFINITION,operation:ms.QUERY,name:void 0,variableDefinitions:[],directives:[],selectionSet:this.parseSelectionSet()});const n=this.parseOperationType();let r;return this.peek(ee.NAME)&&(r=this.parseName()),this.node(t,{kind:Se.OPERATION_DEFINITION,operation:n,name:r,variableDefinitions:this.parseVariableDefinitions(),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseOperationType(){const t=this.expectToken(ee.NAME);switch(t.value){case"query":return ms.QUERY;case"mutation":return ms.MUTATION;case"subscription":return ms.SUBSCRIPTION}throw this.unexpected(t)}parseVariableDefinitions(){return this.optionalMany(ee.PAREN_L,this.parseVariableDefinition,ee.PAREN_R)}parseVariableDefinition(){return this.node(this._lexer.token,{kind:Se.VARIABLE_DEFINITION,variable:this.parseVariable(),type:(this.expectToken(ee.COLON),this.parseTypeReference()),defaultValue:this.expectOptionalToken(ee.EQUALS)?this.parseConstValueLiteral():void 0,directives:this.parseConstDirectives()})}parseVariable(){const t=this._lexer.token;return this.expectToken(ee.DOLLAR),this.node(t,{kind:Se.VARIABLE,name:this.parseName()})}parseSelectionSet(){return this.node(this._lexer.token,{kind:Se.SELECTION_SET,selections:this.many(ee.BRACE_L,this.parseSelection,ee.BRACE_R)})}parseSelection(){return this.peek(ee.SPREAD)?this.parseFragment():this.parseField()}parseField(){const t=this._lexer.token,n=this.parseName();let r,i;return this.expectOptionalToken(ee.COLON)?(r=n,i=this.parseName()):i=n,this.node(t,{kind:Se.FIELD,alias:r,name:i,arguments:this.parseArguments(!1),directives:this.parseDirectives(!1),selectionSet:this.peek(ee.BRACE_L)?this.parseSelectionSet():void 0})}parseArguments(t){const n=t?this.parseConstArgument:this.parseArgument;return this.optionalMany(ee.PAREN_L,n,ee.PAREN_R)}parseArgument(t=!1){const n=this._lexer.token,r=this.parseName();return this.expectToken(ee.COLON),this.node(n,{kind:Se.ARGUMENT,name:r,value:this.parseValueLiteral(t)})}parseConstArgument(){return this.parseArgument(!0)}parseFragment(){const t=this._lexer.token;this.expectToken(ee.SPREAD);const n=this.expectOptionalKeyword("on");return!n&&this.peek(ee.NAME)?this.node(t,{kind:Se.FRAGMENT_SPREAD,name:this.parseFragmentName(),directives:this.parseDirectives(!1)}):this.node(t,{kind:Se.INLINE_FRAGMENT,typeCondition:n?this.parseNamedType():void 0,directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentDefinition(){const t=this._lexer.token;return this.expectKeyword("fragment"),this._options.allowLegacyFragmentVariables===!0?this.node(t,{kind:Se.FRAGMENT_DEFINITION,name:this.parseFragmentName(),variableDefinitions:this.parseVariableDefinitions(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()}):this.node(t,{kind:Se.FRAGMENT_DEFINITION,name:this.parseFragmentName(),typeCondition:(this.expectKeyword("on"),this.parseNamedType()),directives:this.parseDirectives(!1),selectionSet:this.parseSelectionSet()})}parseFragmentName(){if(this._lexer.token.value==="on")throw this.unexpected();return this.parseName()}parseValueLiteral(t){const n=this._lexer.token;switch(n.kind){case ee.BRACKET_L:return this.parseList(t);case ee.BRACE_L:return this.parseObject(t);case ee.INT:return this.advanceLexer(),this.node(n,{kind:Se.INT,value:n.value});case ee.FLOAT:return this.advanceLexer(),this.node(n,{kind:Se.FLOAT,value:n.value});case ee.STRING:case ee.BLOCK_STRING:return this.parseStringLiteral();case ee.NAME:switch(this.advanceLexer(),n.value){case"true":return this.node(n,{kind:Se.BOOLEAN,value:!0});case"false":return this.node(n,{kind:Se.BOOLEAN,value:!1});case"null":return this.node(n,{kind:Se.NULL});default:return this.node(n,{kind:Se.ENUM,value:n.value})}case ee.DOLLAR:if(t)if(this.expectToken(ee.DOLLAR),this._lexer.token.kind===ee.NAME){const r=this._lexer.token.value;throw kt(this._lexer.source,n.start,`Unexpected variable "$${r}" in constant value.`)}else throw this.unexpected(n);return this.parseVariable();default:throw this.unexpected()}}parseConstValueLiteral(){return this.parseValueLiteral(!0)}parseStringLiteral(){const t=this._lexer.token;return this.advanceLexer(),this.node(t,{kind:Se.STRING,value:t.value,block:t.kind===ee.BLOCK_STRING})}parseList(t){const n=()=>this.parseValueLiteral(t);return this.node(this._lexer.token,{kind:Se.LIST,values:this.any(ee.BRACKET_L,n,ee.BRACKET_R)})}parseObject(t){const n=()=>this.parseObjectField(t);return this.node(this._lexer.token,{kind:Se.OBJECT,fields:this.any(ee.BRACE_L,n,ee.BRACE_R)})}parseObjectField(t){const n=this._lexer.token,r=this.parseName();return this.expectToken(ee.COLON),this.node(n,{kind:Se.OBJECT_FIELD,name:r,value:this.parseValueLiteral(t)})}parseDirectives(t){const n=[];for(;this.peek(ee.AT);)n.push(this.parseDirective(t));return n}parseConstDirectives(){return this.parseDirectives(!0)}parseDirective(t){const n=this._lexer.token;return this.expectToken(ee.AT),this.node(n,{kind:Se.DIRECTIVE,name:this.parseName(),arguments:this.parseArguments(t)})}parseTypeReference(){const t=this._lexer.token;let n;if(this.expectOptionalToken(ee.BRACKET_L)){const r=this.parseTypeReference();this.expectToken(ee.BRACKET_R),n=this.node(t,{kind:Se.LIST_TYPE,type:r})}else n=this.parseNamedType();return this.expectOptionalToken(ee.BANG)?this.node(t,{kind:Se.NON_NULL_TYPE,type:n}):n}parseNamedType(){return this.node(this._lexer.token,{kind:Se.NAMED_TYPE,name:this.parseName()})}peekDescription(){return this.peek(ee.STRING)||this.peek(ee.BLOCK_STRING)}parseDescription(){if(this.peekDescription())return this.parseStringLiteral()}parseSchemaDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("schema");const r=this.parseConstDirectives(),i=this.many(ee.BRACE_L,this.parseOperationTypeDefinition,ee.BRACE_R);return this.node(t,{kind:Se.SCHEMA_DEFINITION,description:n,directives:r,operationTypes:i})}parseOperationTypeDefinition(){const t=this._lexer.token,n=this.parseOperationType();this.expectToken(ee.COLON);const r=this.parseNamedType();return this.node(t,{kind:Se.OPERATION_TYPE_DEFINITION,operation:n,type:r})}parseScalarTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("scalar");const r=this.parseName(),i=this.parseConstDirectives();return this.node(t,{kind:Se.SCALAR_TYPE_DEFINITION,description:n,name:r,directives:i})}parseObjectTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("type");const r=this.parseName(),i=this.parseImplementsInterfaces(),s=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(t,{kind:Se.OBJECT_TYPE_DEFINITION,description:n,name:r,interfaces:i,directives:s,fields:o})}parseImplementsInterfaces(){return this.expectOptionalKeyword("implements")?this.delimitedMany(ee.AMP,this.parseNamedType):[]}parseFieldsDefinition(){return this.optionalMany(ee.BRACE_L,this.parseFieldDefinition,ee.BRACE_R)}parseFieldDefinition(){const t=this._lexer.token,n=this.parseDescription(),r=this.parseName(),i=this.parseArgumentDefs();this.expectToken(ee.COLON);const s=this.parseTypeReference(),o=this.parseConstDirectives();return this.node(t,{kind:Se.FIELD_DEFINITION,description:n,name:r,arguments:i,type:s,directives:o})}parseArgumentDefs(){return this.optionalMany(ee.PAREN_L,this.parseInputValueDef,ee.PAREN_R)}parseInputValueDef(){const t=this._lexer.token,n=this.parseDescription(),r=this.parseName();this.expectToken(ee.COLON);const i=this.parseTypeReference();let s;this.expectOptionalToken(ee.EQUALS)&&(s=this.parseConstValueLiteral());const o=this.parseConstDirectives();return this.node(t,{kind:Se.INPUT_VALUE_DEFINITION,description:n,name:r,type:i,defaultValue:s,directives:o})}parseInterfaceTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("interface");const r=this.parseName(),i=this.parseImplementsInterfaces(),s=this.parseConstDirectives(),o=this.parseFieldsDefinition();return this.node(t,{kind:Se.INTERFACE_TYPE_DEFINITION,description:n,name:r,interfaces:i,directives:s,fields:o})}parseUnionTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("union");const r=this.parseName(),i=this.parseConstDirectives(),s=this.parseUnionMemberTypes();return this.node(t,{kind:Se.UNION_TYPE_DEFINITION,description:n,name:r,directives:i,types:s})}parseUnionMemberTypes(){return this.expectOptionalToken(ee.EQUALS)?this.delimitedMany(ee.PIPE,this.parseNamedType):[]}parseEnumTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("enum");const r=this.parseName(),i=this.parseConstDirectives(),s=this.parseEnumValuesDefinition();return this.node(t,{kind:Se.ENUM_TYPE_DEFINITION,description:n,name:r,directives:i,values:s})}parseEnumValuesDefinition(){return this.optionalMany(ee.BRACE_L,this.parseEnumValueDefinition,ee.BRACE_R)}parseEnumValueDefinition(){const t=this._lexer.token,n=this.parseDescription(),r=this.parseEnumValueName(),i=this.parseConstDirectives();return this.node(t,{kind:Se.ENUM_VALUE_DEFINITION,description:n,name:r,directives:i})}parseEnumValueName(){if(this._lexer.token.value==="true"||this._lexer.token.value==="false"||this._lexer.token.value==="null")throw kt(this._lexer.source,this._lexer.token.start,`${Wc(this._lexer.token)} is reserved and cannot be used for an enum value.`);return this.parseName()}parseInputObjectTypeDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("input");const r=this.parseName(),i=this.parseConstDirectives(),s=this.parseInputFieldsDefinition();return this.node(t,{kind:Se.INPUT_OBJECT_TYPE_DEFINITION,description:n,name:r,directives:i,fields:s})}parseInputFieldsDefinition(){return this.optionalMany(ee.BRACE_L,this.parseInputValueDef,ee.BRACE_R)}parseTypeSystemExtension(){const t=this._lexer.lookahead();if(t.kind===ee.NAME)switch(t.value){case"schema":return this.parseSchemaExtension();case"scalar":return this.parseScalarTypeExtension();case"type":return this.parseObjectTypeExtension();case"interface":return this.parseInterfaceTypeExtension();case"union":return this.parseUnionTypeExtension();case"enum":return this.parseEnumTypeExtension();case"input":return this.parseInputObjectTypeExtension()}throw this.unexpected(t)}parseSchemaExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("schema");const n=this.parseConstDirectives(),r=this.optionalMany(ee.BRACE_L,this.parseOperationTypeDefinition,ee.BRACE_R);if(n.length===0&&r.length===0)throw this.unexpected();return this.node(t,{kind:Se.SCHEMA_EXTENSION,directives:n,operationTypes:r})}parseScalarTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("scalar");const n=this.parseName(),r=this.parseConstDirectives();if(r.length===0)throw this.unexpected();return this.node(t,{kind:Se.SCALAR_TYPE_EXTENSION,name:n,directives:r})}parseObjectTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("type");const n=this.parseName(),r=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),s=this.parseFieldsDefinition();if(r.length===0&&i.length===0&&s.length===0)throw this.unexpected();return this.node(t,{kind:Se.OBJECT_TYPE_EXTENSION,name:n,interfaces:r,directives:i,fields:s})}parseInterfaceTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("interface");const n=this.parseName(),r=this.parseImplementsInterfaces(),i=this.parseConstDirectives(),s=this.parseFieldsDefinition();if(r.length===0&&i.length===0&&s.length===0)throw this.unexpected();return this.node(t,{kind:Se.INTERFACE_TYPE_EXTENSION,name:n,interfaces:r,directives:i,fields:s})}parseUnionTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("union");const n=this.parseName(),r=this.parseConstDirectives(),i=this.parseUnionMemberTypes();if(r.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:Se.UNION_TYPE_EXTENSION,name:n,directives:r,types:i})}parseEnumTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("enum");const n=this.parseName(),r=this.parseConstDirectives(),i=this.parseEnumValuesDefinition();if(r.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:Se.ENUM_TYPE_EXTENSION,name:n,directives:r,values:i})}parseInputObjectTypeExtension(){const t=this._lexer.token;this.expectKeyword("extend"),this.expectKeyword("input");const n=this.parseName(),r=this.parseConstDirectives(),i=this.parseInputFieldsDefinition();if(r.length===0&&i.length===0)throw this.unexpected();return this.node(t,{kind:Se.INPUT_OBJECT_TYPE_EXTENSION,name:n,directives:r,fields:i})}parseDirectiveDefinition(){const t=this._lexer.token,n=this.parseDescription();this.expectKeyword("directive"),this.expectToken(ee.AT);const r=this.parseName(),i=this.parseArgumentDefs(),s=this.expectOptionalKeyword("repeatable");this.expectKeyword("on");const o=this.parseDirectiveLocations();return this.node(t,{kind:Se.DIRECTIVE_DEFINITION,description:n,name:r,arguments:i,repeatable:s,locations:o})}parseDirectiveLocations(){return this.delimitedMany(ee.PIPE,this.parseDirectiveLocation)}parseDirectiveLocation(){const t=this._lexer.token,n=this.parseName();if(Object.prototype.hasOwnProperty.call(yl,n.value))return n;throw this.unexpected(t)}node(t,n){return this._options.noLocation!==!0&&(n.loc=new ev(t,this._lexer.lastToken,this._lexer.source)),n}peek(t){return this._lexer.token.kind===t}expectToken(t){const n=this._lexer.token;if(n.kind===t)return this.advanceLexer(),n;throw kt(this._lexer.source,n.start,`Expected ${h1(t)}, found ${Wc(n)}.`)}expectOptionalToken(t){return this._lexer.token.kind===t?(this.advanceLexer(),!0):!1}expectKeyword(t){const n=this._lexer.token;if(n.kind===ee.NAME&&n.value===t)this.advanceLexer();else throw kt(this._lexer.source,n.start,`Expected "${t}", found ${Wc(n)}.`)}expectOptionalKeyword(t){const n=this._lexer.token;return n.kind===ee.NAME&&n.value===t?(this.advanceLexer(),!0):!1}unexpected(t){const n=t??this._lexer.token;return kt(this._lexer.source,n.start,`Unexpected ${Wc(n)}.`)}any(t,n,r){this.expectToken(t);const i=[];for(;!this.expectOptionalToken(r);)i.push(n.call(this));return i}optionalMany(t,n,r){if(this.expectOptionalToken(t)){const i=[];do i.push(n.call(this));while(!this.expectOptionalToken(r));return i}return[]}many(t,n,r){this.expectToken(t);const i=[];do i.push(n.call(this));while(!this.expectOptionalToken(r));return i}delimitedMany(t,n){this.expectOptionalToken(t);const r=[];do r.push(n.call(this));while(this.expectOptionalToken(t));return r}advanceLexer(){const{maxTokens:t}=this._options,n=this._lexer.advance();if(n.kind!==ee.EOF&&(++this._tokenCounter,t!==void 0&&this._tokenCounter>t))throw kt(this._lexer.source,n.start,`Document contains more that ${t} tokens. Parsing aborted.`)}}function Wc(e){const t=e.value;return h1(e.kind)+(t!=null?` "${t}"`:"")}function h1(e){return cv(e)?`"${e}"`:e}function Ov(e){return`"${e.replace(Bv,Nv)}"`}const Bv=/[\x00-\x1f\x22\x5c\x7f-\x9f]/g;function Nv(e){return kv[e.charCodeAt(0)]}const kv=["\\u0000","\\u0001","\\u0002","\\u0003","\\u0004","\\u0005","\\u0006","\\u0007","\\b","\\t","\\n","\\u000B","\\f","\\r","\\u000E","\\u000F","\\u0010","\\u0011","\\u0012","\\u0013","\\u0014","\\u0015","\\u0016","\\u0017","\\u0018","\\u0019","\\u001A","\\u001B","\\u001C","\\u001D","\\u001E","\\u001F","","",'\\"',"","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\\\","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","\\u007F","\\u0080","\\u0081","\\u0082","\\u0083","\\u0084","\\u0085","\\u0086","\\u0087","\\u0088","\\u0089","\\u008A","\\u008B","\\u008C","\\u008D","\\u008E","\\u008F","\\u0090","\\u0091","\\u0092","\\u0093","\\u0094","\\u0095","\\u0096","\\u0097","\\u0098","\\u0099","\\u009A","\\u009B","\\u009C","\\u009D","\\u009E","\\u009F"],Pv=Object.freeze({});function Rv(e,t,n=s1){const r=new Map;for(const S of Object.values(Se))r.set(S,Cv(t,S));let i,s=Array.isArray(e),o=[e],c=-1,a=[],u=e,f,l;const d=[],y=[];do{c++;const S=c===o.length,_=S&&a.length!==0;if(S){if(f=y.length===0?void 0:d[d.length-1],u=l,l=y.pop(),_)if(s){u=u.slice();let T=0;for(const[O,A]of a){const R=O-T;A===null?(u.splice(R,1),T++):u[R]=A}}else{u={...u};for(const[T,O]of a)u[T]=O}c=i.index,o=i.keys,a=i.edits,s=i.inArray,i=i.prev}else if(l){if(f=s?c:o[c],u=l[f],u==null)continue;d.push(f)}let w;if(!Array.isArray(u)){var g,m;wy(u)||ia(!1,`Invalid AST Node: ${Ph(u)}.`);const T=S?(g=r.get(u.kind))===null||g===void 0?void 0:g.leave:(m=r.get(u.kind))===null||m===void 0?void 0:m.enter;if(w=T?.call(t,u,f,l,d,y),w===Pv)break;if(w===!1){if(!S){d.pop();continue}}else if(w!==void 0&&(a.push([f,w]),!S))if(wy(w))u=w;else{d.pop();continue}}if(w===void 0&&_&&a.push([f,u]),S)d.pop();else{var E;i={inArray:s,index:c,keys:o,edits:a,prev:i},s=Array.isArray(u),o=s?u:(E=n[u.kind])!==null&&E!==void 0?E:[],c=-1,a=[],l&&y.push(l),l=u}}while(i!==void 0);return a.length!==0?a[a.length-1][1]:e}function Cv(e,t){const n=e[t];return typeof n=="object"?n:typeof n=="function"?{enter:n,leave:void 0}:{enter:e.enter,leave:e.leave}}function Uv(e){return Rv(e,Fv)}const Hv=80,Fv={Name:{leave:e=>e.value},Variable:{leave:e=>"$"+e.name},Document:{leave:e=>ye(e.definitions,`
98
98
 
99
99
  `)},OperationDefinition:{leave(e){const t=Fe("(",ye(e.variableDefinitions,", "),")"),n=ye([e.operation,ye([e.name,t]),ye(e.directives," ")]," ");return(n==="query"?"":n+" ")+e.selectionSet}},VariableDefinition:{leave:({variable:e,type:t,defaultValue:n,directives:r})=>e+": "+t+Fe(" = ",n)+Fe(" ",ye(r," "))},SelectionSet:{leave:({selections:e})=>Un(e)},Field:{leave({alias:e,name:t,arguments:n,directives:r,selectionSet:i}){const s=Fe("",e,": ")+t;let o=s+Fe("(",ye(n,", "),")");return o.length>Hv&&(o=s+Fe(`(
100
100
  `,sa(ye(n,`
@@ -123,13 +123,13 @@ spurious results.`)}}return!1};class l1{constructor(t,n="GraphQL request",r={lin
123
123
  `))}function Ey(e){var t;return(t=e?.some(n=>n.includes(`
124
124
  `)))!==null&&t!==void 0?t:!1}const _y="Accept",ml="Content-Type",wl="application/json",d1="application/graphql-response+json",Sy=e=>e.replace(/([\s,]|#[^\n\r]+)+/g," ").trim(),Mv=e=>{const t=e.toLowerCase();return t.includes(d1)||t.includes(wl)},Ty=e=>{try{if(Array.isArray(e))return{_tag:"Batch",executionResults:e.map(xy)};if(ra(e))return{_tag:"Single",executionResult:xy(e)};throw new Error(`Invalid execution result: result is not object or array.
125
125
  Got:
126
- ${String(e)}`)}catch(t){return t}},xy=e=>{if(typeof e!="object"||e===null)throw new Error("Invalid execution result: result is not object");let t,n,r;if("errors"in e){if(!ra(e.errors)&&!Array.isArray(e.errors))throw new Error("Invalid execution result: errors is not plain object OR array");t=e.errors}if("data"in e){if(!ra(e.data)&&e.data!==null)throw new Error("Invalid execution result: data is not plain object");n=e.data}if("extensions"in e){if(!ra(e.extensions))throw new Error("Invalid execution result: extensions is not plain object");r=e.extensions}return{data:n,errors:t,extensions:r}},Lv=e=>e._tag==="Batch"?e.executionResults.some(Ay):Ay(e.executionResult),Ay=e=>Array.isArray(e.errors)?e.errors.length>0:!!e.errors,p1=e=>typeof e=="object"&&e!==null&&"kind"in e&&e.kind===Se.OPERATION_DEFINITION,qv=e=>{let t;const n=e.definitions.filter(p1);return n.length===1&&(t=n[0].name?.value),t},Vv=e=>{let t=!1;const n=e.definitions.filter(p1);return n.length===1&&(t=n[0].operation==="mutation"),t},Hf=(e,t)=>{const n=typeof e=="string"?e:Uv(e);let r=!1,i;if(t)return{expression:n,isMutation:r,operationName:i};const s=KA(()=>typeof e=="string"?vv(e):e);return s instanceof Error?{expression:n,isMutation:r,operationName:i}:(i=qv(s),r=Vv(s),{expression:n,operationName:i,isMutation:r})},Rh=JSON,Ff=async e=>{const t={...e,method:e.request._tag==="Single"?e.request.document.isMutation?"POST":py(e.method??"post"):e.request.hasMutations?"POST":py(e.method??"post"),fetchOptions:{...e.fetchOptions,errorPolicy:e.fetchOptions.errorPolicy??"none"}},r=await $v(t.method)(t);if(!r.ok)return new vs({status:r.status,headers:r.headers},{query:e.request._tag==="Single"?e.request.document.expression:e.request.query,variables:e.request.variables});const i=await Dv(r,e.fetchOptions.jsonSerializer??Rh);if(i instanceof Error)throw i;const s={status:r.status,headers:r.headers};if(Lv(i)&&t.fetchOptions.errorPolicy==="none"){const o=i._tag==="Batch"?{...i.executionResults,...s}:{...i.executionResult,...s};return new vs(o,{query:e.request._tag==="Single"?e.request.document.expression:e.request.query,variables:e.request.variables})}switch(i._tag){case"Single":return{...s,...vy(t)(i.executionResult)};case"Batch":return{...s,data:i.executionResults.map(vy(t))};default:Nh(i)}},vy=e=>t=>({extensions:t.extensions,data:t.data,errors:e.fetchOptions.errorPolicy==="all"?t.errors:void 0}),Dv=async(e,t)=>{const n=e.headers.get(ml),r=await e.text();return n&&Mv(n)?Ty(t.parse(r)):Ty(r)},$v=e=>async t=>{const n=new Headers(t.headers);let r=null,i;n.has(_y)||n.set(_y,[d1,wl].join(", ")),e==="POST"?(i=(t.fetchOptions.jsonSerializer??Rh).stringify(jv(t)),typeof i=="string"&&!n.has(ml)&&n.set(ml,wl)):r=Kv(t);const s={method:e,headers:n,body:i,...t.fetchOptions};let o=new URL(t.url),c=s;if(t.middleware){const u=await Promise.resolve(t.middleware({...s,url:t.url,operationName:t.request._tag==="Single"?t.request.document.operationName:void 0,variables:t.request.variables})),{url:f,...l}=u;o=new URL(f),c=l}return r&&r.forEach((u,f)=>{o.searchParams.append(f,u)}),await(t.fetch??fetch)(o,c)},jv=e=>{switch(e.request._tag){case"Single":return{query:e.request.document.expression,variables:e.request.variables,operationName:e.request.document.operationName};case"Batch":return n1(e.request.query,e.request.variables??[]).map(([t,n])=>({query:t,variables:n}));default:throw Nh(e.request)}},Kv=e=>{const t=e.fetchOptions.jsonSerializer??Rh,n=new URLSearchParams;switch(e.request._tag){case"Single":return n.append("query",Sy(e.request.document.expression)),e.request.variables&&n.append("variables",t.stringify(e.request.variables)),e.request.document.operationName&&n.append("operationName",e.request.document.operationName),n;case"Batch":{const r=e.request.variables?.map(o=>t.stringify(o))??[],i=e.request.query.map(Sy),s=n1(i,r).map(([o,c])=>({query:o,variables:c}));return n.append("query",t.stringify(s)),n}default:throw Nh(e.request)}};class Gv{url;requestConfig;constructor(t,n={}){this.url=t,this.requestConfig=n}rawRequest=async(...t)=>{const[n,r,i]=t,s=XA(n,r,i),{headers:o,fetch:c=globalThis.fetch,method:a="POST",requestMiddleware:u,responseMiddleware:f,excludeOperationName:l,...d}=this.requestConfig,{url:y}=this;s.signal!==void 0&&(d.signal=s.signal);const g=Hf(s.query,l),m=await Ff({url:y,request:{_tag:"Single",document:g,variables:s.variables},headers:{...fs(Cf(o)),...fs(s.requestHeaders)},fetch:c,method:a,fetchOptions:d,middleware:u});if(f&&await f(m,{operationName:g.operationName,variables:r,url:this.url}),m instanceof Error)throw m;return m};async request(t,...n){const[r,i]=n,s=Wv(t,r,i),{headers:o,fetch:c=globalThis.fetch,method:a="POST",requestMiddleware:u,responseMiddleware:f,excludeOperationName:l,...d}=this.requestConfig,{url:y}=this;s.signal!==void 0&&(d.signal=s.signal);const g=Hf(s.document,l),m=await Ff({url:y,request:{_tag:"Single",document:g,variables:s.variables},headers:{...fs(Cf(o)),...fs(s.requestHeaders)},fetch:c,method:a,fetchOptions:d,middleware:u});if(f&&await f(m,{operationName:g.operationName,variables:s.variables,url:this.url}),m instanceof Error)throw m;return m.data}async batchRequests(t,n){const r=WA(t,n),{headers:i,excludeOperationName:s,...o}=this.requestConfig;r.signal!==void 0&&(o.signal=r.signal);const c=r.documents.map(({document:d})=>Hf(d,s)),a=c.map(({expression:d})=>d),u=c.some(({isMutation:d})=>d),f=r.documents.map(({variables:d})=>d),l=await Ff({url:this.url,request:{_tag:"Batch",operationName:void 0,query:a,hasMutations:u,variables:f},headers:{...fs(Cf(i)),...fs(r.requestHeaders)},fetch:this.requestConfig.fetch??globalThis.fetch,method:this.requestConfig.method||"POST",fetchOptions:o,middleware:this.requestConfig.requestMiddleware});if(this.requestConfig.responseMiddleware&&await this.requestConfig.responseMiddleware(l,{operationName:void 0,variables:f,url:this.url}),l instanceof Error)throw l;return l.data}setHeaders(t){return this.requestConfig.headers=t,this}setHeader(t,n){const{headers:r}=this.requestConfig;return r?r[t]=n:this.requestConfig.headers={[t]:n},this}setEndpoint(t){return this.url=t,this}}const Wv=(e,t,n)=>e.document?e:{document:e,variables:t,requestHeaders:n,signal:void 0},Xv=(e,...t)=>e.reduce((n,r,i)=>`${n}${r}${i in t?String(t[i]):""}`,"");/*!
126
+ ${String(e)}`)}catch(t){return t}},xy=e=>{if(typeof e!="object"||e===null)throw new Error("Invalid execution result: result is not object");let t,n,r;if("errors"in e){if(!ra(e.errors)&&!Array.isArray(e.errors))throw new Error("Invalid execution result: errors is not plain object OR array");t=e.errors}if("data"in e){if(!ra(e.data)&&e.data!==null)throw new Error("Invalid execution result: data is not plain object");n=e.data}if("extensions"in e){if(!ra(e.extensions))throw new Error("Invalid execution result: extensions is not plain object");r=e.extensions}return{data:n,errors:t,extensions:r}},Lv=e=>e._tag==="Batch"?e.executionResults.some(Ay):Ay(e.executionResult),Ay=e=>Array.isArray(e.errors)?e.errors.length>0:!!e.errors,p1=e=>typeof e=="object"&&e!==null&&"kind"in e&&e.kind===Se.OPERATION_DEFINITION,qv=e=>{let t;const n=e.definitions.filter(p1);return n.length===1&&(t=n[0].name?.value),t},Vv=e=>{let t=!1;const n=e.definitions.filter(p1);return n.length===1&&(t=n[0].operation==="mutation"),t},Hf=(e,t)=>{const n=typeof e=="string"?e:Uv(e);let r=!1,i;if(t)return{expression:n,isMutation:r,operationName:i};const s=KA(()=>typeof e=="string"?vv(e):e);return s instanceof Error?{expression:n,isMutation:r,operationName:i}:(i=qv(s),r=Vv(s),{expression:n,operationName:i,isMutation:r})},Rh=JSON,Ff=async e=>{const t={...e,method:e.request._tag==="Single"?e.request.document.isMutation?"POST":py(e.method??"post"):e.request.hasMutations?"POST":py(e.method??"post"),fetchOptions:{...e.fetchOptions,errorPolicy:e.fetchOptions.errorPolicy??"none"}},r=await $v(t.method)(t);if(!r.ok)return new Is({status:r.status,headers:r.headers},{query:e.request._tag==="Single"?e.request.document.expression:e.request.query,variables:e.request.variables});const i=await Dv(r,e.fetchOptions.jsonSerializer??Rh);if(i instanceof Error)throw i;const s={status:r.status,headers:r.headers};if(Lv(i)&&t.fetchOptions.errorPolicy==="none"){const o=i._tag==="Batch"?{...i.executionResults,...s}:{...i.executionResult,...s};return new Is(o,{query:e.request._tag==="Single"?e.request.document.expression:e.request.query,variables:e.request.variables})}switch(i._tag){case"Single":return{...s,...vy(t)(i.executionResult)};case"Batch":return{...s,data:i.executionResults.map(vy(t))};default:Nh(i)}},vy=e=>t=>({extensions:t.extensions,data:t.data,errors:e.fetchOptions.errorPolicy==="all"?t.errors:void 0}),Dv=async(e,t)=>{const n=e.headers.get(ml),r=await e.text();return n&&Mv(n)?Ty(t.parse(r)):Ty(r)},$v=e=>async t=>{const n=new Headers(t.headers);let r=null,i;n.has(_y)||n.set(_y,[d1,wl].join(", ")),e==="POST"?(i=(t.fetchOptions.jsonSerializer??Rh).stringify(jv(t)),typeof i=="string"&&!n.has(ml)&&n.set(ml,wl)):r=Kv(t);const s={method:e,headers:n,body:i,...t.fetchOptions};let o=new URL(t.url),c=s;if(t.middleware){const u=await Promise.resolve(t.middleware({...s,url:t.url,operationName:t.request._tag==="Single"?t.request.document.operationName:void 0,variables:t.request.variables})),{url:f,...l}=u;o=new URL(f),c=l}return r&&r.forEach((u,f)=>{o.searchParams.append(f,u)}),await(t.fetch??fetch)(o,c)},jv=e=>{switch(e.request._tag){case"Single":return{query:e.request.document.expression,variables:e.request.variables,operationName:e.request.document.operationName};case"Batch":return n1(e.request.query,e.request.variables??[]).map(([t,n])=>({query:t,variables:n}));default:throw Nh(e.request)}},Kv=e=>{const t=e.fetchOptions.jsonSerializer??Rh,n=new URLSearchParams;switch(e.request._tag){case"Single":return n.append("query",Sy(e.request.document.expression)),e.request.variables&&n.append("variables",t.stringify(e.request.variables)),e.request.document.operationName&&n.append("operationName",e.request.document.operationName),n;case"Batch":{const r=e.request.variables?.map(o=>t.stringify(o))??[],i=e.request.query.map(Sy),s=n1(i,r).map(([o,c])=>({query:o,variables:c}));return n.append("query",t.stringify(s)),n}default:throw Nh(e.request)}};class Gv{url;requestConfig;constructor(t,n={}){this.url=t,this.requestConfig=n}rawRequest=async(...t)=>{const[n,r,i]=t,s=XA(n,r,i),{headers:o,fetch:c=globalThis.fetch,method:a="POST",requestMiddleware:u,responseMiddleware:f,excludeOperationName:l,...d}=this.requestConfig,{url:y}=this;s.signal!==void 0&&(d.signal=s.signal);const g=Hf(s.query,l),m=await Ff({url:y,request:{_tag:"Single",document:g,variables:s.variables},headers:{...fs(Cf(o)),...fs(s.requestHeaders)},fetch:c,method:a,fetchOptions:d,middleware:u});if(f&&await f(m,{operationName:g.operationName,variables:r,url:this.url}),m instanceof Error)throw m;return m};async request(t,...n){const[r,i]=n,s=Wv(t,r,i),{headers:o,fetch:c=globalThis.fetch,method:a="POST",requestMiddleware:u,responseMiddleware:f,excludeOperationName:l,...d}=this.requestConfig,{url:y}=this;s.signal!==void 0&&(d.signal=s.signal);const g=Hf(s.document,l),m=await Ff({url:y,request:{_tag:"Single",document:g,variables:s.variables},headers:{...fs(Cf(o)),...fs(s.requestHeaders)},fetch:c,method:a,fetchOptions:d,middleware:u});if(f&&await f(m,{operationName:g.operationName,variables:s.variables,url:this.url}),m instanceof Error)throw m;return m.data}async batchRequests(t,n){const r=WA(t,n),{headers:i,excludeOperationName:s,...o}=this.requestConfig;r.signal!==void 0&&(o.signal=r.signal);const c=r.documents.map(({document:d})=>Hf(d,s)),a=c.map(({expression:d})=>d),u=c.some(({isMutation:d})=>d),f=r.documents.map(({variables:d})=>d),l=await Ff({url:this.url,request:{_tag:"Batch",operationName:void 0,query:a,hasMutations:u,variables:f},headers:{...fs(Cf(i)),...fs(r.requestHeaders)},fetch:this.requestConfig.fetch??globalThis.fetch,method:this.requestConfig.method||"POST",fetchOptions:o,middleware:this.requestConfig.requestMiddleware});if(this.requestConfig.responseMiddleware&&await this.requestConfig.responseMiddleware(l,{operationName:void 0,variables:f,url:this.url}),l instanceof Error)throw l;return l.data}setHeaders(t){return this.requestConfig.headers=t,this}setHeader(t,n){const{headers:r}=this.requestConfig;return r?r[t]=n:this.requestConfig.headers={[t]:n},this}setEndpoint(t){return this.url=t,this}}const Wv=(e,t,n)=>e.document?e:{document:e,variables:t,requestHeaders:n,signal:void 0},Xv=(e,...t)=>e.reduce((n,r,i)=>`${n}${r}${i in t?String(t[i]):""}`,"");/*!
127
127
  * decimal.js v10.6.0
128
128
  * An arbitrary-precision Decimal type for JavaScript.
129
129
  * https://github.com/MikeMcl/decimal.js
130
130
  * Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>
131
131
  * MIT Licence
132
- */var ms=9e15,gi=1e9,bl="0123456789abcdef",Fa="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Ma="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",El={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-ms,maxE:ms,crypto:!1},y1,Ar,ve=!0,Tu="[DecimalError] ",hi=Tu+"Invalid argument: ",g1=Tu+"Precision limit exceeded",m1=Tu+"crypto unavailable",w1="[object Decimal]",Xt=Math.floor,At=Math.pow,zv=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Yv=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Zv=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,b1=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,jn=1e7,_e=7,Jv=9007199254740991,Qv=Fa.length-1,_l=Ma.length-1,se={toStringTag:w1};se.absoluteValue=se.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),be(e)};se.ceil=function(){return be(new this.constructor(this),this.e+1,2)};se.clampedTo=se.clamp=function(e,t){var n,r=this,i=r.constructor;if(e=new i(e),t=new i(t),!e.s||!t.s)return new i(NaN);if(e.gt(t))throw Error(hi+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};se.comparedTo=se.cmp=function(e){var t,n,r,i,s=this,o=s.d,c=(e=new s.constructor(e)).d,a=s.s,u=e.s;if(!o||!c)return!a||!u?NaN:a!==u?a:o===c?0:!o^a<0?1:-1;if(!o[0]||!c[0])return o[0]?a:c[0]?-u:0;if(a!==u)return a;if(s.e!==e.e)return s.e>e.e^a<0?1:-1;for(r=o.length,i=c.length,t=0,n=r<i?r:i;t<n;++t)if(o[t]!==c[t])return o[t]>c[t]^a<0?1:-1;return r===i?0:r>i^a<0?1:-1};se.cosine=se.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+_e,r.rounding=1,n=eI(r,x1(r,n)),r.precision=e,r.rounding=t,be(Ar==2||Ar==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};se.cubeRoot=se.cbrt=function(){var e,t,n,r,i,s,o,c,a,u,f=this,l=f.constructor;if(!f.isFinite()||f.isZero())return new l(f);for(ve=!1,s=f.s*At(f.s*f,1/3),!s||Math.abs(s)==1/0?(n=Ft(f.d),e=f.e,(s=(e-n.length+1)%3)&&(n+=s==1||s==-2?"0":"00"),s=At(n,1/3),e=Xt((e+1)/3)-(e%3==(e<0?-1:2)),s==1/0?n="5e"+e:(n=s.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new l(n),r.s=f.s):r=new l(s.toString()),o=(e=l.precision)+3;;)if(c=r,a=c.times(c).times(c),u=a.plus(f),r=Je(u.plus(f).times(c),u.plus(a),o+2,1),Ft(c.d).slice(0,o)===(n=Ft(r.d)).slice(0,o))if(n=n.slice(o-3,o+1),n=="9999"||!i&&n=="4999"){if(!i&&(be(c,e+1,0),c.times(c).times(c).eq(f))){r=c;break}o+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(be(r,e+1,1),t=!r.times(r).times(r).eq(f));break}return ve=!0,be(r,e,l.rounding,t)};se.decimalPlaces=se.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-Xt(this.e/_e))*_e,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};se.dividedBy=se.div=function(e){return Je(this,new this.constructor(e))};se.dividedToIntegerBy=se.divToInt=function(e){var t=this,n=t.constructor;return be(Je(t,new n(e),0,1,1),n.precision,n.rounding)};se.equals=se.eq=function(e){return this.cmp(e)===0};se.floor=function(){return be(new this.constructor(this),this.e+1,3)};se.greaterThan=se.gt=function(e){return this.cmp(e)>0};se.greaterThanOrEqualTo=se.gte=function(e){var t=this.cmp(e);return t==1||t===0};se.hyperbolicCosine=se.cosh=function(){var e,t,n,r,i,s=this,o=s.constructor,c=new o(1);if(!s.isFinite())return new o(s.s?1/0:NaN);if(s.isZero())return c;n=o.precision,r=o.rounding,o.precision=n+Math.max(s.e,s.sd())+4,o.rounding=1,i=s.d.length,i<32?(e=Math.ceil(i/3),t=(1/Au(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),s=Hs(o,1,s.times(t),new o(1),!0);for(var a,u=e,f=new o(8);u--;)a=s.times(s),s=c.minus(a.times(f.minus(a.times(f))));return be(s,o.precision=n,o.rounding=r,!0)};se.hyperbolicSine=se.sinh=function(){var e,t,n,r,i=this,s=i.constructor;if(!i.isFinite()||i.isZero())return new s(i);if(t=s.precision,n=s.rounding,s.precision=t+Math.max(i.e,i.sd())+4,s.rounding=1,r=i.d.length,r<3)i=Hs(s,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/Au(5,e)),i=Hs(s,2,i,i,!0);for(var o,c=new s(5),a=new s(16),u=new s(20);e--;)o=i.times(i),i=i.times(c.plus(o.times(a.times(o).plus(u))))}return s.precision=t,s.rounding=n,be(i,t,n,!0)};se.hyperbolicTangent=se.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,Je(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};se.inverseCosine=se.acos=function(){var e=this,t=e.constructor,n=e.abs().cmp(1),r=t.precision,i=t.rounding;return n!==-1?n===0?e.isNeg()?nr(t,r,i):new t(0):new t(NaN):e.isZero()?nr(t,r+4,i).times(.5):(t.precision=r+6,t.rounding=1,e=new t(1).minus(e).div(e.plus(1)).sqrt().atan(),t.precision=r,t.rounding=i,e.times(2))};se.inverseHyperbolicCosine=se.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,ve=!1,n=n.times(n).minus(1).sqrt().plus(n),ve=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};se.inverseHyperbolicSine=se.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,ve=!1,n=n.times(n).plus(1).sqrt().plus(n),ve=!0,r.precision=e,r.rounding=t,n.ln())};se.inverseHyperbolicTangent=se.atanh=function(){var e,t,n,r,i=this,s=i.constructor;return i.isFinite()?i.e>=0?new s(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=s.precision,t=s.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?be(new s(i),e,t,!0):(s.precision=n=r-i.e,i=Je(i.plus(1),new s(1).minus(i),n+e,1),s.precision=e+4,s.rounding=1,i=i.ln(),s.precision=e,s.rounding=t,i.times(.5))):new s(NaN)};se.inverseSine=se.asin=function(){var e,t,n,r,i=this,s=i.constructor;return i.isZero()?new s(i):(t=i.abs().cmp(1),n=s.precision,r=s.rounding,t!==-1?t===0?(e=nr(s,n+4,r).times(.5),e.s=i.s,e):new s(NaN):(s.precision=n+6,s.rounding=1,i=i.div(new s(1).minus(i.times(i)).sqrt().plus(1)).atan(),s.precision=n,s.rounding=r,i.times(2)))};se.inverseTangent=se.atan=function(){var e,t,n,r,i,s,o,c,a,u=this,f=u.constructor,l=f.precision,d=f.rounding;if(u.isFinite()){if(u.isZero())return new f(u);if(u.abs().eq(1)&&l+4<=_l)return o=nr(f,l+4,d).times(.25),o.s=u.s,o}else{if(!u.s)return new f(NaN);if(l+4<=_l)return o=nr(f,l+4,d).times(.5),o.s=u.s,o}for(f.precision=c=l+10,f.rounding=1,n=Math.min(28,c/_e+2|0),e=n;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(ve=!1,t=Math.ceil(c/_e),r=1,a=u.times(u),o=new f(u),i=u;e!==-1;)if(i=i.times(a),s=o.minus(i.div(r+=2)),i=i.times(a),o=s.plus(i.div(r+=2)),o.d[t]!==void 0)for(e=t;o.d[e]===s.d[e]&&e--;);return n&&(o=o.times(2<<n-1)),ve=!0,be(o,f.precision=l,f.rounding=d,!0)};se.isFinite=function(){return!!this.d};se.isInteger=se.isInt=function(){return!!this.d&&Xt(this.e/_e)>this.d.length-2};se.isNaN=function(){return!this.s};se.isNegative=se.isNeg=function(){return this.s<0};se.isPositive=se.isPos=function(){return this.s>0};se.isZero=function(){return!!this.d&&this.d[0]===0};se.lessThan=se.lt=function(e){return this.cmp(e)<0};se.lessThanOrEqualTo=se.lte=function(e){return this.cmp(e)<1};se.logarithm=se.log=function(e){var t,n,r,i,s,o,c,a,u=this,f=u.constructor,l=f.precision,d=f.rounding,y=5;if(e==null)e=new f(10),t=!0;else{if(e=new f(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new f(NaN);t=e.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new f(n&&!n[0]?-1/0:u.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)s=!0;else{for(i=n[0];i%10===0;)i/=10;s=i!==1}if(ve=!1,c=l+y,o=oi(u,c),r=t?La(f,c+10):oi(e,c),a=Je(o,r,c,1),jo(a.d,i=l,d))do if(c+=10,o=oi(u,c),r=t?La(f,c+10):oi(e,c),a=Je(o,r,c,1),!s){+Ft(a.d).slice(i+1,i+15)+1==1e14&&(a=be(a,l+1,0));break}while(jo(a.d,i+=10,d));return ve=!0,be(a,l,d)};se.minus=se.sub=function(e){var t,n,r,i,s,o,c,a,u,f,l,d,y=this,g=y.constructor;if(e=new g(e),!y.d||!e.d)return!y.s||!e.s?e=new g(NaN):y.d?e.s=-e.s:e=new g(e.d||y.s!==e.s?y:NaN),e;if(y.s!=e.s)return e.s=-e.s,y.plus(e);if(u=y.d,d=e.d,c=g.precision,a=g.rounding,!u[0]||!d[0]){if(d[0])e.s=-e.s;else if(u[0])e=new g(y);else return new g(a===3?-0:0);return ve?be(e,c,a):e}if(n=Xt(e.e/_e),f=Xt(y.e/_e),u=u.slice(),s=f-n,s){for(l=s<0,l?(t=u,s=-s,o=d.length):(t=d,n=f,o=u.length),r=Math.max(Math.ceil(c/_e),o)+2,s>r&&(s=r,t.length=1),t.reverse(),r=s;r--;)t.push(0);t.reverse()}else{for(r=u.length,o=d.length,l=r<o,l&&(o=r),r=0;r<o;r++)if(u[r]!=d[r]){l=u[r]<d[r];break}s=0}for(l&&(t=u,u=d,d=t,e.s=-e.s),o=u.length,r=d.length-o;r>0;--r)u[o++]=0;for(r=d.length;r>s;){if(u[--r]<d[r]){for(i=r;i&&u[--i]===0;)u[i]=jn-1;--u[i],u[r]+=jn}u[r]-=d[r]}for(;u[--o]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=xu(u,n),ve?be(e,c,a):e):new g(a===3?-0:0)};se.modulo=se.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?be(new r(n),r.precision,r.rounding):(ve=!1,r.modulo==9?(t=Je(n,e.abs(),0,3,1),t.s*=e.s):t=Je(n,e,0,r.modulo,1),t=t.times(e),ve=!0,n.minus(t))};se.naturalExponential=se.exp=function(){return Sl(this)};se.naturalLogarithm=se.ln=function(){return oi(this)};se.negated=se.neg=function(){var e=new this.constructor(this);return e.s=-e.s,be(e)};se.plus=se.add=function(e){var t,n,r,i,s,o,c,a,u,f,l=this,d=l.constructor;if(e=new d(e),!l.d||!e.d)return!l.s||!e.s?e=new d(NaN):l.d||(e=new d(e.d||l.s===e.s?l:NaN)),e;if(l.s!=e.s)return e.s=-e.s,l.minus(e);if(u=l.d,f=e.d,c=d.precision,a=d.rounding,!u[0]||!f[0])return f[0]||(e=new d(l)),ve?be(e,c,a):e;if(s=Xt(l.e/_e),r=Xt(e.e/_e),u=u.slice(),i=s-r,i){for(i<0?(n=u,i=-i,o=f.length):(n=f,r=s,o=u.length),s=Math.ceil(c/_e),o=s>o?s+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=u.length,i=f.length,o-i<0&&(i=o,n=f,f=u,u=n),t=0;i;)t=(u[--i]=u[i]+f[i]+t)/jn|0,u[i]%=jn;for(t&&(u.unshift(t),++r),o=u.length;u[--o]==0;)u.pop();return e.d=u,e.e=xu(u,r),ve?be(e,c,a):e};se.precision=se.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(hi+e);return n.d?(t=E1(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};se.round=function(){var e=this,t=e.constructor;return be(new t(e),e.e+1,t.rounding)};se.sine=se.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+_e,r.rounding=1,n=nI(r,x1(r,n)),r.precision=e,r.rounding=t,be(Ar>2?n.neg():n,e,t,!0)):new r(NaN)};se.squareRoot=se.sqrt=function(){var e,t,n,r,i,s,o=this,c=o.d,a=o.e,u=o.s,f=o.constructor;if(u!==1||!c||!c[0])return new f(!u||u<0&&(!c||c[0])?NaN:c?o:1/0);for(ve=!1,u=Math.sqrt(+o),u==0||u==1/0?(t=Ft(c),(t.length+a)%2==0&&(t+="0"),u=Math.sqrt(t),a=Xt((a+1)/2)-(a<0||a%2),u==1/0?t="5e"+a:(t=u.toExponential(),t=t.slice(0,t.indexOf("e")+1)+a),r=new f(t)):r=new f(u.toString()),n=(a=f.precision)+3;;)if(s=r,r=s.plus(Je(o,s,n+2,1)).times(.5),Ft(s.d).slice(0,n)===(t=Ft(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(be(s,a+1,0),s.times(s).eq(o))){r=s;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(be(r,a+1,1),e=!r.times(r).eq(o));break}return ve=!0,be(r,a,f.rounding,e)};se.tangent=se.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=Je(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,be(Ar==2||Ar==4?n.neg():n,e,t,!0)):new r(NaN)};se.times=se.mul=function(e){var t,n,r,i,s,o,c,a,u,f=this,l=f.constructor,d=f.d,y=(e=new l(e)).d;if(e.s*=f.s,!d||!d[0]||!y||!y[0])return new l(!e.s||d&&!d[0]&&!y||y&&!y[0]&&!d?NaN:!d||!y?e.s/0:e.s*0);for(n=Xt(f.e/_e)+Xt(e.e/_e),a=d.length,u=y.length,a<u&&(s=d,d=y,y=s,o=a,a=u,u=o),s=[],o=a+u,r=o;r--;)s.push(0);for(r=u;--r>=0;){for(t=0,i=a+r;i>r;)c=s[i]+y[r]*d[i-r-1]+t,s[i--]=c%jn|0,t=c/jn|0;s[i]=(s[i]+t)%jn|0}for(;!s[--o];)s.pop();return t?++n:s.shift(),e.d=s,e.e=xu(s,n),ve?be(e,l.precision,l.rounding):e};se.toBinary=function(e,t){return Ch(this,2,e,t)};se.toDecimalPlaces=se.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(yn(e,0,gi),t===void 0?t=r.rounding:yn(t,0,8),be(n,e+n.e+1,t))};se.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=sr(r,!0):(yn(e,0,gi),t===void 0?t=i.rounding:yn(t,0,8),r=be(new i(r),e+1,t),n=sr(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};se.toFixed=function(e,t){var n,r,i=this,s=i.constructor;return e===void 0?n=sr(i):(yn(e,0,gi),t===void 0?t=s.rounding:yn(t,0,8),r=be(new s(i),e+i.e+1,t),n=sr(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};se.toFraction=function(e){var t,n,r,i,s,o,c,a,u,f,l,d,y=this,g=y.d,m=y.constructor;if(!g)return new m(y);if(u=n=new m(1),r=a=new m(0),t=new m(r),s=t.e=E1(g)-y.e-1,o=s%_e,t.d[0]=At(10,o<0?_e+o:o),e==null)e=s>0?t:u;else{if(c=new m(e),!c.isInt()||c.lt(u))throw Error(hi+c);e=c.gt(t)?s>0?t:u:c}for(ve=!1,c=new m(Ft(g)),f=m.precision,m.precision=s=g.length*_e*2;l=Je(c,t,0,1,1),i=n.plus(l.times(r)),i.cmp(e)!=1;)n=r,r=i,i=u,u=a.plus(l.times(i)),a=i,i=t,t=c.minus(l.times(i)),c=i;return i=Je(e.minus(n),r,0,1,1),a=a.plus(i.times(u)),n=n.plus(i.times(r)),a.s=u.s=y.s,d=Je(u,r,s,1).minus(y).abs().cmp(Je(a,n,s,1).minus(y).abs())<1?[u,r]:[a,n],m.precision=f,ve=!0,d};se.toHexadecimal=se.toHex=function(e,t){return Ch(this,16,e,t)};se.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:yn(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(ve=!1,n=Je(n,e,0,t,1).times(e),ve=!0,be(n)):(e.s=n.s,n=e),n};se.toNumber=function(){return+this};se.toOctal=function(e,t){return Ch(this,8,e,t)};se.toPower=se.pow=function(e){var t,n,r,i,s,o,c=this,a=c.constructor,u=+(e=new a(e));if(!c.d||!e.d||!c.d[0]||!e.d[0])return new a(At(+c,u));if(c=new a(c),c.eq(1))return c;if(r=a.precision,s=a.rounding,e.eq(1))return be(c,r,s);if(t=Xt(e.e/_e),t>=e.d.length-1&&(n=u<0?-u:u)<=Jv)return i=_1(a,c,n,r),e.s<0?new a(1).div(i):be(i,r,s);if(o=c.s,o<0){if(t<e.d.length-1)return new a(NaN);if((e.d[t]&1)==0&&(o=1),c.e==0&&c.d[0]==1&&c.d.length==1)return c.s=o,c}return n=At(+c,u),t=n==0||!isFinite(n)?Xt(u*(Math.log("0."+Ft(c.d))/Math.LN10+c.e+1)):new a(n+"").e,t>a.maxE+1||t<a.minE-1?new a(t>0?o/0:0):(ve=!1,a.rounding=c.s=1,n=Math.min(12,(t+"").length),i=Sl(e.times(oi(c,r+n)),r),i.d&&(i=be(i,r+5,1),jo(i.d,r,s)&&(t=r+10,i=be(Sl(e.times(oi(c,t+n)),t),t+5,1),+Ft(i.d).slice(r+1,r+15)+1==1e14&&(i=be(i,r+1,0)))),i.s=o,ve=!0,a.rounding=s,be(i,r,s))};se.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=sr(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(yn(e,1,gi),t===void 0?t=i.rounding:yn(t,0,8),r=be(new i(r),e,t),n=sr(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};se.toSignificantDigits=se.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(yn(e,1,gi),t===void 0?t=r.rounding:yn(t,0,8)),be(new r(n),e,t)};se.toString=function(){var e=this,t=e.constructor,n=sr(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};se.truncated=se.trunc=function(){return be(new this.constructor(this),this.e+1,1)};se.valueOf=se.toJSON=function(){var e=this,t=e.constructor,n=sr(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function Ft(e){var t,n,r,i=e.length-1,s="",o=e[0];if(i>0){for(s+=o,t=1;t<i;t++)r=e[t]+"",n=_e-r.length,n&&(s+=si(n)),s+=r;o=e[t],r=o+"",n=_e-r.length,n&&(s+=si(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return s+o}function yn(e,t,n){if(e!==~~e||e<t||e>n)throw Error(hi+e)}function jo(e,t,n,r){var i,s,o,c;for(s=e[0];s>=10;s/=10)--t;return--t<0?(t+=_e,i=0):(i=Math.ceil((t+1)/_e),t%=_e),s=At(10,_e-t),c=e[i]%s|0,r==null?t<3?(t==0?c=c/100|0:t==1&&(c=c/10|0),o=n<4&&c==99999||n>3&&c==49999||c==5e4||c==0):o=(n<4&&c+1==s||n>3&&c+1==s/2)&&(e[i+1]/s/100|0)==At(10,t-2)-1||(c==s/2||c==0)&&(e[i+1]/s/100|0)==0:t<4?(t==0?c=c/1e3|0:t==1?c=c/100|0:t==2&&(c=c/10|0),o=(r||n<4)&&c==9999||!r&&n>3&&c==4999):o=((r||n<4)&&c+1==s||!r&&n>3&&c+1==s/2)&&(e[i+1]/s/1e3|0)==At(10,t-3)-1,o}function oa(e,t,n){for(var r,i=[0],s,o=0,c=e.length;o<c;){for(s=i.length;s--;)i[s]*=t;for(i[0]+=bl.indexOf(e.charAt(o++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function eI(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/Au(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=Hs(e,1,t.times(i),new e(1));for(var s=n;s--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=n,t}var Je=(function(){function e(r,i,s){var o,c=0,a=r.length;for(r=r.slice();a--;)o=r[a]*i+c,r[a]=o%s|0,c=o/s|0;return c&&r.unshift(c),r}function t(r,i,s,o){var c,a;if(s!=o)a=s>o?1:-1;else for(c=a=0;c<s;c++)if(r[c]!=i[c]){a=r[c]>i[c]?1:-1;break}return a}function n(r,i,s,o){for(var c=0;s--;)r[s]-=c,c=r[s]<i[s]?1:0,r[s]=c*o+r[s]-i[s];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,s,o,c,a){var u,f,l,d,y,g,m,E,S,_,w,T,O,A,R,M,v,C,q,K,H=r.constructor,D=r.s==i.s?1:-1,P=r.d,$=i.d;if(!P||!P[0]||!$||!$[0])return new H(!r.s||!i.s||(P?$&&P[0]==$[0]:!$)?NaN:P&&P[0]==0||!$?D*0:D/0);for(a?(y=1,f=r.e-i.e):(a=jn,y=_e,f=Xt(r.e/y)-Xt(i.e/y)),q=$.length,v=P.length,S=new H(D),_=S.d=[],l=0;$[l]==(P[l]||0);l++);if($[l]>(P[l]||0)&&f--,s==null?(A=s=H.precision,o=H.rounding):c?A=s+(r.e-i.e)+1:A=s,A<0)_.push(1),g=!0;else{if(A=A/y+2|0,l=0,q==1){for(d=0,$=$[0],A++;(l<v||d)&&A--;l++)R=d*a+(P[l]||0),_[l]=R/$|0,d=R%$|0;g=d||l<v}else{for(d=a/($[0]+1)|0,d>1&&($=e($,d,a),P=e(P,d,a),q=$.length,v=P.length),M=q,w=P.slice(0,q),T=w.length;T<q;)w[T++]=0;K=$.slice(),K.unshift(0),C=$[0],$[1]>=a/2&&++C;do d=0,u=t($,w,q,T),u<0?(O=w[0],q!=T&&(O=O*a+(w[1]||0)),d=O/C|0,d>1?(d>=a&&(d=a-1),m=e($,d,a),E=m.length,T=w.length,u=t(m,w,E,T),u==1&&(d--,n(m,q<E?K:$,E,a))):(d==0&&(u=d=1),m=$.slice()),E=m.length,E<T&&m.unshift(0),n(w,m,T,a),u==-1&&(T=w.length,u=t($,w,q,T),u<1&&(d++,n(w,q<T?K:$,T,a))),T=w.length):u===0&&(d++,w=[0]),_[l++]=d,u&&w[0]?w[T++]=P[M]||0:(w=[P[M]],T=1);while((M++<v||w[0]!==void 0)&&A--);g=w[0]!==void 0}_[0]||_.shift()}if(y==1)S.e=f,y1=g;else{for(l=1,d=_[0];d>=10;d/=10)l++;S.e=l+f*y-1,be(S,c?s+S.e+1:s,o,g)}return S}})();function be(e,t,n,r){var i,s,o,c,a,u,f,l,d,y=e.constructor;e:if(t!=null){if(l=e.d,!l)return e;for(i=1,c=l[0];c>=10;c/=10)i++;if(s=t-i,s<0)s+=_e,o=t,f=l[d=0],a=f/At(10,i-o-1)%10|0;else if(d=Math.ceil((s+1)/_e),c=l.length,d>=c)if(r){for(;c++<=d;)l.push(0);f=a=0,i=1,s%=_e,o=s-_e+1}else break e;else{for(f=c=l[d],i=1;c>=10;c/=10)i++;s%=_e,o=s-_e+i,a=o<0?0:f/At(10,i-o-1)%10|0}if(r=r||t<0||l[d+1]!==void 0||(o<0?f:f%At(10,i-o-1)),u=n<4?(a||r)&&(n==0||n==(e.s<0?3:2)):a>5||a==5&&(n==4||r||n==6&&(s>0?o>0?f/At(10,i-o):0:l[d-1])%10&1||n==(e.s<0?8:7)),t<1||!l[0])return l.length=0,u?(t-=e.e+1,l[0]=At(10,(_e-t%_e)%_e),e.e=-t||0):l[0]=e.e=0,e;if(s==0?(l.length=d,c=1,d--):(l.length=d+1,c=At(10,_e-s),l[d]=o>0?(f/At(10,i-o)%At(10,o)|0)*c:0),u)for(;;)if(d==0){for(s=1,o=l[0];o>=10;o/=10)s++;for(o=l[0]+=c,c=1;o>=10;o/=10)c++;s!=c&&(e.e++,l[0]==jn&&(l[0]=1));break}else{if(l[d]+=c,l[d]!=jn)break;l[d--]=0,c=1}for(s=l.length;l[--s]===0;)l.pop()}return ve&&(e.e>y.maxE?(e.d=null,e.e=NaN):e.e<y.minE&&(e.e=0,e.d=[0])),e}function sr(e,t,n){if(!e.isFinite())return T1(e);var r,i=e.e,s=Ft(e.d),o=s.length;return t?(n&&(r=n-o)>0?s=s.charAt(0)+"."+s.slice(1)+si(r):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(e.e<0?"e":"e+")+e.e):i<0?(s="0."+si(-i-1)+s,n&&(r=n-o)>0&&(s+=si(r))):i>=o?(s+=si(i+1-o),n&&(r=n-i-1)>0&&(s=s+"."+si(r))):((r=i+1)<o&&(s=s.slice(0,r)+"."+s.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(s+="."),s+=si(r))),s}function xu(e,t){var n=e[0];for(t*=_e;n>=10;n/=10)t++;return t}function La(e,t,n){if(t>Qv)throw ve=!0,n&&(e.precision=n),Error(g1);return be(new e(Fa),t,1,!0)}function nr(e,t,n){if(t>_l)throw Error(g1);return be(new e(Ma),t,n,!0)}function E1(e){var t=e.length-1,n=t*_e+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function si(e){for(var t="";e--;)t+="0";return t}function _1(e,t,n,r){var i,s=new e(1),o=Math.ceil(r/_e+4);for(ve=!1;;){if(n%2&&(s=s.times(t),Oy(s.d,o)&&(i=!0)),n=Xt(n/2),n===0){n=s.d.length-1,i&&s.d[n]===0&&++s.d[n];break}t=t.times(t),Oy(t.d,o)}return ve=!0,s}function Iy(e){return e.d[e.d.length-1]&1}function S1(e,t,n){for(var r,i,s=new e(t[0]),o=0;++o<t.length;){if(i=new e(t[o]),!i.s){s=i;break}r=s.cmp(i),(r===n||r===0&&s.s===n)&&(s=i)}return s}function Sl(e,t){var n,r,i,s,o,c,a,u=0,f=0,l=0,d=e.constructor,y=d.rounding,g=d.precision;if(!e.d||!e.d[0]||e.e>17)return new d(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(ve=!1,a=g):a=t,c=new d(.03125);e.e>-2;)e=e.times(c),l+=5;for(r=Math.log(At(2,l))/Math.LN10*2+5|0,a+=r,n=s=o=new d(1),d.precision=a;;){if(s=be(s.times(e),a,1),n=n.times(++f),c=o.plus(Je(s,n,a,1)),Ft(c.d).slice(0,a)===Ft(o.d).slice(0,a)){for(i=l;i--;)o=be(o.times(o),a,1);if(t==null)if(u<3&&jo(o.d,a-r,y,u))d.precision=a+=10,n=s=c=new d(1),f=0,u++;else return be(o,d.precision=g,y,ve=!0);else return d.precision=g,o}o=c}}function oi(e,t){var n,r,i,s,o,c,a,u,f,l,d,y=1,g=10,m=e,E=m.d,S=m.constructor,_=S.rounding,w=S.precision;if(m.s<0||!E||!E[0]||!m.e&&E[0]==1&&E.length==1)return new S(E&&!E[0]?-1/0:m.s!=1?NaN:E?0:m);if(t==null?(ve=!1,f=w):f=t,S.precision=f+=g,n=Ft(E),r=n.charAt(0),Math.abs(s=m.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)m=m.times(e),n=Ft(m.d),r=n.charAt(0),y++;s=m.e,r>1?(m=new S("0."+n),s++):m=new S(r+"."+n.slice(1))}else return u=La(S,f+2,w).times(s+""),m=oi(new S(r+"."+n.slice(1)),f-g).plus(u),S.precision=w,t==null?be(m,w,_,ve=!0):m;for(l=m,a=o=m=Je(m.minus(1),m.plus(1),f,1),d=be(m.times(m),f,1),i=3;;){if(o=be(o.times(d),f,1),u=a.plus(Je(o,new S(i),f,1)),Ft(u.d).slice(0,f)===Ft(a.d).slice(0,f))if(a=a.times(2),s!==0&&(a=a.plus(La(S,f+2,w).times(s+""))),a=Je(a,new S(y),f,1),t==null)if(jo(a.d,f-g,_,c))S.precision=f+=g,u=o=m=Je(l.minus(1),l.plus(1),f,1),d=be(m.times(m),f,1),i=c=1;else return be(a,S.precision=w,_,ve=!0);else return S.precision=w,a;a=u,i+=2}}function T1(e){return String(e.s*e.s/0)}function ca(e,t){var n,r,i;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(i=t.length;t.charCodeAt(i-1)===48;--i);if(t=t.slice(r,i),t){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%_e,n<0&&(r+=_e),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=_e;r<i;)e.d.push(+t.slice(r,r+=_e));t=t.slice(r),r=_e-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),ve&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}function tI(e,t){var n,r,i,s,o,c,a,u,f;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),b1.test(t))return ca(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Yv.test(t))n=16,t=t.toLowerCase();else if(zv.test(t))n=2;else if(Zv.test(t))n=8;else throw Error(hi+t);for(s=t.search(/p/i),s>0?(a=+t.slice(s+1),t=t.substring(2,s)):t=t.slice(2),s=t.indexOf("."),o=s>=0,r=e.constructor,o&&(t=t.replace(".",""),c=t.length,s=c-s,i=_1(r,new r(n),s,s*2)),u=oa(t,n,jn),f=u.length-1,s=f;u[s]===0;--s)u.pop();return s<0?new r(e.s*0):(e.e=xu(u,f),e.d=u,ve=!1,o&&(e=Je(e,i,c*4)),a&&(e=e.times(Math.abs(a)<54?At(2,a):Er.pow(2,a))),ve=!0,e)}function nI(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:Hs(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/Au(5,n)),t=Hs(e,2,t,t);for(var i,s=new e(5),o=new e(16),c=new e(20);n--;)i=t.times(t),t=t.times(s.plus(i.times(o.times(i).minus(c))));return t}function Hs(e,t,n,r,i){var s,o,c,a,u=e.precision,f=Math.ceil(u/_e);for(ve=!1,a=n.times(n),c=new e(r);;){if(o=Je(c.times(a),new e(t++*t++),u,1),c=i?r.plus(o):r.minus(o),r=Je(o.times(a),new e(t++*t++),u,1),o=c.plus(r),o.d[f]!==void 0){for(s=f;o.d[s]===c.d[s]&&s--;);if(s==-1)break}s=c,c=r,r=o,o=s}return ve=!0,o.d.length=f+1,o}function Au(e,t){for(var n=e;--t;)n*=e;return n}function x1(e,t){var n,r=t.s<0,i=nr(e,e.precision,1),s=i.times(.5);if(t=t.abs(),t.lte(s))return Ar=r?4:1,t;if(n=t.divToInt(i),n.isZero())Ar=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(s))return Ar=Iy(n)?r?2:3:r?4:1,t;Ar=Iy(n)?r?1:4:r?3:2}return t.minus(i).abs()}function Ch(e,t,n,r){var i,s,o,c,a,u,f,l,d,y=e.constructor,g=n!==void 0;if(g?(yn(n,1,gi),r===void 0?r=y.rounding:yn(r,0,8)):(n=y.precision,r=y.rounding),!e.isFinite())f=T1(e);else{for(f=sr(e),o=f.indexOf("."),g?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,o>=0&&(f=f.replace(".",""),d=new y(1),d.e=f.length-o,d.d=oa(sr(d),10,i),d.e=d.d.length),l=oa(f,10,i),s=a=l.length;l[--a]==0;)l.pop();if(!l[0])f=g?"0p+0":"0";else{if(o<0?s--:(e=new y(e),e.d=l,e.e=s,e=Je(e,d,n,r,0,i),l=e.d,s=e.e,u=y1),o=l[n],c=i/2,u=u||l[n+1]!==void 0,u=r<4?(o!==void 0||u)&&(r===0||r===(e.s<0?3:2)):o>c||o===c&&(r===4||u||r===6&&l[n-1]&1||r===(e.s<0?8:7)),l.length=n,u)for(;++l[--n]>i-1;)l[n]=0,n||(++s,l.unshift(1));for(a=l.length;!l[a-1];--a);for(o=0,f="";o<a;o++)f+=bl.charAt(l[o]);if(g){if(a>1)if(t==16||t==8){for(o=t==16?4:3,--a;a%o;a++)f+="0";for(l=oa(f,i,t),a=l.length;!l[a-1];--a);for(o=1,f="1.";o<a;o++)f+=bl.charAt(l[o])}else f=f.charAt(0)+"."+f.slice(1);f=f+(s<0?"p":"p+")+s}else if(s<0){for(;++s;)f="0"+f;f="0."+f}else if(++s>a)for(s-=a;s--;)f+="0";else s<a&&(f=f.slice(0,s)+"."+f.slice(s))}f=(t==16?"0x":t==2?"0b":t==8?"0o":"")+f}return e.s<0?"-"+f:f}function Oy(e,t){if(e.length>t)return e.length=t,!0}function rI(e){return new this(e).abs()}function iI(e){return new this(e).acos()}function sI(e){return new this(e).acosh()}function oI(e,t){return new this(e).plus(t)}function cI(e){return new this(e).asin()}function aI(e){return new this(e).asinh()}function uI(e){return new this(e).atan()}function fI(e){return new this(e).atanh()}function lI(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,s=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=nr(this,s,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?nr(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=nr(this,s,1).times(.5),n.s=e.s):t.s<0?(this.precision=s,this.rounding=1,n=this.atan(Je(e,t,s,1)),t=nr(this,s,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(Je(e,t,s,1)),n}function hI(e){return new this(e).cbrt()}function dI(e){return be(e=new this(e),e.e+1,2)}function pI(e,t,n){return new this(e).clamp(t,n)}function yI(e){if(!e||typeof e!="object")throw Error(Tu+"Object expected");var t,n,r,i=e.defaults===!0,s=["precision",1,gi,"rounding",0,8,"toExpNeg",-ms,0,"toExpPos",0,ms,"maxE",0,ms,"minE",-ms,0,"modulo",0,9];for(t=0;t<s.length;t+=3)if(n=s[t],i&&(this[n]=El[n]),(r=e[n])!==void 0)if(Xt(r)===r&&r>=s[t+1]&&r<=s[t+2])this[n]=r;else throw Error(hi+n+": "+r);if(n="crypto",i&&(this[n]=El[n]),(r=e[n])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(m1);else this[n]=!1;else throw Error(hi+n+": "+r);return this}function gI(e){return new this(e).cos()}function mI(e){return new this(e).cosh()}function A1(e){var t,n,r;function i(s){var o,c,a,u=this;if(!(u instanceof i))return new i(s);if(u.constructor=i,By(s)){u.s=s.s,ve?!s.d||s.e>i.maxE?(u.e=NaN,u.d=null):s.e<i.minE?(u.e=0,u.d=[0]):(u.e=s.e,u.d=s.d.slice()):(u.e=s.e,u.d=s.d?s.d.slice():s.d);return}if(a=typeof s,a==="number"){if(s===0){u.s=1/s<0?-1:1,u.e=0,u.d=[0];return}if(s<0?(s=-s,u.s=-1):u.s=1,s===~~s&&s<1e7){for(o=0,c=s;c>=10;c/=10)o++;ve?o>i.maxE?(u.e=NaN,u.d=null):o<i.minE?(u.e=0,u.d=[0]):(u.e=o,u.d=[s]):(u.e=o,u.d=[s]);return}if(s*0!==0){s||(u.s=NaN),u.e=NaN,u.d=null;return}return ca(u,s.toString())}if(a==="string")return(c=s.charCodeAt(0))===45?(s=s.slice(1),u.s=-1):(c===43&&(s=s.slice(1)),u.s=1),b1.test(s)?ca(u,s):tI(u,s);if(a==="bigint")return s<0?(s=-s,u.s=-1):u.s=1,ca(u,s.toString());throw Error(hi+s)}if(i.prototype=se,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=yI,i.clone=A1,i.isDecimal=By,i.abs=rI,i.acos=iI,i.acosh=sI,i.add=oI,i.asin=cI,i.asinh=aI,i.atan=uI,i.atanh=fI,i.atan2=lI,i.cbrt=hI,i.ceil=dI,i.clamp=pI,i.cos=gI,i.cosh=mI,i.div=wI,i.exp=bI,i.floor=EI,i.hypot=_I,i.ln=SI,i.log=TI,i.log10=AI,i.log2=xI,i.max=vI,i.min=II,i.mod=OI,i.mul=BI,i.pow=NI,i.random=kI,i.round=PI,i.sign=RI,i.sin=CI,i.sinh=UI,i.sqrt=HI,i.sub=FI,i.sum=MI,i.tan=LI,i.tanh=qI,i.trunc=VI,e===void 0&&(e={}),e&&e.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function wI(e,t){return new this(e).div(t)}function bI(e){return new this(e).exp()}function EI(e){return be(e=new this(e),e.e+1,3)}function _I(){var e,t,n=new this(0);for(ve=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return ve=!0,new this(1/0);n=t}return ve=!0,n.sqrt()}function By(e){return e instanceof Er||e&&e.toStringTag===w1||!1}function SI(e){return new this(e).ln()}function TI(e,t){return new this(e).log(t)}function xI(e){return new this(e).log(2)}function AI(e){return new this(e).log(10)}function vI(){return S1(this,arguments,-1)}function II(){return S1(this,arguments,1)}function OI(e,t){return new this(e).mod(t)}function BI(e,t){return new this(e).mul(t)}function NI(e,t){return new this(e).pow(t)}function kI(e){var t,n,r,i,s=0,o=new this(1),c=[];if(e===void 0?e=this.precision:yn(e,1,gi),r=Math.ceil(e/_e),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));s<r;)i=t[s],i>=429e7?t[s]=crypto.getRandomValues(new Uint32Array(1))[0]:c[s++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);s<r;)i=t[s]+(t[s+1]<<8)+(t[s+2]<<16)+((t[s+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,s):(c.push(i%1e7),s+=4);s=r/4}else throw Error(m1);else for(;s<r;)c[s++]=Math.random()*1e7|0;for(r=c[--s],e%=_e,r&&e&&(i=At(10,_e-e),c[s]=(r/i|0)*i);c[s]===0;s--)c.pop();if(s<0)n=0,c=[0];else{for(n=-1;c[0]===0;n-=_e)c.shift();for(r=1,i=c[0];i>=10;i/=10)r++;r<_e&&(n-=_e-r)}return o.e=n,o.d=c,o}function PI(e){return be(e=new this(e),e.e+1,this.rounding)}function RI(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function CI(e){return new this(e).sin()}function UI(e){return new this(e).sinh()}function HI(e){return new this(e).sqrt()}function FI(e,t){return new this(e).sub(t)}function MI(){var e=0,t=arguments,n=new this(t[e]);for(ve=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return ve=!0,be(n,this.precision,this.rounding)}function LI(e){return new this(e).tan()}function qI(e){return new this(e).tanh()}function VI(e){return be(e=new this(e),e.e+1,1)}se[Symbol.for("nodejs.util.inspect.custom")]=se.toString;se[Symbol.toStringTag]="Decimal";var Er=se.constructor=A1(El);Fa=new Er(Fa);Ma=new Er(Ma);const DI=({IDL:e})=>{const t=e.Variant({Ok:e.Null,Err:e.Text}),n=e.Variant({P2WPKH:e.Null,OpReturn:e.Nat64,P2SH:e.Null,P2TR:e.Null}),r=e.Record({input_types:e.Vec(n),pool_address:e.Vec(e.Text),output_types:e.Vec(n)}),i=e.Variant({Ok:e.Nat64,Err:e.Text}),s=e.Record({user_id:e.Principal}),o=e.Record({canister_version:e.Opt(e.Nat64),canister_id:e.Principal}),c=e.Variant({from_user:s,from_canister:o}),a=e.Record({controllers:e.Vec(e.Principal)}),u=e.Variant({reinstall:e.Null,upgrade:e.Null,install:e.Null}),f=e.Record({mode:u,module_hash:e.Vec(e.Nat8)}),l=e.Record({canister_version:e.Nat64,taken_at_timestamp:e.Nat64,snapshot_id:e.Vec(e.Nat8)}),d=e.Variant({creation:a,code_deployment:f,load_snapshot:l,controllers_change:a,code_uninstall:e.Null}),y=e.Record({timestamp_nanos:e.Nat64,canister_version:e.Nat64,origin:c,details:d}),g=e.Record({controllers:e.Vec(e.Principal),module_hash:e.Opt(e.Vec(e.Nat8)),recent_changes:e.Vec(y),total_num_changes:e.Nat64}),m=e.Variant({Ok:g,Err:e.Text}),E=e.Record({exchange_id:e.Text,pool_address:e.Text,pool_key:e.Text}),S=e.Variant({All:e.Null,ByTxid:e.Text,ByAddress:e.Text,BySecondsPassed:e.Nat64}),_=e.Variant({Ok:e.Text,Err:e.Text}),w=e.Record({result:_,exchange_id:e.Text,maybe_return_time:e.Opt(e.Text),calling_method:e.Text,calling_args:e.Text,pool_address:e.Text,calling_time:e.Text}),T=e.Record({rollback_results:e.Vec(e.Text),invoke_args:e.Text,invoke_time:e.Text,finalized_time:e.Opt(e.Text),confirmed_time:e.Opt(e.Text),execution_steps:e.Vec(w),processing_result:_,broadcasted_time:e.Opt(e.Text)}),O=e.Record({block_hash:e.Text,block_height:e.Nat32}),A=e.Record({processing_results:e.Vec(e.Text),block_basic:O,txids:e.Vec(e.Text),block_time:e.Text,received_time:e.Text}),R=e.Variant({Active:e.Null,Halted:e.Record({reason:e.Text})}),M=e.Record({status:R,exchange_id:e.Text,canister_id:e.Principal,client_canisters:e.Vec(e.Principal)}),v=e.Record({rollback_results:e.Vec(e.Text),txid:e.Text,received_time:e.Text,reason:e.Text}),C=e.Variant({mainnet:e.Null,regtest:e.Null,testnet:e.Null}),q=e.Record({exchange_registry_principal:e.Principal,max_input_count_of_psbt:e.Nat32,min_tx_confirmations:e.Nat32,mempool_connector_principal:e.Principal,max_unconfirmed_tx_count_in_pool:e.Nat32,min_btc_amount_for_utxo:e.Nat64,rune_indexer_principal:e.Principal,max_intentions_per_invoke:e.Nat32,max_received_blocks_count:e.Nat32,bitcoin_network:C}),K=e.Record({low:e.Nat64,high:e.Nat64,update_time:e.Text,medium:e.Nat64}),H=e.Variant({Enabled:e.Null,Disabled:e.Null,AllowEmpty:e.Null}),D=e.Record({last_block:e.Opt(O),pending_tx_count:e.Nat64,mempool_tx_fee_rate:K,invoke_paused:e.Bool,utxo_proof_verification_status:H}),P=e.Variant({Confirmed:e.Nat32,Rejected:e.Text,Pending:e.Null}),$=e.Record({status:e.Opt(P),invoke_log:T,included_block:e.Opt(O),sent_tx_hex:e.Text}),F=e.Record({id:e.Text,value:e.Nat}),x=e.Record({maybe_rune:e.Opt(F),value:e.Nat64,script_pubkey_hex:e.Text,outpoint:e.Text}),B=e.Record({coin:F,from:e.Text}),L=e.Record({to:e.Text,coin:F}),N=e.Record({coins:e.Vec(F),sats:e.Nat64,txid:e.Text,vout:e.Nat32}),V=e.Record({input_coins:e.Vec(B),output_coins:e.Vec(L),action:e.Text,exchange_id:e.Text,pool_utxo_spent:e.Vec(e.Text),action_params:e.Text,nonce:e.Nat64,pool_address:e.Text,pool_utxo_received:e.Vec(N)}),G=e.Record({tx_fee_in_sats:e.Nat64,initiator_address:e.Text,intentions:e.Vec(V)}),X=e.Record({intention_set:G,initiator_utxo_proof:e.Vec(e.Nat8),psbt_hex:e.Text}),Y=e.Record({block_hash:e.Text,block_timestamp:e.Nat64,tx_ids:e.Vec(e.Text),block_height:e.Nat32}),ce=e.Variant({Ok:e.Vec(e.Text),Err:e.Text}),ue=e.Record({exchange_canister:e.Principal,exchange_id:e.Text,client_canisters:e.Vec(e.Principal)}),te=e.Record({txid:e.Text,timestamp:e.Nat64,block:O}),Z=e.Record({low:e.Nat64,high:e.Nat64,medium:e.Nat64});return e.Service({clear_failed_invoke_logs:e.Func([e.Opt(e.Nat64),e.Vec(e.Text)],[t],[]),estimate_min_tx_fee:e.Func([r],[i],["query"]),get_canister_info:e.Func([e.Nat64],[m],[]),get_exchange_pools:e.Func([],[e.Vec(E)],["query"]),get_failed_invoke_logs:e.Func([S],[e.Vec(e.Tuple(e.Text,T))],["query"]),get_last_sent_txs:e.Func([e.Opt(e.Nat32)],[e.Vec(e.Tuple(e.Text,e.Text,e.Opt(e.Nat32)))],["query"]),get_received_blocks:e.Func([e.Opt(e.Bool)],[e.Vec(A)],["query"]),get_registered_exchanges:e.Func([],[e.Vec(M)],["query"]),get_rejected_txs:e.Func([e.Opt(e.Nat32)],[e.Vec(v)],["query"]),get_settings:e.Func([],[q],["query"]),get_status:e.Func([],[D],["query"]),get_tx_for_outpoint:e.Func([e.Text],[e.Opt($)],["query"]),get_tx_queue_of_pool:e.Func([e.Text],[e.Vec(e.Tuple(e.Text,e.Opt(e.Nat32)))],["query"]),get_tx_sent:e.Func([e.Text],[e.Opt($)],["query"]),get_used_outpoints:e.Func([e.Opt(e.Text)],[e.Vec(e.Tuple(e.Text,e.Text))],["query"]),get_zero_confirmed_tx_count_of_pool:e.Func([e.Text],[e.Nat32],["query"]),get_zero_confirmed_txs:e.Func([e.Opt(e.Text)],[e.Vec(e.Text)],["query"]),get_zero_confirmed_utxos_of_address:e.Func([e.Text],[e.Vec(x)],["query"]),invoke:e.Func([X],[_],[]),new_block_detected:e.Func([Y],[t],[]),notify_exchange_for_blocks_from_height:e.Func([e.Text,e.Nat32],[ce],[]),register_exchange:e.Func([ue],[t],[]),save_included_block_for_tx:e.Func([te],[t],[]),set_max_input_count_of_psbt:e.Func([e.Nat32],[t],[]),set_max_intentions_per_invoke:e.Func([e.Nat32],[t],[]),set_max_received_blocks_count:e.Func([e.Nat32],[t],[]),set_max_unconfirmed_tx_count_in_pool:e.Func([e.Nat32],[t],[]),set_min_btc_amount_for_utxo:e.Func([e.Nat64],[t],[]),set_min_tx_confirmations:e.Func([e.Nat32],[t],[]),set_tx_fee_per_vbyte:e.Func([Z],[t],[]),update_bitcoin_subnet_certificate:e.Func([e.Vec(e.Nat8)],[],[]),version:e.Func([],[e.Text],["query"])})};class v1{maestro;config;exchange;orchestrator;constructor(t){this.config=t;const n=t.network===Bs.Testnet,r=n?"https://xbt-testnet.gomaestro-api.org/v0":"https://xbt-mainnet.gomaestro-api.org/v0";this.maestro=new rx({baseUrl:r,apiKey:t.maestroApiKey});const i="https://icp0.io";this.exchange=Ha.createActor(t.exchangeIdlFactory,{agent:xr.createSync({host:i,retryTimes:50,verifyQuerySignatures:!1}),canisterId:t.exchangeCanisterId}),this.orchestrator=Ha.createActor(DI,{agent:xr.createSync({host:i,retryTimes:50,verifyQuerySignatures:!1}),canisterId:n?VA:qA})}async filterSpentUtxos(t,n){const r=await this.orchestrator.get_used_outpoints([t]);return n.filter(({txid:i,vout:s})=>r.findIndex(([o])=>`${i}:${s}`===o)<0)}async getBtcUtxos(t,n=!0){let r=null;const i=[];do{const o=await this.maestro.utxosByAddress(t,r,n);i.push(...o.data),r=o.next_cursor}while(r!==null);const s=i.map(({txid:o,vout:c,runes:a,satoshis:u,script_pubkey:f,address:l})=>({txid:o,vout:c,address:l,runes:a.map(({rune_id:d,amount:y})=>{const g=(y.split(".")[1]??"").length,m=new Er(y).mul(10**g).toFixed(0);return{id:d,amount:m}}),satoshis:u,scriptPk:f}));return this.filterSpentUtxos(t,s)}async getRuneUtxos(t,n){let r=null;const i=[];do{const o=await this.maestro.runeUtxosByAddress(t,n,r);i.push(...o.data),r=o.next_cursor}while(r!==null);const s=i.map(({txid:o,vout:c,runes:a,satoshis:u})=>{const f=Bh(t,this.config.network);return{txid:o,vout:c,address:t,runes:a.map(({rune_id:l,amount:d})=>{const y=(d.split(".")[1]??"").length,g=new Er(d).mul(10**y).toFixed(0);return{id:l,amount:g}}),satoshis:u,scriptPk:Ih(f)}});return this.filterSpentUtxos(t,s)}async searchRunes(t){const n=this.config.network===Bs.Testnet?$A:DA,r=Xv`
132
+ */var ws=9e15,gi=1e9,bl="0123456789abcdef",Fa="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058",Ma="3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789",El={precision:20,rounding:4,modulo:1,toExpNeg:-7,toExpPos:21,minE:-ws,maxE:ws,crypto:!1},y1,Ar,ve=!0,Tu="[DecimalError] ",hi=Tu+"Invalid argument: ",g1=Tu+"Precision limit exceeded",m1=Tu+"crypto unavailable",w1="[object Decimal]",Xt=Math.floor,At=Math.pow,zv=/^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,Yv=/^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,Zv=/^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,b1=/^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,jn=1e7,_e=7,Jv=9007199254740991,Qv=Fa.length-1,_l=Ma.length-1,se={toStringTag:w1};se.absoluteValue=se.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),be(e)};se.ceil=function(){return be(new this.constructor(this),this.e+1,2)};se.clampedTo=se.clamp=function(e,t){var n,r=this,i=r.constructor;if(e=new i(e),t=new i(t),!e.s||!t.s)return new i(NaN);if(e.gt(t))throw Error(hi+t);return n=r.cmp(e),n<0?e:r.cmp(t)>0?t:new i(r)};se.comparedTo=se.cmp=function(e){var t,n,r,i,s=this,o=s.d,c=(e=new s.constructor(e)).d,a=s.s,u=e.s;if(!o||!c)return!a||!u?NaN:a!==u?a:o===c?0:!o^a<0?1:-1;if(!o[0]||!c[0])return o[0]?a:c[0]?-u:0;if(a!==u)return a;if(s.e!==e.e)return s.e>e.e^a<0?1:-1;for(r=o.length,i=c.length,t=0,n=r<i?r:i;t<n;++t)if(o[t]!==c[t])return o[t]>c[t]^a<0?1:-1;return r===i?0:r>i^a<0?1:-1};se.cosine=se.cos=function(){var e,t,n=this,r=n.constructor;return n.d?n.d[0]?(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+_e,r.rounding=1,n=eI(r,x1(r,n)),r.precision=e,r.rounding=t,be(Ar==2||Ar==3?n.neg():n,e,t,!0)):new r(1):new r(NaN)};se.cubeRoot=se.cbrt=function(){var e,t,n,r,i,s,o,c,a,u,f=this,l=f.constructor;if(!f.isFinite()||f.isZero())return new l(f);for(ve=!1,s=f.s*At(f.s*f,1/3),!s||Math.abs(s)==1/0?(n=Ft(f.d),e=f.e,(s=(e-n.length+1)%3)&&(n+=s==1||s==-2?"0":"00"),s=At(n,1/3),e=Xt((e+1)/3)-(e%3==(e<0?-1:2)),s==1/0?n="5e"+e:(n=s.toExponential(),n=n.slice(0,n.indexOf("e")+1)+e),r=new l(n),r.s=f.s):r=new l(s.toString()),o=(e=l.precision)+3;;)if(c=r,a=c.times(c).times(c),u=a.plus(f),r=Je(u.plus(f).times(c),u.plus(a),o+2,1),Ft(c.d).slice(0,o)===(n=Ft(r.d)).slice(0,o))if(n=n.slice(o-3,o+1),n=="9999"||!i&&n=="4999"){if(!i&&(be(c,e+1,0),c.times(c).times(c).eq(f))){r=c;break}o+=4,i=1}else{(!+n||!+n.slice(1)&&n.charAt(0)=="5")&&(be(r,e+1,1),t=!r.times(r).times(r).eq(f));break}return ve=!0,be(r,e,l.rounding,t)};se.decimalPlaces=se.dp=function(){var e,t=this.d,n=NaN;if(t){if(e=t.length-1,n=(e-Xt(this.e/_e))*_e,e=t[e],e)for(;e%10==0;e/=10)n--;n<0&&(n=0)}return n};se.dividedBy=se.div=function(e){return Je(this,new this.constructor(e))};se.dividedToIntegerBy=se.divToInt=function(e){var t=this,n=t.constructor;return be(Je(t,new n(e),0,1,1),n.precision,n.rounding)};se.equals=se.eq=function(e){return this.cmp(e)===0};se.floor=function(){return be(new this.constructor(this),this.e+1,3)};se.greaterThan=se.gt=function(e){return this.cmp(e)>0};se.greaterThanOrEqualTo=se.gte=function(e){var t=this.cmp(e);return t==1||t===0};se.hyperbolicCosine=se.cosh=function(){var e,t,n,r,i,s=this,o=s.constructor,c=new o(1);if(!s.isFinite())return new o(s.s?1/0:NaN);if(s.isZero())return c;n=o.precision,r=o.rounding,o.precision=n+Math.max(s.e,s.sd())+4,o.rounding=1,i=s.d.length,i<32?(e=Math.ceil(i/3),t=(1/Au(4,e)).toString()):(e=16,t="2.3283064365386962890625e-10"),s=Fs(o,1,s.times(t),new o(1),!0);for(var a,u=e,f=new o(8);u--;)a=s.times(s),s=c.minus(a.times(f.minus(a.times(f))));return be(s,o.precision=n,o.rounding=r,!0)};se.hyperbolicSine=se.sinh=function(){var e,t,n,r,i=this,s=i.constructor;if(!i.isFinite()||i.isZero())return new s(i);if(t=s.precision,n=s.rounding,s.precision=t+Math.max(i.e,i.sd())+4,s.rounding=1,r=i.d.length,r<3)i=Fs(s,2,i,i,!0);else{e=1.4*Math.sqrt(r),e=e>16?16:e|0,i=i.times(1/Au(5,e)),i=Fs(s,2,i,i,!0);for(var o,c=new s(5),a=new s(16),u=new s(20);e--;)o=i.times(i),i=i.times(c.plus(o.times(a.times(o).plus(u))))}return s.precision=t,s.rounding=n,be(i,t,n,!0)};se.hyperbolicTangent=se.tanh=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+7,r.rounding=1,Je(n.sinh(),n.cosh(),r.precision=e,r.rounding=t)):new r(n.s)};se.inverseCosine=se.acos=function(){var e=this,t=e.constructor,n=e.abs().cmp(1),r=t.precision,i=t.rounding;return n!==-1?n===0?e.isNeg()?nr(t,r,i):new t(0):new t(NaN):e.isZero()?nr(t,r+4,i).times(.5):(t.precision=r+6,t.rounding=1,e=new t(1).minus(e).div(e.plus(1)).sqrt().atan(),t.precision=r,t.rounding=i,e.times(2))};se.inverseHyperbolicCosine=se.acosh=function(){var e,t,n=this,r=n.constructor;return n.lte(1)?new r(n.eq(1)?0:NaN):n.isFinite()?(e=r.precision,t=r.rounding,r.precision=e+Math.max(Math.abs(n.e),n.sd())+4,r.rounding=1,ve=!1,n=n.times(n).minus(1).sqrt().plus(n),ve=!0,r.precision=e,r.rounding=t,n.ln()):new r(n)};se.inverseHyperbolicSine=se.asinh=function(){var e,t,n=this,r=n.constructor;return!n.isFinite()||n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+2*Math.max(Math.abs(n.e),n.sd())+6,r.rounding=1,ve=!1,n=n.times(n).plus(1).sqrt().plus(n),ve=!0,r.precision=e,r.rounding=t,n.ln())};se.inverseHyperbolicTangent=se.atanh=function(){var e,t,n,r,i=this,s=i.constructor;return i.isFinite()?i.e>=0?new s(i.abs().eq(1)?i.s/0:i.isZero()?i:NaN):(e=s.precision,t=s.rounding,r=i.sd(),Math.max(r,e)<2*-i.e-1?be(new s(i),e,t,!0):(s.precision=n=r-i.e,i=Je(i.plus(1),new s(1).minus(i),n+e,1),s.precision=e+4,s.rounding=1,i=i.ln(),s.precision=e,s.rounding=t,i.times(.5))):new s(NaN)};se.inverseSine=se.asin=function(){var e,t,n,r,i=this,s=i.constructor;return i.isZero()?new s(i):(t=i.abs().cmp(1),n=s.precision,r=s.rounding,t!==-1?t===0?(e=nr(s,n+4,r).times(.5),e.s=i.s,e):new s(NaN):(s.precision=n+6,s.rounding=1,i=i.div(new s(1).minus(i.times(i)).sqrt().plus(1)).atan(),s.precision=n,s.rounding=r,i.times(2)))};se.inverseTangent=se.atan=function(){var e,t,n,r,i,s,o,c,a,u=this,f=u.constructor,l=f.precision,d=f.rounding;if(u.isFinite()){if(u.isZero())return new f(u);if(u.abs().eq(1)&&l+4<=_l)return o=nr(f,l+4,d).times(.25),o.s=u.s,o}else{if(!u.s)return new f(NaN);if(l+4<=_l)return o=nr(f,l+4,d).times(.5),o.s=u.s,o}for(f.precision=c=l+10,f.rounding=1,n=Math.min(28,c/_e+2|0),e=n;e;--e)u=u.div(u.times(u).plus(1).sqrt().plus(1));for(ve=!1,t=Math.ceil(c/_e),r=1,a=u.times(u),o=new f(u),i=u;e!==-1;)if(i=i.times(a),s=o.minus(i.div(r+=2)),i=i.times(a),o=s.plus(i.div(r+=2)),o.d[t]!==void 0)for(e=t;o.d[e]===s.d[e]&&e--;);return n&&(o=o.times(2<<n-1)),ve=!0,be(o,f.precision=l,f.rounding=d,!0)};se.isFinite=function(){return!!this.d};se.isInteger=se.isInt=function(){return!!this.d&&Xt(this.e/_e)>this.d.length-2};se.isNaN=function(){return!this.s};se.isNegative=se.isNeg=function(){return this.s<0};se.isPositive=se.isPos=function(){return this.s>0};se.isZero=function(){return!!this.d&&this.d[0]===0};se.lessThan=se.lt=function(e){return this.cmp(e)<0};se.lessThanOrEqualTo=se.lte=function(e){return this.cmp(e)<1};se.logarithm=se.log=function(e){var t,n,r,i,s,o,c,a,u=this,f=u.constructor,l=f.precision,d=f.rounding,y=5;if(e==null)e=new f(10),t=!0;else{if(e=new f(e),n=e.d,e.s<0||!n||!n[0]||e.eq(1))return new f(NaN);t=e.eq(10)}if(n=u.d,u.s<0||!n||!n[0]||u.eq(1))return new f(n&&!n[0]?-1/0:u.s!=1?NaN:n?0:1/0);if(t)if(n.length>1)s=!0;else{for(i=n[0];i%10===0;)i/=10;s=i!==1}if(ve=!1,c=l+y,o=oi(u,c),r=t?La(f,c+10):oi(e,c),a=Je(o,r,c,1),jo(a.d,i=l,d))do if(c+=10,o=oi(u,c),r=t?La(f,c+10):oi(e,c),a=Je(o,r,c,1),!s){+Ft(a.d).slice(i+1,i+15)+1==1e14&&(a=be(a,l+1,0));break}while(jo(a.d,i+=10,d));return ve=!0,be(a,l,d)};se.minus=se.sub=function(e){var t,n,r,i,s,o,c,a,u,f,l,d,y=this,g=y.constructor;if(e=new g(e),!y.d||!e.d)return!y.s||!e.s?e=new g(NaN):y.d?e.s=-e.s:e=new g(e.d||y.s!==e.s?y:NaN),e;if(y.s!=e.s)return e.s=-e.s,y.plus(e);if(u=y.d,d=e.d,c=g.precision,a=g.rounding,!u[0]||!d[0]){if(d[0])e.s=-e.s;else if(u[0])e=new g(y);else return new g(a===3?-0:0);return ve?be(e,c,a):e}if(n=Xt(e.e/_e),f=Xt(y.e/_e),u=u.slice(),s=f-n,s){for(l=s<0,l?(t=u,s=-s,o=d.length):(t=d,n=f,o=u.length),r=Math.max(Math.ceil(c/_e),o)+2,s>r&&(s=r,t.length=1),t.reverse(),r=s;r--;)t.push(0);t.reverse()}else{for(r=u.length,o=d.length,l=r<o,l&&(o=r),r=0;r<o;r++)if(u[r]!=d[r]){l=u[r]<d[r];break}s=0}for(l&&(t=u,u=d,d=t,e.s=-e.s),o=u.length,r=d.length-o;r>0;--r)u[o++]=0;for(r=d.length;r>s;){if(u[--r]<d[r]){for(i=r;i&&u[--i]===0;)u[i]=jn-1;--u[i],u[r]+=jn}u[r]-=d[r]}for(;u[--o]===0;)u.pop();for(;u[0]===0;u.shift())--n;return u[0]?(e.d=u,e.e=xu(u,n),ve?be(e,c,a):e):new g(a===3?-0:0)};se.modulo=se.mod=function(e){var t,n=this,r=n.constructor;return e=new r(e),!n.d||!e.s||e.d&&!e.d[0]?new r(NaN):!e.d||n.d&&!n.d[0]?be(new r(n),r.precision,r.rounding):(ve=!1,r.modulo==9?(t=Je(n,e.abs(),0,3,1),t.s*=e.s):t=Je(n,e,0,r.modulo,1),t=t.times(e),ve=!0,n.minus(t))};se.naturalExponential=se.exp=function(){return Sl(this)};se.naturalLogarithm=se.ln=function(){return oi(this)};se.negated=se.neg=function(){var e=new this.constructor(this);return e.s=-e.s,be(e)};se.plus=se.add=function(e){var t,n,r,i,s,o,c,a,u,f,l=this,d=l.constructor;if(e=new d(e),!l.d||!e.d)return!l.s||!e.s?e=new d(NaN):l.d||(e=new d(e.d||l.s===e.s?l:NaN)),e;if(l.s!=e.s)return e.s=-e.s,l.minus(e);if(u=l.d,f=e.d,c=d.precision,a=d.rounding,!u[0]||!f[0])return f[0]||(e=new d(l)),ve?be(e,c,a):e;if(s=Xt(l.e/_e),r=Xt(e.e/_e),u=u.slice(),i=s-r,i){for(i<0?(n=u,i=-i,o=f.length):(n=f,r=s,o=u.length),s=Math.ceil(c/_e),o=s>o?s+1:o+1,i>o&&(i=o,n.length=1),n.reverse();i--;)n.push(0);n.reverse()}for(o=u.length,i=f.length,o-i<0&&(i=o,n=f,f=u,u=n),t=0;i;)t=(u[--i]=u[i]+f[i]+t)/jn|0,u[i]%=jn;for(t&&(u.unshift(t),++r),o=u.length;u[--o]==0;)u.pop();return e.d=u,e.e=xu(u,r),ve?be(e,c,a):e};se.precision=se.sd=function(e){var t,n=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(hi+e);return n.d?(t=E1(n.d),e&&n.e+1>t&&(t=n.e+1)):t=NaN,t};se.round=function(){var e=this,t=e.constructor;return be(new t(e),e.e+1,t.rounding)};se.sine=se.sin=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+Math.max(n.e,n.sd())+_e,r.rounding=1,n=nI(r,x1(r,n)),r.precision=e,r.rounding=t,be(Ar>2?n.neg():n,e,t,!0)):new r(NaN)};se.squareRoot=se.sqrt=function(){var e,t,n,r,i,s,o=this,c=o.d,a=o.e,u=o.s,f=o.constructor;if(u!==1||!c||!c[0])return new f(!u||u<0&&(!c||c[0])?NaN:c?o:1/0);for(ve=!1,u=Math.sqrt(+o),u==0||u==1/0?(t=Ft(c),(t.length+a)%2==0&&(t+="0"),u=Math.sqrt(t),a=Xt((a+1)/2)-(a<0||a%2),u==1/0?t="5e"+a:(t=u.toExponential(),t=t.slice(0,t.indexOf("e")+1)+a),r=new f(t)):r=new f(u.toString()),n=(a=f.precision)+3;;)if(s=r,r=s.plus(Je(o,s,n+2,1)).times(.5),Ft(s.d).slice(0,n)===(t=Ft(r.d)).slice(0,n))if(t=t.slice(n-3,n+1),t=="9999"||!i&&t=="4999"){if(!i&&(be(s,a+1,0),s.times(s).eq(o))){r=s;break}n+=4,i=1}else{(!+t||!+t.slice(1)&&t.charAt(0)=="5")&&(be(r,a+1,1),e=!r.times(r).eq(o));break}return ve=!0,be(r,a,f.rounding,e)};se.tangent=se.tan=function(){var e,t,n=this,r=n.constructor;return n.isFinite()?n.isZero()?new r(n):(e=r.precision,t=r.rounding,r.precision=e+10,r.rounding=1,n=n.sin(),n.s=1,n=Je(n,new r(1).minus(n.times(n)).sqrt(),e+10,0),r.precision=e,r.rounding=t,be(Ar==2||Ar==4?n.neg():n,e,t,!0)):new r(NaN)};se.times=se.mul=function(e){var t,n,r,i,s,o,c,a,u,f=this,l=f.constructor,d=f.d,y=(e=new l(e)).d;if(e.s*=f.s,!d||!d[0]||!y||!y[0])return new l(!e.s||d&&!d[0]&&!y||y&&!y[0]&&!d?NaN:!d||!y?e.s/0:e.s*0);for(n=Xt(f.e/_e)+Xt(e.e/_e),a=d.length,u=y.length,a<u&&(s=d,d=y,y=s,o=a,a=u,u=o),s=[],o=a+u,r=o;r--;)s.push(0);for(r=u;--r>=0;){for(t=0,i=a+r;i>r;)c=s[i]+y[r]*d[i-r-1]+t,s[i--]=c%jn|0,t=c/jn|0;s[i]=(s[i]+t)%jn|0}for(;!s[--o];)s.pop();return t?++n:s.shift(),e.d=s,e.e=xu(s,n),ve?be(e,l.precision,l.rounding):e};se.toBinary=function(e,t){return Ch(this,2,e,t)};se.toDecimalPlaces=se.toDP=function(e,t){var n=this,r=n.constructor;return n=new r(n),e===void 0?n:(yn(e,0,gi),t===void 0?t=r.rounding:yn(t,0,8),be(n,e+n.e+1,t))};se.toExponential=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=sr(r,!0):(yn(e,0,gi),t===void 0?t=i.rounding:yn(t,0,8),r=be(new i(r),e+1,t),n=sr(r,!0,e+1)),r.isNeg()&&!r.isZero()?"-"+n:n};se.toFixed=function(e,t){var n,r,i=this,s=i.constructor;return e===void 0?n=sr(i):(yn(e,0,gi),t===void 0?t=s.rounding:yn(t,0,8),r=be(new s(i),e+i.e+1,t),n=sr(r,!1,e+r.e+1)),i.isNeg()&&!i.isZero()?"-"+n:n};se.toFraction=function(e){var t,n,r,i,s,o,c,a,u,f,l,d,y=this,g=y.d,m=y.constructor;if(!g)return new m(y);if(u=n=new m(1),r=a=new m(0),t=new m(r),s=t.e=E1(g)-y.e-1,o=s%_e,t.d[0]=At(10,o<0?_e+o:o),e==null)e=s>0?t:u;else{if(c=new m(e),!c.isInt()||c.lt(u))throw Error(hi+c);e=c.gt(t)?s>0?t:u:c}for(ve=!1,c=new m(Ft(g)),f=m.precision,m.precision=s=g.length*_e*2;l=Je(c,t,0,1,1),i=n.plus(l.times(r)),i.cmp(e)!=1;)n=r,r=i,i=u,u=a.plus(l.times(i)),a=i,i=t,t=c.minus(l.times(i)),c=i;return i=Je(e.minus(n),r,0,1,1),a=a.plus(i.times(u)),n=n.plus(i.times(r)),a.s=u.s=y.s,d=Je(u,r,s,1).minus(y).abs().cmp(Je(a,n,s,1).minus(y).abs())<1?[u,r]:[a,n],m.precision=f,ve=!0,d};se.toHexadecimal=se.toHex=function(e,t){return Ch(this,16,e,t)};se.toNearest=function(e,t){var n=this,r=n.constructor;if(n=new r(n),e==null){if(!n.d)return n;e=new r(1),t=r.rounding}else{if(e=new r(e),t===void 0?t=r.rounding:yn(t,0,8),!n.d)return e.s?n:e;if(!e.d)return e.s&&(e.s=n.s),e}return e.d[0]?(ve=!1,n=Je(n,e,0,t,1).times(e),ve=!0,be(n)):(e.s=n.s,n=e),n};se.toNumber=function(){return+this};se.toOctal=function(e,t){return Ch(this,8,e,t)};se.toPower=se.pow=function(e){var t,n,r,i,s,o,c=this,a=c.constructor,u=+(e=new a(e));if(!c.d||!e.d||!c.d[0]||!e.d[0])return new a(At(+c,u));if(c=new a(c),c.eq(1))return c;if(r=a.precision,s=a.rounding,e.eq(1))return be(c,r,s);if(t=Xt(e.e/_e),t>=e.d.length-1&&(n=u<0?-u:u)<=Jv)return i=_1(a,c,n,r),e.s<0?new a(1).div(i):be(i,r,s);if(o=c.s,o<0){if(t<e.d.length-1)return new a(NaN);if((e.d[t]&1)==0&&(o=1),c.e==0&&c.d[0]==1&&c.d.length==1)return c.s=o,c}return n=At(+c,u),t=n==0||!isFinite(n)?Xt(u*(Math.log("0."+Ft(c.d))/Math.LN10+c.e+1)):new a(n+"").e,t>a.maxE+1||t<a.minE-1?new a(t>0?o/0:0):(ve=!1,a.rounding=c.s=1,n=Math.min(12,(t+"").length),i=Sl(e.times(oi(c,r+n)),r),i.d&&(i=be(i,r+5,1),jo(i.d,r,s)&&(t=r+10,i=be(Sl(e.times(oi(c,t+n)),t),t+5,1),+Ft(i.d).slice(r+1,r+15)+1==1e14&&(i=be(i,r+1,0)))),i.s=o,ve=!0,a.rounding=s,be(i,r,s))};se.toPrecision=function(e,t){var n,r=this,i=r.constructor;return e===void 0?n=sr(r,r.e<=i.toExpNeg||r.e>=i.toExpPos):(yn(e,1,gi),t===void 0?t=i.rounding:yn(t,0,8),r=be(new i(r),e,t),n=sr(r,e<=r.e||r.e<=i.toExpNeg,e)),r.isNeg()&&!r.isZero()?"-"+n:n};se.toSignificantDigits=se.toSD=function(e,t){var n=this,r=n.constructor;return e===void 0?(e=r.precision,t=r.rounding):(yn(e,1,gi),t===void 0?t=r.rounding:yn(t,0,8)),be(new r(n),e,t)};se.toString=function(){var e=this,t=e.constructor,n=sr(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()&&!e.isZero()?"-"+n:n};se.truncated=se.trunc=function(){return be(new this.constructor(this),this.e+1,1)};se.valueOf=se.toJSON=function(){var e=this,t=e.constructor,n=sr(e,e.e<=t.toExpNeg||e.e>=t.toExpPos);return e.isNeg()?"-"+n:n};function Ft(e){var t,n,r,i=e.length-1,s="",o=e[0];if(i>0){for(s+=o,t=1;t<i;t++)r=e[t]+"",n=_e-r.length,n&&(s+=si(n)),s+=r;o=e[t],r=o+"",n=_e-r.length,n&&(s+=si(n))}else if(o===0)return"0";for(;o%10===0;)o/=10;return s+o}function yn(e,t,n){if(e!==~~e||e<t||e>n)throw Error(hi+e)}function jo(e,t,n,r){var i,s,o,c;for(s=e[0];s>=10;s/=10)--t;return--t<0?(t+=_e,i=0):(i=Math.ceil((t+1)/_e),t%=_e),s=At(10,_e-t),c=e[i]%s|0,r==null?t<3?(t==0?c=c/100|0:t==1&&(c=c/10|0),o=n<4&&c==99999||n>3&&c==49999||c==5e4||c==0):o=(n<4&&c+1==s||n>3&&c+1==s/2)&&(e[i+1]/s/100|0)==At(10,t-2)-1||(c==s/2||c==0)&&(e[i+1]/s/100|0)==0:t<4?(t==0?c=c/1e3|0:t==1?c=c/100|0:t==2&&(c=c/10|0),o=(r||n<4)&&c==9999||!r&&n>3&&c==4999):o=((r||n<4)&&c+1==s||!r&&n>3&&c+1==s/2)&&(e[i+1]/s/1e3|0)==At(10,t-3)-1,o}function oa(e,t,n){for(var r,i=[0],s,o=0,c=e.length;o<c;){for(s=i.length;s--;)i[s]*=t;for(i[0]+=bl.indexOf(e.charAt(o++)),r=0;r<i.length;r++)i[r]>n-1&&(i[r+1]===void 0&&(i[r+1]=0),i[r+1]+=i[r]/n|0,i[r]%=n)}return i.reverse()}function eI(e,t){var n,r,i;if(t.isZero())return t;r=t.d.length,r<32?(n=Math.ceil(r/3),i=(1/Au(4,n)).toString()):(n=16,i="2.3283064365386962890625e-10"),e.precision+=n,t=Fs(e,1,t.times(i),new e(1));for(var s=n;s--;){var o=t.times(t);t=o.times(o).minus(o).times(8).plus(1)}return e.precision-=n,t}var Je=(function(){function e(r,i,s){var o,c=0,a=r.length;for(r=r.slice();a--;)o=r[a]*i+c,r[a]=o%s|0,c=o/s|0;return c&&r.unshift(c),r}function t(r,i,s,o){var c,a;if(s!=o)a=s>o?1:-1;else for(c=a=0;c<s;c++)if(r[c]!=i[c]){a=r[c]>i[c]?1:-1;break}return a}function n(r,i,s,o){for(var c=0;s--;)r[s]-=c,c=r[s]<i[s]?1:0,r[s]=c*o+r[s]-i[s];for(;!r[0]&&r.length>1;)r.shift()}return function(r,i,s,o,c,a){var u,f,l,d,y,g,m,E,S,_,w,T,O,A,R,M,v,C,q,K,H=r.constructor,D=r.s==i.s?1:-1,P=r.d,$=i.d;if(!P||!P[0]||!$||!$[0])return new H(!r.s||!i.s||(P?$&&P[0]==$[0]:!$)?NaN:P&&P[0]==0||!$?D*0:D/0);for(a?(y=1,f=r.e-i.e):(a=jn,y=_e,f=Xt(r.e/y)-Xt(i.e/y)),q=$.length,v=P.length,S=new H(D),_=S.d=[],l=0;$[l]==(P[l]||0);l++);if($[l]>(P[l]||0)&&f--,s==null?(A=s=H.precision,o=H.rounding):c?A=s+(r.e-i.e)+1:A=s,A<0)_.push(1),g=!0;else{if(A=A/y+2|0,l=0,q==1){for(d=0,$=$[0],A++;(l<v||d)&&A--;l++)R=d*a+(P[l]||0),_[l]=R/$|0,d=R%$|0;g=d||l<v}else{for(d=a/($[0]+1)|0,d>1&&($=e($,d,a),P=e(P,d,a),q=$.length,v=P.length),M=q,w=P.slice(0,q),T=w.length;T<q;)w[T++]=0;K=$.slice(),K.unshift(0),C=$[0],$[1]>=a/2&&++C;do d=0,u=t($,w,q,T),u<0?(O=w[0],q!=T&&(O=O*a+(w[1]||0)),d=O/C|0,d>1?(d>=a&&(d=a-1),m=e($,d,a),E=m.length,T=w.length,u=t(m,w,E,T),u==1&&(d--,n(m,q<E?K:$,E,a))):(d==0&&(u=d=1),m=$.slice()),E=m.length,E<T&&m.unshift(0),n(w,m,T,a),u==-1&&(T=w.length,u=t($,w,q,T),u<1&&(d++,n(w,q<T?K:$,T,a))),T=w.length):u===0&&(d++,w=[0]),_[l++]=d,u&&w[0]?w[T++]=P[M]||0:(w=[P[M]],T=1);while((M++<v||w[0]!==void 0)&&A--);g=w[0]!==void 0}_[0]||_.shift()}if(y==1)S.e=f,y1=g;else{for(l=1,d=_[0];d>=10;d/=10)l++;S.e=l+f*y-1,be(S,c?s+S.e+1:s,o,g)}return S}})();function be(e,t,n,r){var i,s,o,c,a,u,f,l,d,y=e.constructor;e:if(t!=null){if(l=e.d,!l)return e;for(i=1,c=l[0];c>=10;c/=10)i++;if(s=t-i,s<0)s+=_e,o=t,f=l[d=0],a=f/At(10,i-o-1)%10|0;else if(d=Math.ceil((s+1)/_e),c=l.length,d>=c)if(r){for(;c++<=d;)l.push(0);f=a=0,i=1,s%=_e,o=s-_e+1}else break e;else{for(f=c=l[d],i=1;c>=10;c/=10)i++;s%=_e,o=s-_e+i,a=o<0?0:f/At(10,i-o-1)%10|0}if(r=r||t<0||l[d+1]!==void 0||(o<0?f:f%At(10,i-o-1)),u=n<4?(a||r)&&(n==0||n==(e.s<0?3:2)):a>5||a==5&&(n==4||r||n==6&&(s>0?o>0?f/At(10,i-o):0:l[d-1])%10&1||n==(e.s<0?8:7)),t<1||!l[0])return l.length=0,u?(t-=e.e+1,l[0]=At(10,(_e-t%_e)%_e),e.e=-t||0):l[0]=e.e=0,e;if(s==0?(l.length=d,c=1,d--):(l.length=d+1,c=At(10,_e-s),l[d]=o>0?(f/At(10,i-o)%At(10,o)|0)*c:0),u)for(;;)if(d==0){for(s=1,o=l[0];o>=10;o/=10)s++;for(o=l[0]+=c,c=1;o>=10;o/=10)c++;s!=c&&(e.e++,l[0]==jn&&(l[0]=1));break}else{if(l[d]+=c,l[d]!=jn)break;l[d--]=0,c=1}for(s=l.length;l[--s]===0;)l.pop()}return ve&&(e.e>y.maxE?(e.d=null,e.e=NaN):e.e<y.minE&&(e.e=0,e.d=[0])),e}function sr(e,t,n){if(!e.isFinite())return T1(e);var r,i=e.e,s=Ft(e.d),o=s.length;return t?(n&&(r=n-o)>0?s=s.charAt(0)+"."+s.slice(1)+si(r):o>1&&(s=s.charAt(0)+"."+s.slice(1)),s=s+(e.e<0?"e":"e+")+e.e):i<0?(s="0."+si(-i-1)+s,n&&(r=n-o)>0&&(s+=si(r))):i>=o?(s+=si(i+1-o),n&&(r=n-i-1)>0&&(s=s+"."+si(r))):((r=i+1)<o&&(s=s.slice(0,r)+"."+s.slice(r)),n&&(r=n-o)>0&&(i+1===o&&(s+="."),s+=si(r))),s}function xu(e,t){var n=e[0];for(t*=_e;n>=10;n/=10)t++;return t}function La(e,t,n){if(t>Qv)throw ve=!0,n&&(e.precision=n),Error(g1);return be(new e(Fa),t,1,!0)}function nr(e,t,n){if(t>_l)throw Error(g1);return be(new e(Ma),t,n,!0)}function E1(e){var t=e.length-1,n=t*_e+1;if(t=e[t],t){for(;t%10==0;t/=10)n--;for(t=e[0];t>=10;t/=10)n++}return n}function si(e){for(var t="";e--;)t+="0";return t}function _1(e,t,n,r){var i,s=new e(1),o=Math.ceil(r/_e+4);for(ve=!1;;){if(n%2&&(s=s.times(t),Oy(s.d,o)&&(i=!0)),n=Xt(n/2),n===0){n=s.d.length-1,i&&s.d[n]===0&&++s.d[n];break}t=t.times(t),Oy(t.d,o)}return ve=!0,s}function Iy(e){return e.d[e.d.length-1]&1}function S1(e,t,n){for(var r,i,s=new e(t[0]),o=0;++o<t.length;){if(i=new e(t[o]),!i.s){s=i;break}r=s.cmp(i),(r===n||r===0&&s.s===n)&&(s=i)}return s}function Sl(e,t){var n,r,i,s,o,c,a,u=0,f=0,l=0,d=e.constructor,y=d.rounding,g=d.precision;if(!e.d||!e.d[0]||e.e>17)return new d(e.d?e.d[0]?e.s<0?0:1/0:1:e.s?e.s<0?0:e:NaN);for(t==null?(ve=!1,a=g):a=t,c=new d(.03125);e.e>-2;)e=e.times(c),l+=5;for(r=Math.log(At(2,l))/Math.LN10*2+5|0,a+=r,n=s=o=new d(1),d.precision=a;;){if(s=be(s.times(e),a,1),n=n.times(++f),c=o.plus(Je(s,n,a,1)),Ft(c.d).slice(0,a)===Ft(o.d).slice(0,a)){for(i=l;i--;)o=be(o.times(o),a,1);if(t==null)if(u<3&&jo(o.d,a-r,y,u))d.precision=a+=10,n=s=c=new d(1),f=0,u++;else return be(o,d.precision=g,y,ve=!0);else return d.precision=g,o}o=c}}function oi(e,t){var n,r,i,s,o,c,a,u,f,l,d,y=1,g=10,m=e,E=m.d,S=m.constructor,_=S.rounding,w=S.precision;if(m.s<0||!E||!E[0]||!m.e&&E[0]==1&&E.length==1)return new S(E&&!E[0]?-1/0:m.s!=1?NaN:E?0:m);if(t==null?(ve=!1,f=w):f=t,S.precision=f+=g,n=Ft(E),r=n.charAt(0),Math.abs(s=m.e)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)m=m.times(e),n=Ft(m.d),r=n.charAt(0),y++;s=m.e,r>1?(m=new S("0."+n),s++):m=new S(r+"."+n.slice(1))}else return u=La(S,f+2,w).times(s+""),m=oi(new S(r+"."+n.slice(1)),f-g).plus(u),S.precision=w,t==null?be(m,w,_,ve=!0):m;for(l=m,a=o=m=Je(m.minus(1),m.plus(1),f,1),d=be(m.times(m),f,1),i=3;;){if(o=be(o.times(d),f,1),u=a.plus(Je(o,new S(i),f,1)),Ft(u.d).slice(0,f)===Ft(a.d).slice(0,f))if(a=a.times(2),s!==0&&(a=a.plus(La(S,f+2,w).times(s+""))),a=Je(a,new S(y),f,1),t==null)if(jo(a.d,f-g,_,c))S.precision=f+=g,u=o=m=Je(l.minus(1),l.plus(1),f,1),d=be(m.times(m),f,1),i=c=1;else return be(a,S.precision=w,_,ve=!0);else return S.precision=w,a;a=u,i+=2}}function T1(e){return String(e.s*e.s/0)}function ca(e,t){var n,r,i;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;r++);for(i=t.length;t.charCodeAt(i-1)===48;--i);if(t=t.slice(r,i),t){if(i-=r,e.e=n=n-r-1,e.d=[],r=(n+1)%_e,n<0&&(r+=_e),r<i){for(r&&e.d.push(+t.slice(0,r)),i-=_e;r<i;)e.d.push(+t.slice(r,r+=_e));t=t.slice(r),r=_e-t.length}else r-=i;for(;r--;)t+="0";e.d.push(+t),ve&&(e.e>e.constructor.maxE?(e.d=null,e.e=NaN):e.e<e.constructor.minE&&(e.e=0,e.d=[0]))}else e.e=0,e.d=[0];return e}function tI(e,t){var n,r,i,s,o,c,a,u,f;if(t.indexOf("_")>-1){if(t=t.replace(/(\d)_(?=\d)/g,"$1"),b1.test(t))return ca(e,t)}else if(t==="Infinity"||t==="NaN")return+t||(e.s=NaN),e.e=NaN,e.d=null,e;if(Yv.test(t))n=16,t=t.toLowerCase();else if(zv.test(t))n=2;else if(Zv.test(t))n=8;else throw Error(hi+t);for(s=t.search(/p/i),s>0?(a=+t.slice(s+1),t=t.substring(2,s)):t=t.slice(2),s=t.indexOf("."),o=s>=0,r=e.constructor,o&&(t=t.replace(".",""),c=t.length,s=c-s,i=_1(r,new r(n),s,s*2)),u=oa(t,n,jn),f=u.length-1,s=f;u[s]===0;--s)u.pop();return s<0?new r(e.s*0):(e.e=xu(u,f),e.d=u,ve=!1,o&&(e=Je(e,i,c*4)),a&&(e=e.times(Math.abs(a)<54?At(2,a):Er.pow(2,a))),ve=!0,e)}function nI(e,t){var n,r=t.d.length;if(r<3)return t.isZero()?t:Fs(e,2,t,t);n=1.4*Math.sqrt(r),n=n>16?16:n|0,t=t.times(1/Au(5,n)),t=Fs(e,2,t,t);for(var i,s=new e(5),o=new e(16),c=new e(20);n--;)i=t.times(t),t=t.times(s.plus(i.times(o.times(i).minus(c))));return t}function Fs(e,t,n,r,i){var s,o,c,a,u=e.precision,f=Math.ceil(u/_e);for(ve=!1,a=n.times(n),c=new e(r);;){if(o=Je(c.times(a),new e(t++*t++),u,1),c=i?r.plus(o):r.minus(o),r=Je(o.times(a),new e(t++*t++),u,1),o=c.plus(r),o.d[f]!==void 0){for(s=f;o.d[s]===c.d[s]&&s--;);if(s==-1)break}s=c,c=r,r=o,o=s}return ve=!0,o.d.length=f+1,o}function Au(e,t){for(var n=e;--t;)n*=e;return n}function x1(e,t){var n,r=t.s<0,i=nr(e,e.precision,1),s=i.times(.5);if(t=t.abs(),t.lte(s))return Ar=r?4:1,t;if(n=t.divToInt(i),n.isZero())Ar=r?3:2;else{if(t=t.minus(n.times(i)),t.lte(s))return Ar=Iy(n)?r?2:3:r?4:1,t;Ar=Iy(n)?r?1:4:r?3:2}return t.minus(i).abs()}function Ch(e,t,n,r){var i,s,o,c,a,u,f,l,d,y=e.constructor,g=n!==void 0;if(g?(yn(n,1,gi),r===void 0?r=y.rounding:yn(r,0,8)):(n=y.precision,r=y.rounding),!e.isFinite())f=T1(e);else{for(f=sr(e),o=f.indexOf("."),g?(i=2,t==16?n=n*4-3:t==8&&(n=n*3-2)):i=t,o>=0&&(f=f.replace(".",""),d=new y(1),d.e=f.length-o,d.d=oa(sr(d),10,i),d.e=d.d.length),l=oa(f,10,i),s=a=l.length;l[--a]==0;)l.pop();if(!l[0])f=g?"0p+0":"0";else{if(o<0?s--:(e=new y(e),e.d=l,e.e=s,e=Je(e,d,n,r,0,i),l=e.d,s=e.e,u=y1),o=l[n],c=i/2,u=u||l[n+1]!==void 0,u=r<4?(o!==void 0||u)&&(r===0||r===(e.s<0?3:2)):o>c||o===c&&(r===4||u||r===6&&l[n-1]&1||r===(e.s<0?8:7)),l.length=n,u)for(;++l[--n]>i-1;)l[n]=0,n||(++s,l.unshift(1));for(a=l.length;!l[a-1];--a);for(o=0,f="";o<a;o++)f+=bl.charAt(l[o]);if(g){if(a>1)if(t==16||t==8){for(o=t==16?4:3,--a;a%o;a++)f+="0";for(l=oa(f,i,t),a=l.length;!l[a-1];--a);for(o=1,f="1.";o<a;o++)f+=bl.charAt(l[o])}else f=f.charAt(0)+"."+f.slice(1);f=f+(s<0?"p":"p+")+s}else if(s<0){for(;++s;)f="0"+f;f="0."+f}else if(++s>a)for(s-=a;s--;)f+="0";else s<a&&(f=f.slice(0,s)+"."+f.slice(s))}f=(t==16?"0x":t==2?"0b":t==8?"0o":"")+f}return e.s<0?"-"+f:f}function Oy(e,t){if(e.length>t)return e.length=t,!0}function rI(e){return new this(e).abs()}function iI(e){return new this(e).acos()}function sI(e){return new this(e).acosh()}function oI(e,t){return new this(e).plus(t)}function cI(e){return new this(e).asin()}function aI(e){return new this(e).asinh()}function uI(e){return new this(e).atan()}function fI(e){return new this(e).atanh()}function lI(e,t){e=new this(e),t=new this(t);var n,r=this.precision,i=this.rounding,s=r+4;return!e.s||!t.s?n=new this(NaN):!e.d&&!t.d?(n=nr(this,s,1).times(t.s>0?.25:.75),n.s=e.s):!t.d||e.isZero()?(n=t.s<0?nr(this,r,i):new this(0),n.s=e.s):!e.d||t.isZero()?(n=nr(this,s,1).times(.5),n.s=e.s):t.s<0?(this.precision=s,this.rounding=1,n=this.atan(Je(e,t,s,1)),t=nr(this,s,1),this.precision=r,this.rounding=i,n=e.s<0?n.minus(t):n.plus(t)):n=this.atan(Je(e,t,s,1)),n}function hI(e){return new this(e).cbrt()}function dI(e){return be(e=new this(e),e.e+1,2)}function pI(e,t,n){return new this(e).clamp(t,n)}function yI(e){if(!e||typeof e!="object")throw Error(Tu+"Object expected");var t,n,r,i=e.defaults===!0,s=["precision",1,gi,"rounding",0,8,"toExpNeg",-ws,0,"toExpPos",0,ws,"maxE",0,ws,"minE",-ws,0,"modulo",0,9];for(t=0;t<s.length;t+=3)if(n=s[t],i&&(this[n]=El[n]),(r=e[n])!==void 0)if(Xt(r)===r&&r>=s[t+1]&&r<=s[t+2])this[n]=r;else throw Error(hi+n+": "+r);if(n="crypto",i&&(this[n]=El[n]),(r=e[n])!==void 0)if(r===!0||r===!1||r===0||r===1)if(r)if(typeof crypto<"u"&&crypto&&(crypto.getRandomValues||crypto.randomBytes))this[n]=!0;else throw Error(m1);else this[n]=!1;else throw Error(hi+n+": "+r);return this}function gI(e){return new this(e).cos()}function mI(e){return new this(e).cosh()}function A1(e){var t,n,r;function i(s){var o,c,a,u=this;if(!(u instanceof i))return new i(s);if(u.constructor=i,By(s)){u.s=s.s,ve?!s.d||s.e>i.maxE?(u.e=NaN,u.d=null):s.e<i.minE?(u.e=0,u.d=[0]):(u.e=s.e,u.d=s.d.slice()):(u.e=s.e,u.d=s.d?s.d.slice():s.d);return}if(a=typeof s,a==="number"){if(s===0){u.s=1/s<0?-1:1,u.e=0,u.d=[0];return}if(s<0?(s=-s,u.s=-1):u.s=1,s===~~s&&s<1e7){for(o=0,c=s;c>=10;c/=10)o++;ve?o>i.maxE?(u.e=NaN,u.d=null):o<i.minE?(u.e=0,u.d=[0]):(u.e=o,u.d=[s]):(u.e=o,u.d=[s]);return}if(s*0!==0){s||(u.s=NaN),u.e=NaN,u.d=null;return}return ca(u,s.toString())}if(a==="string")return(c=s.charCodeAt(0))===45?(s=s.slice(1),u.s=-1):(c===43&&(s=s.slice(1)),u.s=1),b1.test(s)?ca(u,s):tI(u,s);if(a==="bigint")return s<0?(s=-s,u.s=-1):u.s=1,ca(u,s.toString());throw Error(hi+s)}if(i.prototype=se,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.EUCLID=9,i.config=i.set=yI,i.clone=A1,i.isDecimal=By,i.abs=rI,i.acos=iI,i.acosh=sI,i.add=oI,i.asin=cI,i.asinh=aI,i.atan=uI,i.atanh=fI,i.atan2=lI,i.cbrt=hI,i.ceil=dI,i.clamp=pI,i.cos=gI,i.cosh=mI,i.div=wI,i.exp=bI,i.floor=EI,i.hypot=_I,i.ln=SI,i.log=TI,i.log10=AI,i.log2=xI,i.max=vI,i.min=II,i.mod=OI,i.mul=BI,i.pow=NI,i.random=kI,i.round=PI,i.sign=RI,i.sin=CI,i.sinh=UI,i.sqrt=HI,i.sub=FI,i.sum=MI,i.tan=LI,i.tanh=qI,i.trunc=VI,e===void 0&&(e={}),e&&e.defaults!==!0)for(r=["precision","rounding","toExpNeg","toExpPos","maxE","minE","modulo","crypto"],t=0;t<r.length;)e.hasOwnProperty(n=r[t++])||(e[n]=this[n]);return i.config(e),i}function wI(e,t){return new this(e).div(t)}function bI(e){return new this(e).exp()}function EI(e){return be(e=new this(e),e.e+1,3)}function _I(){var e,t,n=new this(0);for(ve=!1,e=0;e<arguments.length;)if(t=new this(arguments[e++]),t.d)n.d&&(n=n.plus(t.times(t)));else{if(t.s)return ve=!0,new this(1/0);n=t}return ve=!0,n.sqrt()}function By(e){return e instanceof Er||e&&e.toStringTag===w1||!1}function SI(e){return new this(e).ln()}function TI(e,t){return new this(e).log(t)}function xI(e){return new this(e).log(2)}function AI(e){return new this(e).log(10)}function vI(){return S1(this,arguments,-1)}function II(){return S1(this,arguments,1)}function OI(e,t){return new this(e).mod(t)}function BI(e,t){return new this(e).mul(t)}function NI(e,t){return new this(e).pow(t)}function kI(e){var t,n,r,i,s=0,o=new this(1),c=[];if(e===void 0?e=this.precision:yn(e,1,gi),r=Math.ceil(e/_e),this.crypto)if(crypto.getRandomValues)for(t=crypto.getRandomValues(new Uint32Array(r));s<r;)i=t[s],i>=429e7?t[s]=crypto.getRandomValues(new Uint32Array(1))[0]:c[s++]=i%1e7;else if(crypto.randomBytes){for(t=crypto.randomBytes(r*=4);s<r;)i=t[s]+(t[s+1]<<8)+(t[s+2]<<16)+((t[s+3]&127)<<24),i>=214e7?crypto.randomBytes(4).copy(t,s):(c.push(i%1e7),s+=4);s=r/4}else throw Error(m1);else for(;s<r;)c[s++]=Math.random()*1e7|0;for(r=c[--s],e%=_e,r&&e&&(i=At(10,_e-e),c[s]=(r/i|0)*i);c[s]===0;s--)c.pop();if(s<0)n=0,c=[0];else{for(n=-1;c[0]===0;n-=_e)c.shift();for(r=1,i=c[0];i>=10;i/=10)r++;r<_e&&(n-=_e-r)}return o.e=n,o.d=c,o}function PI(e){return be(e=new this(e),e.e+1,this.rounding)}function RI(e){return e=new this(e),e.d?e.d[0]?e.s:0*e.s:e.s||NaN}function CI(e){return new this(e).sin()}function UI(e){return new this(e).sinh()}function HI(e){return new this(e).sqrt()}function FI(e,t){return new this(e).sub(t)}function MI(){var e=0,t=arguments,n=new this(t[e]);for(ve=!1;n.s&&++e<t.length;)n=n.plus(t[e]);return ve=!0,be(n,this.precision,this.rounding)}function LI(e){return new this(e).tan()}function qI(e){return new this(e).tanh()}function VI(e){return be(e=new this(e),e.e+1,1)}se[Symbol.for("nodejs.util.inspect.custom")]=se.toString;se[Symbol.toStringTag]="Decimal";var Er=se.constructor=A1(El);Fa=new Er(Fa);Ma=new Er(Ma);const DI=({IDL:e})=>{const t=e.Variant({Ok:e.Null,Err:e.Text}),n=e.Variant({P2WPKH:e.Null,OpReturn:e.Nat64,P2SH:e.Null,P2TR:e.Null}),r=e.Record({input_types:e.Vec(n),pool_address:e.Vec(e.Text),output_types:e.Vec(n)}),i=e.Variant({Ok:e.Nat64,Err:e.Text}),s=e.Record({user_id:e.Principal}),o=e.Record({canister_version:e.Opt(e.Nat64),canister_id:e.Principal}),c=e.Variant({from_user:s,from_canister:o}),a=e.Record({controllers:e.Vec(e.Principal)}),u=e.Variant({reinstall:e.Null,upgrade:e.Null,install:e.Null}),f=e.Record({mode:u,module_hash:e.Vec(e.Nat8)}),l=e.Record({canister_version:e.Nat64,taken_at_timestamp:e.Nat64,snapshot_id:e.Vec(e.Nat8)}),d=e.Variant({creation:a,code_deployment:f,load_snapshot:l,controllers_change:a,code_uninstall:e.Null}),y=e.Record({timestamp_nanos:e.Nat64,canister_version:e.Nat64,origin:c,details:d}),g=e.Record({controllers:e.Vec(e.Principal),module_hash:e.Opt(e.Vec(e.Nat8)),recent_changes:e.Vec(y),total_num_changes:e.Nat64}),m=e.Variant({Ok:g,Err:e.Text}),E=e.Record({exchange_id:e.Text,pool_address:e.Text,pool_key:e.Text}),S=e.Variant({All:e.Null,ByTxid:e.Text,ByAddress:e.Text,BySecondsPassed:e.Nat64}),_=e.Variant({Ok:e.Text,Err:e.Text}),w=e.Record({result:_,exchange_id:e.Text,maybe_return_time:e.Opt(e.Text),calling_method:e.Text,calling_args:e.Text,pool_address:e.Text,calling_time:e.Text}),T=e.Record({rollback_results:e.Vec(e.Text),invoke_args:e.Text,invoke_time:e.Text,finalized_time:e.Opt(e.Text),confirmed_time:e.Opt(e.Text),execution_steps:e.Vec(w),processing_result:_,broadcasted_time:e.Opt(e.Text)}),O=e.Record({block_hash:e.Text,block_height:e.Nat32}),A=e.Record({processing_results:e.Vec(e.Text),block_basic:O,txids:e.Vec(e.Text),block_time:e.Text,received_time:e.Text}),R=e.Variant({Active:e.Null,Halted:e.Record({reason:e.Text})}),M=e.Record({status:R,exchange_id:e.Text,canister_id:e.Principal,client_canisters:e.Vec(e.Principal)}),v=e.Record({rollback_results:e.Vec(e.Text),txid:e.Text,received_time:e.Text,reason:e.Text}),C=e.Variant({mainnet:e.Null,regtest:e.Null,testnet:e.Null}),q=e.Record({exchange_registry_principal:e.Principal,max_input_count_of_psbt:e.Nat32,min_tx_confirmations:e.Nat32,mempool_connector_principal:e.Principal,max_unconfirmed_tx_count_in_pool:e.Nat32,min_btc_amount_for_utxo:e.Nat64,rune_indexer_principal:e.Principal,max_intentions_per_invoke:e.Nat32,max_received_blocks_count:e.Nat32,bitcoin_network:C}),K=e.Record({low:e.Nat64,high:e.Nat64,update_time:e.Text,medium:e.Nat64}),H=e.Variant({Enabled:e.Null,Disabled:e.Null,AllowEmpty:e.Null}),D=e.Record({last_block:e.Opt(O),pending_tx_count:e.Nat64,mempool_tx_fee_rate:K,invoke_paused:e.Bool,utxo_proof_verification_status:H}),P=e.Variant({Confirmed:e.Nat32,Rejected:e.Text,Pending:e.Null}),$=e.Record({status:e.Opt(P),invoke_log:T,included_block:e.Opt(O),sent_tx_hex:e.Text}),F=e.Record({id:e.Text,value:e.Nat}),x=e.Record({maybe_rune:e.Opt(F),value:e.Nat64,script_pubkey_hex:e.Text,outpoint:e.Text}),B=e.Record({coin:F,from:e.Text}),L=e.Record({to:e.Text,coin:F}),N=e.Record({coins:e.Vec(F),sats:e.Nat64,txid:e.Text,vout:e.Nat32}),V=e.Record({input_coins:e.Vec(B),output_coins:e.Vec(L),action:e.Text,exchange_id:e.Text,pool_utxo_spent:e.Vec(e.Text),action_params:e.Text,nonce:e.Nat64,pool_address:e.Text,pool_utxo_received:e.Vec(N)}),G=e.Record({tx_fee_in_sats:e.Nat64,initiator_address:e.Text,intentions:e.Vec(V)}),X=e.Record({intention_set:G,initiator_utxo_proof:e.Vec(e.Nat8),psbt_hex:e.Text}),Y=e.Record({block_hash:e.Text,block_timestamp:e.Nat64,tx_ids:e.Vec(e.Text),block_height:e.Nat32}),ce=e.Variant({Ok:e.Vec(e.Text),Err:e.Text}),ue=e.Record({exchange_canister:e.Principal,exchange_id:e.Text,client_canisters:e.Vec(e.Principal)}),te=e.Record({txid:e.Text,timestamp:e.Nat64,block:O}),Z=e.Record({low:e.Nat64,high:e.Nat64,medium:e.Nat64});return e.Service({clear_failed_invoke_logs:e.Func([e.Opt(e.Nat64),e.Vec(e.Text)],[t],[]),estimate_min_tx_fee:e.Func([r],[i],["query"]),get_canister_info:e.Func([e.Nat64],[m],[]),get_exchange_pools:e.Func([],[e.Vec(E)],["query"]),get_failed_invoke_logs:e.Func([S],[e.Vec(e.Tuple(e.Text,T))],["query"]),get_last_sent_txs:e.Func([e.Opt(e.Nat32)],[e.Vec(e.Tuple(e.Text,e.Text,e.Opt(e.Nat32)))],["query"]),get_received_blocks:e.Func([e.Opt(e.Bool)],[e.Vec(A)],["query"]),get_registered_exchanges:e.Func([],[e.Vec(M)],["query"]),get_rejected_txs:e.Func([e.Opt(e.Nat32)],[e.Vec(v)],["query"]),get_settings:e.Func([],[q],["query"]),get_status:e.Func([],[D],["query"]),get_tx_for_outpoint:e.Func([e.Text],[e.Opt($)],["query"]),get_tx_queue_of_pool:e.Func([e.Text],[e.Vec(e.Tuple(e.Text,e.Opt(e.Nat32)))],["query"]),get_tx_sent:e.Func([e.Text],[e.Opt($)],["query"]),get_used_outpoints:e.Func([e.Opt(e.Text)],[e.Vec(e.Tuple(e.Text,e.Text))],["query"]),get_zero_confirmed_tx_count_of_pool:e.Func([e.Text],[e.Nat32],["query"]),get_zero_confirmed_txs:e.Func([e.Opt(e.Text)],[e.Vec(e.Text)],["query"]),get_zero_confirmed_utxos_of_address:e.Func([e.Text],[e.Vec(x)],["query"]),invoke:e.Func([X],[_],[]),new_block_detected:e.Func([Y],[t],[]),notify_exchange_for_blocks_from_height:e.Func([e.Text,e.Nat32],[ce],[]),register_exchange:e.Func([ue],[t],[]),save_included_block_for_tx:e.Func([te],[t],[]),set_max_input_count_of_psbt:e.Func([e.Nat32],[t],[]),set_max_intentions_per_invoke:e.Func([e.Nat32],[t],[]),set_max_received_blocks_count:e.Func([e.Nat32],[t],[]),set_max_unconfirmed_tx_count_in_pool:e.Func([e.Nat32],[t],[]),set_min_btc_amount_for_utxo:e.Func([e.Nat64],[t],[]),set_min_tx_confirmations:e.Func([e.Nat32],[t],[]),set_tx_fee_per_vbyte:e.Func([Z],[t],[]),update_bitcoin_subnet_certificate:e.Func([e.Vec(e.Nat8)],[],[]),version:e.Func([],[e.Text],["query"])})};class v1{maestro;config;exchange;orchestrator;constructor(t){this.config=t;const n=t.network===Ns.Testnet,r=n?"https://xbt-testnet.gomaestro-api.org/v0":"https://xbt-mainnet.gomaestro-api.org/v0";this.maestro=new rx({baseUrl:r,apiKey:t.maestroApiKey});const i="https://icp0.io";this.exchange=Ha.createActor(t.exchangeIdlFactory,{agent:xr.createSync({host:i,retryTimes:50,verifyQuerySignatures:!1}),canisterId:t.exchangeCanisterId}),this.orchestrator=Ha.createActor(DI,{agent:xr.createSync({host:i,retryTimes:50,verifyQuerySignatures:!1}),canisterId:n?VA:qA})}async filterSpentUtxos(t,n){const r=await this.orchestrator.get_used_outpoints([t]);return n.filter(({txid:i,vout:s})=>r.findIndex(([o])=>`${i}:${s}`===o)<0)}async getBtcUtxos(t,n=!0){let r=null;const i=[];do{const o=await this.maestro.utxosByAddress(t,r,n);i.push(...o.data),r=o.next_cursor}while(r!==null);const s=i.map(({txid:o,vout:c,runes:a,satoshis:u,script_pubkey:f,address:l})=>({txid:o,vout:c,address:l,runes:a.map(({rune_id:d,amount:y})=>{const g=(y.split(".")[1]??"").length,m=new Er(y).mul(10**g).toFixed(0);return{id:d,amount:m}}),satoshis:u,scriptPk:f}));return this.filterSpentUtxos(t,s)}async getRuneUtxos(t,n){let r=null;const i=[];do{const o=await this.maestro.runeUtxosByAddress(t,n,r);i.push(...o.data),r=o.next_cursor}while(r!==null);const s=i.map(({txid:o,vout:c,runes:a,satoshis:u})=>{const f=Bh(t,this.config.network);return{txid:o,vout:c,address:t,runes:a.map(({rune_id:l,amount:d})=>{const y=(d.split(".")[1]??"").length,g=new Er(d).mul(10**y).toFixed(0);return{id:l,amount:g}}),satoshis:u,scriptPk:Ih(f)}});return this.filterSpentUtxos(t,s)}async searchRunes(t){const n=this.config.network===Ns.Testnet?$A:DA,r=Xv`
133
133
  query GetRunes($keyword: String!, $regex: String!) {
134
134
  runes(
135
135
  where: {
@@ -149,4 +149,4 @@ ${String(e)}`)}catch(t){return t}},xy=e=>{if(typeof e!="object"||e===null)throw
149
149
  divisibility
150
150
  }
151
151
  }
152
- `,i=new Gv(n),s=t.split("").filter(c=>!(c==="•"||c===" ")).join("•?"),{runes:o}=await i.request(r,{keyword:t,regex:`(?i)${s}`});return o.map(({rune_id:c,spaced_rune:a,symbol:u,divisibility:f,etching:l})=>({runeId:c,spacedRune:a,symbol:u,divisibility:f,etching:l}))}async getRuneInfo(t){return(await this.searchRunes(t))[0]}async getBtcBalance(t){const r=(await this.getBtcUtxos(t)).reduce((i,s)=>i+BigInt(s.satoshis),BigInt(0));return new Er(r.toString()).div(1e8).toNumber()}async getRuneBalance(t,n){const r=await this.getRuneUtxos(t,n);if(!r)return;let i=new Er(0);for(const s of r)i=i.add(new Er(s.runes.find(o=>o.id===n)?.amount??0));return i.toNumber()}async getPoolList(){try{return await this.exchange.get_pool_list()??[]}catch(t){throw console.error("get pool list failed:",t),t}}async getPoolInfo(t){try{const n=await this.exchange.get_pool_info({pool_address:t});if(n.length===0)throw new Error("Pool not found");return n[0]}catch(n){throw console.error("get pool data failed:",n),n}}async createTransaction({address:t,paymentAddress:n}){return new t1({network:this.config.network,exchangeId:this.config.exchangeId,address:t,paymentAddress:n},this)}}const I1=Ae.createContext(null);function $I({children:e,config:t}){if(!t)throw new Error("ReeProvider: config is required");if(!t.network)throw new Error("ReeProvider: config.network is required");if(!t.maestroApiKey)throw new Error("ReeProvider: config.maestroApiKey is required");if(!t.exchangeIdlFactory)throw new Error("ReeProvider: config.exchangeIdlFactory is required");if(!t.exchangeCanisterId)throw new Error("ReeProvider: config.exchangeCanisterId is required");const[n,r]=Ae.useState({address:"",paymentAddress:"",publicKey:"",paymentPublicKey:""}),i=Ae.useCallback(a=>{r(u=>({...u,...a}))},[]),s=Ae.useMemo(()=>new v1(t),[t]),o=Ae.useCallback(async()=>{if(!s)throw new Error("Client not available");if(!n.address||!n.paymentAddress)throw new Error("Wallet not connected");return s.createTransaction({address:n.address,paymentAddress:n.paymentAddress})},[s,n]),c=Ae.useMemo(()=>({client:s,...n,exchange:s.exchange,updateWallet:i,createTransaction:o}),[s,n,i,o]);return O1.jsx(I1.Provider,{value:c,children:e})}function Cr(){const e=Ae.useContext(I1);if(!e)throw new Error("useRee must be used within ReeProvider");return e}function jI(e={}){const{refreshInterval:t=0,autoRefresh:n=!0}=e,{client:r,paymentAddress:i}=Cr(),[s,o]=Ae.useState(null),[c,a]=Ae.useState(!1),[u,f]=Ae.useState(null),l=Ae.useCallback(async()=>{if(!i){o(null),f("Payment address not set");return}a(!0),f(null);try{const d=await r.getBtcBalance(i);o(d)}catch(d){f(d instanceof Error?d.message:"Failed to fetch BTC balance"),o(null)}finally{a(!1)}},[r,i]);return Ae.useEffect(()=>{n&&l()},[i,l,n]),Ae.useEffect(()=>{if(t>0){const d=setInterval(l,t);return()=>clearInterval(d)}},[t,i,l]),{balance:s,loading:c,error:u,refetch:l}}function KI(e,t={}){const{refreshInterval:n=0,autoRefresh:r=!0}=t,{client:i,address:s}=Cr(),[o,c]=Ae.useState(null),[a,u]=Ae.useState(!1),[f,l]=Ae.useState(null),d=Ae.useCallback(async()=>{if(!s){c(null),l("Address not set");return}if(!e){c(null),l("Rune ID is required");return}u(!0),l(null);try{const y=await i.getRuneBalance(s,e);c(y??null)}catch(y){l(y instanceof Error?y.message:"Failed to fetch rune balance"),c(null)}finally{u(!1)}},[i,s,e]);return Ae.useEffect(()=>{r&&e&&d()},[s,e,d,r]),Ae.useEffect(()=>{if(n>0&&e){const y=setInterval(d,n);return()=>clearInterval(y)}},[n,s,e,d]),{balance:o,loading:a,error:f,refetch:d}}function GI(e={}){const{refreshInterval:t=0,autoRefresh:n=!0}=e,{client:r,paymentAddress:i}=Cr(),[s,o]=Ae.useState([]),[c,a]=Ae.useState(!1),[u,f]=Ae.useState(null),l=Ae.useCallback(async()=>{if(!i){o([]),f("Payment address not set");return}a(!0),f(null);try{const d=await r.getBtcUtxos(i);o(d)}catch(d){f(d instanceof Error?d.message:"Failed to fetch BTC UTXOs"),o([])}finally{a(!1)}},[r,i]);return Ae.useEffect(()=>{n&&i&&l()},[i,l,n]),Ae.useEffect(()=>{if(t>0&&i){const d=setInterval(l,t);return()=>clearInterval(d)}},[t,i,l]),{utxos:s,loading:c,error:u,refetch:l}}function WI(e,t={}){const{refreshInterval:n=0,autoRefresh:r=!0}=t,{client:i,address:s}=Cr(),[o,c]=Ae.useState([]),[a,u]=Ae.useState(!1),[f,l]=Ae.useState(null),d=Ae.useCallback(async()=>{if(!s){c([]),l("Address not set");return}if(!e){c([]),l("Rune ID is required");return}u(!0),l(null);try{const y=await i.getRuneUtxos(s,e);c(y)}catch(y){l(y instanceof Error?y.message:"Failed to fetch rune UTXOs"),c([])}finally{u(!1)}},[i,s,e]);return Ae.useEffect(()=>{r&&s&&e&&d()},[s,e,d,r]),Ae.useEffect(()=>{if(n>0&&s&&e){const y=setInterval(d,n);return()=>clearInterval(y)}},[n,s,e,d]),{utxos:o,loading:a,error:f,refetch:d}}function XI(){const{client:e}=Cr();return Ae.useCallback(async n=>{const r=n;if(!r)throw new Error("Search keyword is required");return await e.searchRunes(r)},[e])}function zI(e){const{client:t}=Cr(),[n,r]=Ae.useState(null),[i,s]=Ae.useState(!1),[o,c]=Ae.useState(null),a=Ae.useCallback(async()=>{if(!e){r(null),c("Rune ID is required");return}s(!0),c(null);try{const u=await t.getRuneInfo(e);r(u||null)}catch(u){c(u instanceof Error?u.message:"Failed to fetch rune info"),r(null)}finally{s(!1)}},[t,e]);return{runeInfo:n,loading:i,error:o,refetch:a}}function YI(){const{client:e}=Cr(),[t,n]=Ae.useState([]),[r,i]=Ae.useState(!1),[s,o]=Ae.useState(null),c=Ae.useCallback(async()=>{i(!0),o(null);try{const a=await e.getPoolList();n(a)}catch(a){o(a instanceof Error?a.message:"Failed to fetch pool list"),n([])}finally{i(!1)}},[e]);return Ae.useEffect(()=>{c()},[c]),{pools:t,loading:r,error:s,refetch:c}}function ZI(e){const{client:t}=Cr(),[n,r]=Ae.useState(null),[i,s]=Ae.useState(!1),[o,c]=Ae.useState(null),a=Ae.useCallback(async()=>{if(!e){r(null),c("Pool address is required");return}s(!0),c(null);try{const u=await t.getPoolInfo(e);r(u)}catch(u){c(u instanceof Error?u.message:"Failed to fetch pool info"),r(null)}finally{s(!1)}},[t,e]);return Ae.useEffect(()=>{a()},[e]),{poolInfo:n,loading:i,error:o,refetch:a}}exports.Network=Bs;exports.ReeClient=v1;exports.ReeProvider=$I;exports.Transaction=t1;exports.useBtcBalance=jI;exports.useBtcUtxos=GI;exports.usePoolInfo=ZI;exports.usePoolList=YI;exports.useRee=Cr;exports.useRuneBalance=KI;exports.useRuneInfo=zI;exports.useRuneUtxos=WI;exports.useSearchRunes=XI;exports.utils=LA;
152
+ `,i=new Gv(n),s=t.split("").filter(c=>!(c==="•"||c===" ")).join("•?"),{runes:o}=await i.request(r,{keyword:t,regex:`(?i)${s}`});return o.map(({rune_id:c,spaced_rune:a,symbol:u,divisibility:f,etching:l})=>({runeId:c,spacedRune:a,symbol:u,divisibility:f,etching:l}))}async getRuneInfo(t){return(await this.searchRunes(t))[0]}async getBtcBalance(t){const r=(await this.getBtcUtxos(t)).reduce((i,s)=>i+BigInt(s.satoshis),BigInt(0));return new Er(r.toString()).div(1e8).toNumber()}async getRuneBalance(t,n){const r=await this.getRuneUtxos(t,n);if(!r)return;let i=new Er(0);for(const s of r)i=i.add(new Er(s.runes.find(o=>o.id===n)?.amount??0));return i.toNumber()}async getPoolList(){try{return await this.exchange.get_pool_list()??[]}catch(t){throw console.error("get pool list failed:",t),t}}async getPoolInfo(t){try{const n=await this.exchange.get_pool_info({pool_address:t});if(n.length===0)throw new Error("Pool not found");return n[0]}catch(n){throw console.error("get pool data failed:",n),n}}async createTransaction({address:t,paymentAddress:n}){return new t1({network:this.config.network,exchangeId:this.config.exchangeId,address:t,paymentAddress:n},this)}}const I1=Ae.createContext(null);function $I({children:e,config:t}){if(!t)throw new Error("ReeProvider: config is required");if(!t.network)throw new Error("ReeProvider: config.network is required");if(!t.maestroApiKey)throw new Error("ReeProvider: config.maestroApiKey is required");if(!t.exchangeIdlFactory)throw new Error("ReeProvider: config.exchangeIdlFactory is required");if(!t.exchangeCanisterId)throw new Error("ReeProvider: config.exchangeCanisterId is required");const[n,r]=Ae.useState({address:"",paymentAddress:"",publicKey:"",paymentPublicKey:""}),i=Ae.useCallback(a=>{r(u=>({...u,...a}))},[]),s=Ae.useMemo(()=>new v1(t),[t]),o=Ae.useCallback(async()=>{if(!s)throw new Error("Client not available");if(!n.address||!n.paymentAddress)throw new Error("Wallet not connected");return s.createTransaction({address:n.address,paymentAddress:n.paymentAddress})},[s,n]),c=Ae.useMemo(()=>({client:s,...n,exchange:s.exchange,updateWallet:i,createTransaction:o}),[s,n,i,o]);return O1.jsx(I1.Provider,{value:c,children:e})}function Cr(){const e=Ae.useContext(I1);if(!e)throw new Error("useRee must be used within ReeProvider");return e}function jI(e={}){const{refreshInterval:t=0,autoRefresh:n=!0}=e,{client:r,paymentAddress:i}=Cr(),[s,o]=Ae.useState(null),[c,a]=Ae.useState(!1),[u,f]=Ae.useState(null),l=Ae.useCallback(async()=>{if(!i){o(null),f("Payment address not set");return}a(!0),f(null);try{const d=await r.getBtcBalance(i);o(d)}catch(d){f(d instanceof Error?d.message:"Failed to fetch BTC balance"),o(null)}finally{a(!1)}},[r,i]);return Ae.useEffect(()=>{n&&l()},[i,l,n]),Ae.useEffect(()=>{if(t>0){const d=setInterval(l,t);return()=>clearInterval(d)}},[t,i,l]),{balance:s,loading:c,error:u,refetch:l}}function KI(e,t={}){const{refreshInterval:n=0,autoRefresh:r=!0}=t,{client:i,address:s}=Cr(),[o,c]=Ae.useState(null),[a,u]=Ae.useState(!1),[f,l]=Ae.useState(null),d=Ae.useCallback(async()=>{if(!s){c(null),l("Address not set");return}if(!e){c(null),l("Rune ID is required");return}u(!0),l(null);try{const y=await i.getRuneBalance(s,e);c(y??null)}catch(y){l(y instanceof Error?y.message:"Failed to fetch rune balance"),c(null)}finally{u(!1)}},[i,s,e]);return Ae.useEffect(()=>{r&&e&&d()},[s,e,d,r]),Ae.useEffect(()=>{if(n>0&&e){const y=setInterval(d,n);return()=>clearInterval(y)}},[n,s,e,d]),{balance:o,loading:a,error:f,refetch:d}}function GI(e={}){const{refreshInterval:t=0,autoRefresh:n=!0}=e,{client:r,paymentAddress:i}=Cr(),[s,o]=Ae.useState([]),[c,a]=Ae.useState(!1),[u,f]=Ae.useState(null),l=Ae.useCallback(async()=>{if(!i){o([]),f("Payment address not set");return}a(!0),f(null);try{const d=await r.getBtcUtxos(i);o(d)}catch(d){f(d instanceof Error?d.message:"Failed to fetch BTC UTXOs"),o([])}finally{a(!1)}},[r,i]);return Ae.useEffect(()=>{n&&i&&l()},[i,l,n]),Ae.useEffect(()=>{if(t>0&&i){const d=setInterval(l,t);return()=>clearInterval(d)}},[t,i,l]),{utxos:s,loading:c,error:u,refetch:l}}function WI(e,t={}){const{refreshInterval:n=0,autoRefresh:r=!0}=t,{client:i,address:s}=Cr(),[o,c]=Ae.useState([]),[a,u]=Ae.useState(!1),[f,l]=Ae.useState(null),d=Ae.useCallback(async()=>{if(!s){c([]),l("Address not set");return}if(!e){c([]),l("Rune ID is required");return}u(!0),l(null);try{const y=await i.getRuneUtxos(s,e);c(y)}catch(y){l(y instanceof Error?y.message:"Failed to fetch rune UTXOs"),c([])}finally{u(!1)}},[i,s,e]);return Ae.useEffect(()=>{r&&s&&e&&d()},[s,e,d,r]),Ae.useEffect(()=>{if(n>0&&s&&e){const y=setInterval(d,n);return()=>clearInterval(y)}},[n,s,e,d]),{utxos:o,loading:a,error:f,refetch:d}}function XI(){const{client:e}=Cr();return Ae.useCallback(async n=>{const r=n;if(!r)throw new Error("Search keyword is required");return await e.searchRunes(r)},[e])}function zI(e){const{client:t}=Cr(),[n,r]=Ae.useState(null),[i,s]=Ae.useState(!1),[o,c]=Ae.useState(null),a=Ae.useCallback(async()=>{if(!e){r(null),c("Rune ID is required");return}s(!0),c(null);try{const u=await t.getRuneInfo(e);r(u||null)}catch(u){c(u instanceof Error?u.message:"Failed to fetch rune info"),r(null)}finally{s(!1)}},[t,e]);return{runeInfo:n,loading:i,error:o,refetch:a}}function YI(){const{client:e}=Cr(),[t,n]=Ae.useState([]),[r,i]=Ae.useState(!1),[s,o]=Ae.useState(null),c=Ae.useCallback(async()=>{i(!0),o(null);try{const a=await e.getPoolList();n(a)}catch(a){o(a instanceof Error?a.message:"Failed to fetch pool list"),n([])}finally{i(!1)}},[e]);return Ae.useEffect(()=>{c()},[c]),{pools:t,loading:r,error:s,refetch:c}}function ZI(e){const{client:t}=Cr(),[n,r]=Ae.useState(null),[i,s]=Ae.useState(!1),[o,c]=Ae.useState(null),a=Ae.useCallback(async()=>{if(!e){r(null),c("Pool address is required");return}s(!0),c(null);try{const u=await t.getPoolInfo(e);r(u)}catch(u){c(u instanceof Error?u.message:"Failed to fetch pool info"),r(null)}finally{s(!1)}},[t,e]);return Ae.useEffect(()=>{a()},[e]),{poolInfo:n,loading:i,error:o,refetch:a}}exports.Network=Ns;exports.ReeClient=v1;exports.ReeProvider=$I;exports.Transaction=t1;exports.useBtcBalance=jI;exports.useBtcUtxos=GI;exports.usePoolInfo=ZI;exports.usePoolList=YI;exports.useRee=Cr;exports.useRuneBalance=KI;exports.useRuneInfo=zI;exports.useRuneUtxos=WI;exports.useSearchRunes=XI;exports.utils=LA;